gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Fix several doxygen warnings
0 16 0
default
16 files changed:
↑ Collapse diff ↑
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
/// \ingroup demos
20 20
/// \file
21 21
/// \brief Demo of the graph drawing function \ref graphToEps()
22 22
///
23 23
/// This demo program shows examples how to use the function \ref
24 24
/// graphToEps(). It takes no input but simply creates seven
25 25
/// <tt>.eps</tt> files demonstrating the capability of \ref
26 26
/// graphToEps(), and showing how to draw directed graphs,
27 27
/// how to handle parallel egdes, how to change the properties (like
28 28
/// color, shape, size, title etc.) of nodes and arcs individually
29
/// using appropriate \ref maps-page "graph maps".
29
/// using appropriate graph maps.
30 30
///
31 31
/// \include graph_to_eps_demo.cc
32 32

	
33 33
#include<lemon/list_graph.h>
34 34
#include<lemon/graph_to_eps.h>
35 35
#include<lemon/math.h>
36 36

	
37 37
using namespace std;
38 38
using namespace lemon;
39 39

	
40 40
int main()
41 41
{
42 42
  Palette palette;
43 43
  Palette paletteW(true);
44 44

	
45 45
  // Create a small digraph
46 46
  ListDigraph g;
47 47
  typedef ListDigraph::Node Node;
48 48
  typedef ListDigraph::NodeIt NodeIt;
49 49
  typedef ListDigraph::Arc Arc;
50 50
  typedef dim2::Point<int> Point;
51 51

	
52 52
  Node n1=g.addNode();
53 53
  Node n2=g.addNode();
54 54
  Node n3=g.addNode();
55 55
  Node n4=g.addNode();
56 56
  Node n5=g.addNode();
57 57

	
58 58
  ListDigraph::NodeMap<Point> coords(g);
59 59
  ListDigraph::NodeMap<double> sizes(g);
60 60
  ListDigraph::NodeMap<int> colors(g);
61 61
  ListDigraph::NodeMap<int> shapes(g);
62 62
  ListDigraph::ArcMap<int> acolors(g);
63 63
  ListDigraph::ArcMap<int> widths(g);
64 64

	
65 65
  coords[n1]=Point(50,50);  sizes[n1]=1; colors[n1]=1; shapes[n1]=0;
66 66
  coords[n2]=Point(50,70);  sizes[n2]=2; colors[n2]=2; shapes[n2]=2;
67 67
  coords[n3]=Point(70,70);  sizes[n3]=1; colors[n3]=3; shapes[n3]=0;
68 68
  coords[n4]=Point(70,50);  sizes[n4]=2; colors[n4]=4; shapes[n4]=1;
69 69
  coords[n5]=Point(85,60);  sizes[n5]=3; colors[n5]=5; shapes[n5]=2;
70 70

	
71 71
  Arc a;
72 72

	
73 73
  a=g.addArc(n1,n2); acolors[a]=0; widths[a]=1;
74 74
  a=g.addArc(n2,n3); acolors[a]=0; widths[a]=1;
75 75
  a=g.addArc(n3,n5); acolors[a]=0; widths[a]=3;
76 76
  a=g.addArc(n5,n4); acolors[a]=0; widths[a]=1;
77 77
  a=g.addArc(n4,n1); acolors[a]=0; widths[a]=1;
78 78
  a=g.addArc(n2,n4); acolors[a]=1; widths[a]=2;
79 79
  a=g.addArc(n3,n4); acolors[a]=2; widths[a]=1;
80 80

	
81 81
  IdMap<ListDigraph,Node> id(g);
82 82

	
83 83
  // Create .eps files showing the digraph with different options
84 84
  cout << "Create 'graph_to_eps_demo_out_1_pure.eps'" << endl;
85 85
  graphToEps(g,"graph_to_eps_demo_out_1_pure.eps").
86 86
    coords(coords).
87 87
    title("Sample .eps figure").
88 88
    copyright("(C) 2003-2008 LEMON Project").
89 89
    run();
90 90

	
91 91
  cout << "Create 'graph_to_eps_demo_out_2.eps'" << endl;
92 92
  graphToEps(g,"graph_to_eps_demo_out_2.eps").
93 93
    coords(coords).
94 94
    title("Sample .eps figure").
95 95
    copyright("(C) 2003-2008 LEMON Project").
96 96
    absoluteNodeSizes().absoluteArcWidths().
97 97
    nodeScale(2).nodeSizes(sizes).
98 98
    nodeShapes(shapes).
99 99
    nodeColors(composeMap(palette,colors)).
100 100
    arcColors(composeMap(palette,acolors)).
101 101
    arcWidthScale(.4).arcWidths(widths).
102 102
    nodeTexts(id).nodeTextSize(3).
103 103
    run();
104 104

	
105 105
  cout << "Create 'graph_to_eps_demo_out_3_arr.eps'" << endl;
106 106
  graphToEps(g,"graph_to_eps_demo_out_3_arr.eps").
107 107
    title("Sample .eps figure (with arrowheads)").
108 108
    copyright("(C) 2003-2008 LEMON Project").
109 109
    absoluteNodeSizes().absoluteArcWidths().
110 110
    nodeColors(composeMap(palette,colors)).
111 111
    coords(coords).
112 112
    nodeScale(2).nodeSizes(sizes).
113 113
    nodeShapes(shapes).
114 114
    arcColors(composeMap(palette,acolors)).
115 115
    arcWidthScale(.4).arcWidths(widths).
116 116
    nodeTexts(id).nodeTextSize(3).
117 117
    drawArrows().arrowWidth(2).arrowLength(2).
118 118
    run();
119 119

	
120 120
  // Add more arcs to the digraph
121 121
  a=g.addArc(n1,n4); acolors[a]=2; widths[a]=1;
122 122
  a=g.addArc(n4,n1); acolors[a]=1; widths[a]=2;
123 123

	
124 124
  a=g.addArc(n1,n2); acolors[a]=1; widths[a]=1;
125 125
  a=g.addArc(n1,n2); acolors[a]=2; widths[a]=1;
126 126
  a=g.addArc(n1,n2); acolors[a]=3; widths[a]=1;
127 127
  a=g.addArc(n1,n2); acolors[a]=4; widths[a]=1;
128 128
  a=g.addArc(n1,n2); acolors[a]=5; widths[a]=1;
129 129
  a=g.addArc(n1,n2); acolors[a]=6; widths[a]=1;
130 130
  a=g.addArc(n1,n2); acolors[a]=7; widths[a]=1;
131 131

	
132 132
  cout << "Create 'graph_to_eps_demo_out_4_par.eps'" << endl;
133 133
  graphToEps(g,"graph_to_eps_demo_out_4_par.eps").
134 134
    title("Sample .eps figure (parallel arcs)").
135 135
    copyright("(C) 2003-2008 LEMON Project").
136 136
    absoluteNodeSizes().absoluteArcWidths().
137 137
    nodeShapes(shapes).
138 138
    coords(coords).
139 139
    nodeScale(2).nodeSizes(sizes).
140 140
    nodeColors(composeMap(palette,colors)).
141 141
    arcColors(composeMap(palette,acolors)).
142 142
    arcWidthScale(.4).arcWidths(widths).
143 143
    nodeTexts(id).nodeTextSize(3).
144 144
    enableParallel().parArcDist(1.5).
145 145
    run();
146 146

	
147 147
  cout << "Create 'graph_to_eps_demo_out_5_par_arr.eps'" << endl;
148 148
  graphToEps(g,"graph_to_eps_demo_out_5_par_arr.eps").
149 149
    title("Sample .eps figure (parallel arcs and arrowheads)").
150 150
    copyright("(C) 2003-2008 LEMON Project").
151 151
    absoluteNodeSizes().absoluteArcWidths().
152 152
    nodeScale(2).nodeSizes(sizes).
153 153
    coords(coords).
154 154
    nodeShapes(shapes).
155 155
    nodeColors(composeMap(palette,colors)).
156 156
    arcColors(composeMap(palette,acolors)).
157 157
    arcWidthScale(.3).arcWidths(widths).
158 158
    nodeTexts(id).nodeTextSize(3).
159 159
    enableParallel().parArcDist(1).
160 160
    drawArrows().arrowWidth(1).arrowLength(1).
161 161
    run();
162 162

	
163 163
  cout << "Create 'graph_to_eps_demo_out_6_par_arr_a4.eps'" << endl;
164 164
  graphToEps(g,"graph_to_eps_demo_out_6_par_arr_a4.eps").
165 165
    title("Sample .eps figure (fits to A4)").
166 166
    copyright("(C) 2003-2008 LEMON Project").
167 167
    scaleToA4().
168 168
    absoluteNodeSizes().absoluteArcWidths().
169 169
    nodeScale(2).nodeSizes(sizes).
170 170
    coords(coords).
171 171
    nodeShapes(shapes).
172 172
    nodeColors(composeMap(palette,colors)).
173 173
    arcColors(composeMap(palette,acolors)).
174 174
    arcWidthScale(.3).arcWidths(widths).
175 175
    nodeTexts(id).nodeTextSize(3).
176 176
    enableParallel().parArcDist(1).
177 177
    drawArrows().arrowWidth(1).arrowLength(1).
178 178
    run();
179 179

	
180 180
  // Create an .eps file showing the colors of a default Palette
181 181
  ListDigraph h;
182 182
  ListDigraph::NodeMap<int> hcolors(h);
183 183
  ListDigraph::NodeMap<Point> hcoords(h);
184 184

	
185 185
  int cols=int(sqrt(double(palette.size())));
186 186
  for(int i=0;i<int(paletteW.size());i++) {
187 187
    Node n=h.addNode();
188 188
    hcoords[n]=Point(1+i%cols,1+i/cols);
189 189
    hcolors[n]=i;
190 190
  }
191 191

	
192 192
  cout << "Create 'graph_to_eps_demo_out_7_colors.eps'" << endl;
193 193
  graphToEps(h,"graph_to_eps_demo_out_7_colors.eps").
194 194
    scale(60).
195 195
    title("Sample .eps figure (Palette demo)").
196 196
    copyright("(C) 2003-2008 LEMON Project").
197 197
    coords(hcoords).
198 198
    absoluteNodeSizes().absoluteArcWidths().
199 199
    nodeScale(.45).
200 200
    distantColorNodeTexts().
201 201
    nodeTexts(hcolors).nodeTextSize(.6).
202 202
    nodeColors(composeMap(paletteW,hcolors)).
203 203
    run();
204 204

	
205 205
  return 0;
206 206
}
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
namespace lemon {
20 20
/*!
21 21

	
22 22

	
23 23

	
24 24
\page lgf-format LEMON Graph Format (LGF)
25 25

	
26 26
The \e LGF is a <em>column oriented</em>
27 27
file format for storing graphs and associated data like
28 28
node and edge maps.
29 29

	
30 30
Each line with \c '#' first non-whitespace
31 31
character is considered as a comment line.
32 32

	
33 33
Otherwise the file consists of sections starting with
34 34
a header line. The header lines starts with an \c '@' character followed by the
35 35
type of section. The standard section types are \c \@nodes, \c
36 36
\@arcs and \c \@edges
37 37
and \@attributes. Each header line may also have an optional
38 38
\e name, which can be use to distinguish the sections of the same
39 39
type.
40 40

	
41 41
The standard sections are column oriented, each line consists of
42 42
<em>token</em>s separated by whitespaces. A token can be \e plain or
43 43
\e quoted. A plain token is just a sequence of non-whitespace characters,
44 44
while a quoted token is a
45 45
character sequence surrounded by double quotes, and it can also
46 46
contain whitespaces and escape sequences.
47 47

	
48 48
The \c \@nodes section describes a set of nodes and associated
49 49
maps. The first is a header line, its columns are the names of the
50 50
maps appearing in the following lines.
51 51
One of the maps must be called \c
52 52
"label", which plays special role in the file.
53 53
The following
54 54
non-empty lines until the next section describes nodes of the
55 55
graph. Each line contains the values of the node maps
56 56
associated to the current node.
57 57

	
58 58
\code
59 59
 @nodes
60 60
 label  coordinates  size    title
61 61
 1      (10,20)      10      "First node"
62 62
 2      (80,80)      8       "Second node"
63 63
 3      (40,10)      10      "Third node"
64 64
\endcode
65 65

	
66 66
The \c \@arcs section is very similar to the \c \@nodes section,
67 67
it again starts with a header line describing the names of the maps,
68 68
but the \c "label" map is not obligatory here. The following lines
69 69
describe the arcs. The first two tokens of each line are
70 70
the source and the target node of the arc, respectively, then come the map
71 71
values. The source and target tokens must be node labels.
72 72

	
73 73
\code
74 74
 @arcs
75 75
         capacity
76 76
 1   2   16
77 77
 1   3   12
78 78
 2   3   18
79 79
\endcode
80 80

	
81
The \c \@edges is just a synonym of \c \@arcs. The @arcs section can
81
The \c \@edges is just a synonym of \c \@arcs. The \@arcs section can
82 82
also store the edge set of an undirected graph. In such case there is
83 83
a conventional method for store arc maps in the file, if two columns
84 84
has the same caption with \c '+' and \c '-' prefix, then these columns
85 85
can be regarded as the values of an arc map.
86 86

	
87 87
The \c \@attributes section contains key-value pairs, each line
88 88
consists of two tokens, an attribute name, and then an attribute
89 89
value. The value of the attribute could be also a label value of a
90 90
node or an edge, or even an edge label prefixed with \c '+' or \c '-',
91 91
which regards to the forward or backward directed arc of the
92 92
corresponding edge.
93 93

	
94 94
\code
95 95
 @attributes
96 96
 source 1
97 97
 target 3
98 98
 caption "LEMON test digraph"
99 99
\endcode
100 100

	
101 101
The \e LGF can contain extra sections, but there is no restriction on
102 102
the format of such sections.
103 103

	
104 104
*/
105 105
}
106 106

	
107 107
//  LocalWords:  whitespace whitespaces
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_ALTERATION_NOTIFIER_H
20 20
#define LEMON_BITS_ALTERATION_NOTIFIER_H
21 21

	
22 22
#include <vector>
23 23
#include <list>
24 24

	
25 25
#include <lemon/core.h>
26 26

	
27 27
///\ingroup graphbits
28 28
///\file
29 29
///\brief Observer notifier for graph alteration observers.
30 30

	
31 31
namespace lemon {
32 32

	
33 33
  /// \ingroup graphbits
34 34
  ///
35 35
  /// \brief Notifier class to notify observes about alterations in
36 36
  /// a container.
37 37
  ///
38 38
  /// The simple graph's can be refered as two containers, one node container
39 39
  /// and one edge container. But they are not standard containers they
40 40
  /// does not store values directly they are just key continars for more
41 41
  /// value containers which are the node and edge maps.
42 42
  ///
43 43
  /// The graph's node and edge sets can be changed as we add or erase
44 44
  /// nodes and edges in the graph. LEMON would like to handle easily
45 45
  /// that the node and edge maps should contain values for all nodes or
46 46
  /// edges. If we want to check on every indicing if the map contains
47 47
  /// the current indicing key that cause a drawback in the performance
48 48
  /// in the library. We use another solution we notify all maps about
49 49
  /// an alteration in the graph, which cause only drawback on the
50 50
  /// alteration of the graph.
51 51
  ///
52 52
  /// This class provides an interface to the container. The \e first() and \e
53 53
  /// next() member functions make possible to iterate on the keys of the
54 54
  /// container. The \e id() function returns an integer id for each key.
55 55
  /// The \e maxId() function gives back an upper bound of the ids.
56 56
  ///
57 57
  /// For the proper functonality of this class, we should notify it
58 58
  /// about each alteration in the container. The alterations have four type
59 59
  /// as \e add(), \e erase(), \e build() and \e clear(). The \e add() and
60 60
  /// \e erase() signals that only one or few items added or erased to or
61 61
  /// from the graph. If all items are erased from the graph or from an empty
62 62
  /// graph a new graph is builded then it can be signaled with the
63 63
  /// clear() and build() members. Important rule that if we erase items
64 64
  /// from graph we should first signal the alteration and after that erase
65 65
  /// them from the container, on the other way on item addition we should
66 66
  /// first extend the container and just after that signal the alteration.
67 67
  ///
68 68
  /// The alteration can be observed with a class inherited from the
69 69
  /// \e ObserverBase nested class. The signals can be handled with
70 70
  /// overriding the virtual functions defined in the base class.  The
71 71
  /// observer base can be attached to the notifier with the
72 72
  /// \e attach() member and can be detached with detach() function. The
73 73
  /// alteration handlers should not call any function which signals
74 74
  /// an other alteration in the same notifier and should not
75 75
  /// detach any observer from the notifier.
76 76
  ///
77 77
  /// Alteration observers try to be exception safe. If an \e add() or
78 78
  /// a \e clear() function throws an exception then the remaining
79 79
  /// observeres will not be notified and the fulfilled additions will
80 80
  /// be rolled back by calling the \e erase() or \e clear()
81 81
  /// functions. Thence the \e erase() and \e clear() should not throw
82
  /// exception. Actullay, it can be throw only
83
  /// \ref AlterationObserver::ImmediateDetach ImmediateDetach
82
  /// exception. Actullay, it can be throw only \ref ImmediateDetach 
84 83
  /// exception which detach the observer from the notifier.
85 84
  ///
86 85
  /// There are some place when the alteration observing is not completly
87 86
  /// reliable. If we want to carry out the node degree in the graph
88 87
  /// as in the \ref InDegMap and we use the reverseEdge that cause
89 88
  /// unreliable functionality. Because the alteration observing signals
90 89
  /// only erasing and adding but not the reversing it will stores bad
91 90
  /// degrees. The sub graph adaptors cannot signal the alterations because
92 91
  /// just a setting in the filter map can modify the graph and this cannot
93 92
  /// be watched in any way.
94 93
  ///
95 94
  /// \param _Container The container which is observed.
96 95
  /// \param _Item The item type which is obserbved.
97 96

	
98 97
  template <typename _Container, typename _Item>
99 98
  class AlterationNotifier {
100 99
  public:
101 100

	
102 101
    typedef True Notifier;
103 102

	
104 103
    typedef _Container Container;
105 104
    typedef _Item Item;
106 105

	
107 106
    /// \brief Exception which can be called from \e clear() and
108 107
    /// \e erase().
109 108
    ///
110 109
    /// From the \e clear() and \e erase() function only this
111 110
    /// exception is allowed to throw. The exception immediatly
112 111
    /// detaches the current observer from the notifier. Because the
113 112
    /// \e clear() and \e erase() should not throw other exceptions
114 113
    /// it can be used to invalidate the observer.
115 114
    struct ImmediateDetach {};
116 115

	
117 116
    /// \brief ObserverBase is the base class for the observers.
118 117
    ///
119 118
    /// ObserverBase is the abstract base class for the observers.
120 119
    /// It will be notified about an item was inserted into or
121 120
    /// erased from the graph.
122 121
    ///
123 122
    /// The observer interface contains some pure virtual functions
124 123
    /// to override. The add() and erase() functions are
125 124
    /// to notify the oberver when one item is added or
126 125
    /// erased.
127 126
    ///
128 127
    /// The build() and clear() members are to notify the observer
129 128
    /// about the container is built from an empty container or
130 129
    /// is cleared to an empty container.
131 130

	
132 131
    class ObserverBase {
133 132
    protected:
134 133
      typedef AlterationNotifier Notifier;
135 134

	
136 135
      friend class AlterationNotifier;
137 136

	
138 137
      /// \brief Default constructor.
139 138
      ///
140 139
      /// Default constructor for ObserverBase.
141 140
      ///
142 141
      ObserverBase() : _notifier(0) {}
143 142

	
144 143
      /// \brief Constructor which attach the observer into notifier.
145 144
      ///
146 145
      /// Constructor which attach the observer into notifier.
147 146
      ObserverBase(AlterationNotifier& nf) {
148 147
        attach(nf);
149 148
      }
150 149

	
151 150
      /// \brief Constructor which attach the obserever to the same notifier.
152 151
      ///
153 152
      /// Constructor which attach the obserever to the same notifier as
154 153
      /// the other observer is attached to.
155 154
      ObserverBase(const ObserverBase& copy) {
156 155
        if (copy.attached()) {
157 156
          attach(*copy.notifier());
158 157
        }
159 158
      }
160 159

	
161 160
      /// \brief Destructor
162 161
      virtual ~ObserverBase() {
163 162
        if (attached()) {
164 163
          detach();
165 164
        }
166 165
      }
167 166

	
168 167
      /// \brief Attaches the observer into an AlterationNotifier.
169 168
      ///
170 169
      /// This member attaches the observer into an AlterationNotifier.
171 170
      ///
172 171
      void attach(AlterationNotifier& nf) {
173 172
        nf.attach(*this);
174 173
      }
175 174

	
176 175
      /// \brief Detaches the observer into an AlterationNotifier.
177 176
      ///
178 177
      /// This member detaches the observer from an AlterationNotifier.
179 178
      ///
180 179
      void detach() {
181 180
        _notifier->detach(*this);
182 181
      }
183 182

	
184 183
      /// \brief Gives back a pointer to the notifier which the map
185 184
      /// attached into.
186 185
      ///
187 186
      /// This function gives back a pointer to the notifier which the map
188 187
      /// attached into.
189 188
      ///
190 189
      Notifier* notifier() const { return const_cast<Notifier*>(_notifier); }
191 190

	
192 191
      /// Gives back true when the observer is attached into a notifier.
193 192
      bool attached() const { return _notifier != 0; }
194 193

	
195 194
    private:
196 195

	
197 196
      ObserverBase& operator=(const ObserverBase& copy);
198 197

	
199 198
    protected:
200 199

	
201 200
      Notifier* _notifier;
202 201
      typename std::list<ObserverBase*>::iterator _index;
203 202

	
204 203
      /// \brief The member function to notificate the observer about an
205 204
      /// item is added to the container.
206 205
      ///
207 206
      /// The add() member function notificates the observer about an item
208 207
      /// is added to the container. It have to be overrided in the
209 208
      /// subclasses.
210 209
      virtual void add(const Item&) = 0;
211 210

	
212 211
      /// \brief The member function to notificate the observer about
213 212
      /// more item is added to the container.
214 213
      ///
215 214
      /// The add() member function notificates the observer about more item
216 215
      /// is added to the container. It have to be overrided in the
217 216
      /// subclasses.
218 217
      virtual void add(const std::vector<Item>& items) = 0;
219 218

	
220 219
      /// \brief The member function to notificate the observer about an
221 220
      /// item is erased from the container.
222 221
      ///
223 222
      /// The erase() member function notificates the observer about an
224 223
      /// item is erased from the container. It have to be overrided in
225 224
      /// the subclasses.
226 225
      virtual void erase(const Item&) = 0;
227 226

	
228 227
      /// \brief The member function to notificate the observer about
229 228
      /// more item is erased from the container.
230 229
      ///
231 230
      /// The erase() member function notificates the observer about more item
232 231
      /// is erased from the container. It have to be overrided in the
233 232
      /// subclasses.
234 233
      virtual void erase(const std::vector<Item>& items) = 0;
235 234

	
236 235
      /// \brief The member function to notificate the observer about the
237 236
      /// container is built.
238 237
      ///
239 238
      /// The build() member function notificates the observer about the
240 239
      /// container is built from an empty container. It have to be
241 240
      /// overrided in the subclasses.
242 241

	
243 242
      virtual void build() = 0;
244 243

	
245 244
      /// \brief The member function to notificate the observer about all
246 245
      /// items are erased from the container.
247 246
      ///
248 247
      /// The clear() member function notificates the observer about all
249 248
      /// items are erased from the container. It have to be overrided in
250 249
      /// the subclasses.
251 250
      virtual void clear() = 0;
252 251

	
253 252
    };
254 253

	
255 254
  protected:
256 255

	
257 256
    const Container* container;
258 257

	
259 258
    typedef std::list<ObserverBase*> Observers;
260 259
    Observers _observers;
261 260

	
262 261

	
263 262
  public:
264 263

	
265 264
    /// \brief Default constructor.
266 265
    ///
267 266
    /// The default constructor of the AlterationNotifier.
268 267
    /// It creates an empty notifier.
269 268
    AlterationNotifier()
270 269
      : container(0) {}
271 270

	
272 271
    /// \brief Constructor.
273 272
    ///
274 273
    /// Constructor with the observed container parameter.
275 274
    AlterationNotifier(const Container& _container)
276 275
      : container(&_container) {}
277 276

	
278 277
    /// \brief Copy Constructor of the AlterationNotifier.
279 278
    ///
280 279
    /// Copy constructor of the AlterationNotifier.
281 280
    /// It creates only an empty notifier because the copiable
282 281
    /// notifier's observers have to be registered still into that notifier.
283 282
    AlterationNotifier(const AlterationNotifier& _notifier)
284 283
      : container(_notifier.container) {}
285 284

	
286 285
    /// \brief Destructor.
287 286
    ///
288 287
    /// Destructor of the AlterationNotifier.
289 288
    ///
290 289
    ~AlterationNotifier() {
291 290
      typename Observers::iterator it;
292 291
      for (it = _observers.begin(); it != _observers.end(); ++it) {
293 292
        (*it)->_notifier = 0;
294 293
      }
295 294
    }
296 295

	
297 296
    /// \brief Sets the container.
298 297
    ///
299 298
    /// Sets the container.
300 299
    void setContainer(const Container& _container) {
301 300
      container = &_container;
302 301
    }
303 302

	
304 303
  protected:
305 304

	
306 305
    AlterationNotifier& operator=(const AlterationNotifier&);
307 306

	
308 307
  public:
309 308

	
310 309

	
311 310

	
312 311
    /// \brief First item in the container.
313 312
    ///
314 313
    /// Returns the first item in the container. It is
315 314
    /// for start the iteration on the container.
316 315
    void first(Item& item) const {
317 316
      container->first(item);
318 317
    }
319 318

	
320 319
    /// \brief Next item in the container.
321 320
    ///
322 321
    /// Returns the next item in the container. It is
323 322
    /// for iterate on the container.
324 323
    void next(Item& item) const {
325 324
      container->next(item);
326 325
    }
327 326

	
328 327
    /// \brief Returns the id of the item.
329 328
    ///
330 329
    /// Returns the id of the item provided by the container.
331 330
    int id(const Item& item) const {
332 331
      return container->id(item);
333 332
    }
334 333

	
335 334
    /// \brief Returns the maximum id of the container.
336 335
    ///
337 336
    /// Returns the maximum id of the container.
338 337
    int maxId() const {
339 338
      return container->maxId(Item());
340 339
    }
341 340

	
342 341
  protected:
343 342

	
344 343
    void attach(ObserverBase& observer) {
345 344
      observer._index = _observers.insert(_observers.begin(), &observer);
346 345
      observer._notifier = this;
347 346
    }
348 347

	
349 348
    void detach(ObserverBase& observer) {
350 349
      _observers.erase(observer._index);
351 350
      observer._index = _observers.end();
352 351
      observer._notifier = 0;
353 352
    }
354 353

	
355 354
  public:
356 355

	
357 356
    /// \brief Notifies all the registed observers about an item added to
358 357
    /// the container.
359 358
    ///
360 359
    /// It notifies all the registed observers about an item added to
361 360
    /// the container.
362 361
    ///
363 362
    void add(const Item& item) {
364 363
      typename Observers::reverse_iterator it;
365 364
      try {
366 365
        for (it = _observers.rbegin(); it != _observers.rend(); ++it) {
367 366
          (*it)->add(item);
368 367
        }
369 368
      } catch (...) {
370 369
        typename Observers::iterator jt;
371 370
        for (jt = it.base(); jt != _observers.end(); ++jt) {
372 371
          (*jt)->erase(item);
373 372
        }
374 373
        throw;
375 374
      }
376 375
    }
377 376

	
378 377
    /// \brief Notifies all the registed observers about more item added to
379 378
    /// the container.
380 379
    ///
381 380
    /// It notifies all the registed observers about more item added to
382 381
    /// the container.
383 382
    ///
384 383
    void add(const std::vector<Item>& items) {
385 384
      typename Observers::reverse_iterator it;
386 385
      try {
387 386
        for (it = _observers.rbegin(); it != _observers.rend(); ++it) {
388 387
          (*it)->add(items);
389 388
        }
390 389
      } catch (...) {
391 390
        typename Observers::iterator jt;
392 391
        for (jt = it.base(); jt != _observers.end(); ++jt) {
393 392
          (*jt)->erase(items);
394 393
        }
395 394
        throw;
396 395
      }
397 396
    }
398 397

	
399 398
    /// \brief Notifies all the registed observers about an item erased from
400 399
    /// the container.
401 400
    ///
402 401
    /// It notifies all the registed observers about an item erased from
403 402
    /// the container.
404 403
    ///
405 404
    void erase(const Item& item) throw() {
406 405
      typename Observers::iterator it = _observers.begin();
407 406
      while (it != _observers.end()) {
408 407
        try {
409 408
          (*it)->erase(item);
410 409
          ++it;
411 410
        } catch (const ImmediateDetach&) {
412 411
          (*it)->_index = _observers.end();
413 412
          (*it)->_notifier = 0;
414 413
          it = _observers.erase(it);
415 414
        }
416 415
      }
417 416
    }
418 417

	
419 418
    /// \brief Notifies all the registed observers about more item erased
420 419
    /// from the container.
421 420
    ///
422 421
    /// It notifies all the registed observers about more item erased from
423 422
    /// the container.
424 423
    ///
425 424
    void erase(const std::vector<Item>& items) {
426 425
      typename Observers::iterator it = _observers.begin();
427 426
      while (it != _observers.end()) {
428 427
        try {
429 428
          (*it)->erase(items);
430 429
          ++it;
431 430
        } catch (const ImmediateDetach&) {
432 431
          (*it)->_index = _observers.end();
433 432
          (*it)->_notifier = 0;
434 433
          it = _observers.erase(it);
435 434
        }
436 435
      }
437 436
    }
438 437

	
439 438
    /// \brief Notifies all the registed observers about the container is
440 439
    /// built.
441 440
    ///
442 441
    /// Notifies all the registed observers about the container is built
443 442
    /// from an empty container.
444 443
    void build() {
445 444
      typename Observers::reverse_iterator it;
446 445
      try {
447 446
        for (it = _observers.rbegin(); it != _observers.rend(); ++it) {
448 447
          (*it)->build();
449 448
        }
450 449
      } catch (...) {
451 450
        typename Observers::iterator jt;
452 451
        for (jt = it.base(); jt != _observers.end(); ++jt) {
453 452
          (*jt)->clear();
454 453
        }
455 454
        throw;
456 455
      }
457 456
    }
458 457

	
459 458
    /// \brief Notifies all the registed observers about all items are
460 459
    /// erased.
461 460
    ///
462 461
    /// Notifies all the registed observers about all items are erased
463 462
    /// from the container.
464 463
    void clear() {
465 464
      typename Observers::iterator it = _observers.begin();
466 465
      while (it != _observers.end()) {
467 466
        try {
468 467
          (*it)->clear();
469 468
          ++it;
470 469
        } catch (const ImmediateDetach&) {
471 470
          (*it)->_index = _observers.end();
472 471
          (*it)->_notifier = 0;
473 472
          it = _observers.erase(it);
474 473
        }
475 474
      }
476 475
    }
477 476
  };
478 477

	
479 478
}
480 479

	
481 480
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_DEFAULT_MAP_H
20 20
#define LEMON_BITS_DEFAULT_MAP_H
21 21

	
22 22

	
23 23
#include <lemon/bits/array_map.h>
24 24
#include <lemon/bits/vector_map.h>
25 25
//#include <lemon/bits/debug_map.h>
26 26

	
27 27
///\ingroup graphbits
28 28
///\file
29 29
///\brief Graph maps that construct and destruct their elements dynamically.
30 30

	
31 31
namespace lemon {
32 32

	
33 33

	
34 34
  //#ifndef LEMON_USE_DEBUG_MAP
35 35

	
36 36
  template <typename _Graph, typename _Item, typename _Value>
37 37
  struct DefaultMapSelector {
38 38
    typedef ArrayMap<_Graph, _Item, _Value> Map;
39 39
  };
40 40

	
41 41
  // bool
42 42
  template <typename _Graph, typename _Item>
43 43
  struct DefaultMapSelector<_Graph, _Item, bool> {
44 44
    typedef VectorMap<_Graph, _Item, bool> Map;
45 45
  };
46 46

	
47 47
  // char
48 48
  template <typename _Graph, typename _Item>
49 49
  struct DefaultMapSelector<_Graph, _Item, char> {
50 50
    typedef VectorMap<_Graph, _Item, char> Map;
51 51
  };
52 52

	
53 53
  template <typename _Graph, typename _Item>
54 54
  struct DefaultMapSelector<_Graph, _Item, signed char> {
55 55
    typedef VectorMap<_Graph, _Item, signed char> Map;
56 56
  };
57 57

	
58 58
  template <typename _Graph, typename _Item>
59 59
  struct DefaultMapSelector<_Graph, _Item, unsigned char> {
60 60
    typedef VectorMap<_Graph, _Item, unsigned char> Map;
61 61
  };
62 62

	
63 63

	
64 64
  // int
65 65
  template <typename _Graph, typename _Item>
66 66
  struct DefaultMapSelector<_Graph, _Item, signed int> {
67 67
    typedef VectorMap<_Graph, _Item, signed int> Map;
68 68
  };
69 69

	
70 70
  template <typename _Graph, typename _Item>
71 71
  struct DefaultMapSelector<_Graph, _Item, unsigned int> {
72 72
    typedef VectorMap<_Graph, _Item, unsigned int> Map;
73 73
  };
74 74

	
75 75

	
76 76
  // short
77 77
  template <typename _Graph, typename _Item>
78 78
  struct DefaultMapSelector<_Graph, _Item, signed short> {
79 79
    typedef VectorMap<_Graph, _Item, signed short> Map;
80 80
  };
81 81

	
82 82
  template <typename _Graph, typename _Item>
83 83
  struct DefaultMapSelector<_Graph, _Item, unsigned short> {
84 84
    typedef VectorMap<_Graph, _Item, unsigned short> Map;
85 85
  };
86 86

	
87 87

	
88 88
  // long
89 89
  template <typename _Graph, typename _Item>
90 90
  struct DefaultMapSelector<_Graph, _Item, signed long> {
91 91
    typedef VectorMap<_Graph, _Item, signed long> Map;
92 92
  };
93 93

	
94 94
  template <typename _Graph, typename _Item>
95 95
  struct DefaultMapSelector<_Graph, _Item, unsigned long> {
96 96
    typedef VectorMap<_Graph, _Item, unsigned long> Map;
97 97
  };
98 98

	
99 99

	
100 100
#if defined __GNUC__ && !defined __STRICT_ANSI__
101 101

	
102 102
  // long long
103 103
  template <typename _Graph, typename _Item>
104 104
  struct DefaultMapSelector<_Graph, _Item, signed long long> {
105 105
    typedef VectorMap<_Graph, _Item, signed long long> Map;
106 106
  };
107 107

	
108 108
  template <typename _Graph, typename _Item>
109 109
  struct DefaultMapSelector<_Graph, _Item, unsigned long long> {
110 110
    typedef VectorMap<_Graph, _Item, unsigned long long> Map;
111 111
  };
112 112

	
113 113
#endif
114 114

	
115 115

	
116 116
  // float
117 117
  template <typename _Graph, typename _Item>
118 118
  struct DefaultMapSelector<_Graph, _Item, float> {
119 119
    typedef VectorMap<_Graph, _Item, float> Map;
120 120
  };
121 121

	
122 122

	
123 123
  // double
124 124
  template <typename _Graph, typename _Item>
125 125
  struct DefaultMapSelector<_Graph, _Item, double> {
126 126
    typedef VectorMap<_Graph, _Item,  double> Map;
127 127
  };
128 128

	
129 129

	
130 130
  // long double
131 131
  template <typename _Graph, typename _Item>
132 132
  struct DefaultMapSelector<_Graph, _Item, long double> {
133 133
    typedef VectorMap<_Graph, _Item, long double> Map;
134 134
  };
135 135

	
136 136

	
137 137
  // pointer
138 138
  template <typename _Graph, typename _Item, typename _Ptr>
139 139
  struct DefaultMapSelector<_Graph, _Item, _Ptr*> {
140 140
    typedef VectorMap<_Graph, _Item, _Ptr*> Map;
141 141
  };
142 142

	
143 143
// #else
144 144

	
145 145
//   template <typename _Graph, typename _Item, typename _Value>
146 146
//   struct DefaultMapSelector {
147 147
//     typedef DebugMap<_Graph, _Item, _Value> Map;
148 148
//   };
149 149

	
150 150
// #endif
151 151

	
152
  /// \e
152
  /// DefaultMap class
153 153
  template <typename _Graph, typename _Item, typename _Value>
154 154
  class DefaultMap
155 155
    : public DefaultMapSelector<_Graph, _Item, _Value>::Map {
156 156
  public:
157 157
    typedef typename DefaultMapSelector<_Graph, _Item, _Value>::Map Parent;
158 158
    typedef DefaultMap<_Graph, _Item, _Value> Map;
159 159

	
160 160
    typedef typename Parent::Graph Graph;
161 161
    typedef typename Parent::Value Value;
162 162

	
163 163
    explicit DefaultMap(const Graph& graph) : Parent(graph) {}
164 164
    DefaultMap(const Graph& graph, const Value& value)
165 165
      : Parent(graph, value) {}
166 166

	
167 167
    DefaultMap& operator=(const DefaultMap& cmap) {
168 168
      return operator=<DefaultMap>(cmap);
169 169
    }
170 170

	
171 171
    template <typename CMap>
172 172
    DefaultMap& operator=(const CMap& cmap) {
173 173
      Parent::operator=(cmap);
174 174
      return *this;
175 175
    }
176 176

	
177 177
  };
178 178

	
179 179
}
180 180

	
181 181
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_COLOR_H
20 20
#define LEMON_COLOR_H
21 21

	
22 22
#include<vector>
23 23
#include<lemon/math.h>
24 24
#include<lemon/maps.h>
25 25

	
26 26

	
27 27
///\ingroup misc
28 28
///\file
29 29
///\brief Tools to manage RGB colors.
30 30

	
31 31
namespace lemon {
32 32

	
33 33

	
34 34
  /// \addtogroup misc
35 35
  /// @{
36 36

	
37 37
  ///Data structure representing RGB colors.
38 38

	
39 39
  ///Data structure representing RGB colors.
40 40
  class Color
41 41
  {
42 42
    double _r,_g,_b;
43 43
  public:
44 44
    ///Default constructor
45 45
    Color() {}
46 46
    ///Constructor
47 47
    Color(double r,double g,double b) :_r(r),_g(g),_b(b) {};
48 48
    ///Set the red component
49 49
    double & red() {return _r;}
50 50
    ///Return the red component
51 51
    const double & red() const {return _r;}
52 52
    ///Set the green component
53 53
    double & green() {return _g;}
54 54
    ///Return the green component
55 55
    const double & green() const {return _g;}
56 56
    ///Set the blue component
57 57
    double & blue() {return _b;}
58 58
    ///Return the blue component
59 59
    const double & blue() const {return _b;}
60 60
    ///Set the color components
61 61
    void set(double r,double g,double b) { _r=r;_g=g;_b=b; };
62 62
  };
63 63

	
64 64
  /// White color constant
65 65
  extern const Color WHITE;
66 66
  /// Black color constant
67 67
  extern const Color BLACK;
68 68
  /// Red color constant
69 69
  extern const Color RED;
70 70
  /// Green color constant
71 71
  extern const Color GREEN;
72 72
  /// Blue color constant
73 73
  extern const Color BLUE;
74 74
  /// Yellow color constant
75 75
  extern const Color YELLOW;
76 76
  /// Magenta color constant
77 77
  extern const Color MAGENTA;
78 78
  /// Cyan color constant
79 79
  extern const Color CYAN;
80 80
  /// Grey color constant
81 81
  extern const Color GREY;
82 82
  /// Dark red color constant
83 83
  extern const Color DARK_RED;
84 84
  /// Dark green color constant
85 85
  extern const Color DARK_GREEN;
86 86
  /// Drak blue color constant
87 87
  extern const Color DARK_BLUE;
88 88
  /// Dark yellow color constant
89 89
  extern const Color DARK_YELLOW;
90 90
  /// Dark magenta color constant
91 91
  extern const Color DARK_MAGENTA;
92 92
  /// Dark cyan color constant
93 93
  extern const Color DARK_CYAN;
94 94

	
95
  ///Map <tt>int</tt>s to different \ref Color "Color"s
95
  ///Map <tt>int</tt>s to different <tt>Color</tt>s
96 96

	
97 97
  ///This map assigns one of the predefined \ref Color "Color"s to
98 98
  ///each <tt>int</tt>. It is possible to change the colors as well as
99 99
  ///their number. The integer range is cyclically mapped to the
100 100
  ///provided set of colors.
101 101
  ///
102 102
  ///This is a true \ref concepts::ReferenceMap "reference map", so
103 103
  ///you can also change the actual colors.
104 104

	
105 105
  class Palette : public MapBase<int,Color>
106 106
  {
107 107
    std::vector<Color> colors;
108 108
  public:
109 109
    ///Constructor
110 110

	
111 111
    ///Constructor.
112 112
    ///\param have_white Indicates whether white is among the
113 113
    ///provided initial colors (\c true) or not (\c false). If it is true,
114 114
    ///white will be assigned to \c 0.
115 115
    ///\param num The number of the allocated colors. If it is \c -1,
116 116
    ///the default color configuration is set up (26 color plus optionaly the
117 117
    ///white).  If \c num is less then 26/27 then the default color
118 118
    ///list is cut. Otherwise the color list is filled repeatedly with
119 119
    ///the default color list.  (The colors can be changed later on.)
120 120
    Palette(bool have_white=false,int num=-1)
121 121
    {
122 122
      if (num==0) return;
123 123
      do {
124 124
        if(have_white) colors.push_back(Color(1,1,1));
125 125

	
126 126
        colors.push_back(Color(0,0,0));
127 127
        colors.push_back(Color(1,0,0));
128 128
        colors.push_back(Color(0,1,0));
129 129
        colors.push_back(Color(0,0,1));
130 130
        colors.push_back(Color(1,1,0));
131 131
        colors.push_back(Color(1,0,1));
132 132
        colors.push_back(Color(0,1,1));
133 133

	
134 134
        colors.push_back(Color(.5,0,0));
135 135
        colors.push_back(Color(0,.5,0));
136 136
        colors.push_back(Color(0,0,.5));
137 137
        colors.push_back(Color(.5,.5,0));
138 138
        colors.push_back(Color(.5,0,.5));
139 139
        colors.push_back(Color(0,.5,.5));
140 140

	
141 141
        colors.push_back(Color(.5,.5,.5));
142 142
        colors.push_back(Color(1,.5,.5));
143 143
        colors.push_back(Color(.5,1,.5));
144 144
        colors.push_back(Color(.5,.5,1));
145 145
        colors.push_back(Color(1,1,.5));
146 146
        colors.push_back(Color(1,.5,1));
147 147
        colors.push_back(Color(.5,1,1));
148 148

	
149 149
        colors.push_back(Color(1,.5,0));
150 150
        colors.push_back(Color(.5,1,0));
151 151
        colors.push_back(Color(1,0,.5));
152 152
        colors.push_back(Color(0,1,.5));
153 153
        colors.push_back(Color(0,.5,1));
154 154
        colors.push_back(Color(.5,0,1));
155 155
      } while(int(colors.size())<num);
156 156
      if(num>=0) colors.resize(num);
157 157
    }
158 158
    ///\e
159 159
    Color &operator[](int i)
160 160
    {
161 161
      return colors[i%colors.size()];
162 162
    }
163 163
    ///\e
164 164
    const Color &operator[](int i) const
165 165
    {
166 166
      return colors[i%colors.size()];
167 167
    }
168 168
    ///\e
169 169
    void set(int i,const Color &c)
170 170
    {
171 171
      colors[i%colors.size()]=c;
172 172
    }
173 173
    ///Adds a new color to the end of the color list.
174 174
    void add(const Color &c)
175 175
    {
176 176
      colors.push_back(c);
177 177
    }
178 178

	
179 179
    ///Sets the number of the existing colors.
180 180
    void resize(int s) { colors.resize(s);}
181 181
    ///Returns the number of the existing colors.
182 182
    int size() const { return int(colors.size());}
183 183
  };
184 184

	
185 185
  ///Returns a visibly distinct \ref Color
186 186

	
187 187
  ///Returns a \ref Color which is as different from the given parameter
188 188
  ///as it is possible.
189 189
  inline Color distantColor(const Color &c)
190 190
  {
191 191
    return Color(c.red()<.5?1:0,c.green()<.5?1:0,c.blue()<.5?1:0);
192 192
  }
193 193
  ///Returns black for light colors and white for the dark ones.
194 194

	
195 195
  ///Returns black for light colors and white for the dark ones.
196 196
  inline Color distantBW(const Color &c){
197 197
    return (.2125*c.red()+.7154*c.green()+.0721*c.blue())<.5 ? WHITE : BLACK;
198 198
  }
199 199

	
200 200
  /// @}
201 201

	
202 202
} //END OF NAMESPACE LEMON
203 203

	
204 204
#endif // LEMON_COLOR_H
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
///\ingroup graph_concepts
20 20
///\file
21 21
///\brief The concept of graph components.
22 22

	
23 23

	
24 24
#ifndef LEMON_CONCEPT_GRAPH_COMPONENTS_H
25 25
#define LEMON_CONCEPT_GRAPH_COMPONENTS_H
26 26

	
27 27
#include <lemon/core.h>
28 28
#include <lemon/concepts/maps.h>
29 29

	
30 30
#include <lemon/bits/alteration_notifier.h>
31 31

	
32 32
namespace lemon {
33 33
  namespace concepts {
34 34

	
35 35
    /// \brief Skeleton class for graph Node and Arc types
36 36
    ///
37 37
    /// This class describes the interface of Node and Arc (and Edge
38 38
    /// in undirected graphs) subtypes of graph types.
39 39
    ///
40 40
    /// \note This class is a template class so that we can use it to
41 41
    /// create graph skeleton classes. The reason for this is than Node
42 42
    /// and Arc types should \em not derive from the same base class.
43 43
    /// For Node you should instantiate it with character 'n' and for Arc
44 44
    /// with 'a'.
45 45

	
46 46
#ifndef DOXYGEN
47 47
    template <char _selector = '0'>
48 48
#endif
49 49
    class GraphItem {
50 50
    public:
51 51
      /// \brief Default constructor.
52 52
      ///
53 53
      /// \warning The default constructor is not required to set
54 54
      /// the item to some well-defined value. So you should consider it
55 55
      /// as uninitialized.
56 56
      GraphItem() {}
57 57
      /// \brief Copy constructor.
58 58
      ///
59 59
      /// Copy constructor.
60 60
      ///
61 61
      GraphItem(const GraphItem &) {}
62 62
      /// \brief Invalid constructor \& conversion.
63 63
      ///
64 64
      /// This constructor initializes the item to be invalid.
65 65
      /// \sa Invalid for more details.
66 66
      GraphItem(Invalid) {}
67 67
      /// \brief Assign operator for nodes.
68 68
      ///
69 69
      /// The nodes are assignable.
70 70
      ///
71 71
      GraphItem& operator=(GraphItem const&) { return *this; }
72 72
      /// \brief Equality operator.
73 73
      ///
74 74
      /// Two iterators are equal if and only if they represents the
75 75
      /// same node in the graph or both are invalid.
76 76
      bool operator==(GraphItem) const { return false; }
77 77
      /// \brief Inequality operator.
78 78
      ///
79 79
      /// \sa operator==(const Node& n)
80 80
      ///
81 81
      bool operator!=(GraphItem) const { return false; }
82 82

	
83 83
      /// \brief Artificial ordering operator.
84 84
      ///
85 85
      /// To allow the use of graph descriptors as key type in std::map or
86 86
      /// similar associative container we require this.
87 87
      ///
88 88
      /// \note This operator only have to define some strict ordering of
89 89
      /// the items; this order has nothing to do with the iteration
90 90
      /// ordering of the items.
91 91
      bool operator<(GraphItem) const { return false; }
92 92

	
93 93
      template<typename _GraphItem>
94 94
      struct Constraints {
95 95
        void constraints() {
96 96
          _GraphItem i1;
97 97
          _GraphItem i2 = i1;
98 98
          _GraphItem i3 = INVALID;
99 99

	
100 100
          i1 = i2 = i3;
101 101

	
102 102
          bool b;
103 103
          //          b = (ia == ib) && (ia != ib) && (ia < ib);
104 104
          b = (ia == ib) && (ia != ib);
105 105
          b = (ia == INVALID) && (ib != INVALID);
106 106
          b = (ia < ib);
107 107
        }
108 108

	
109 109
        const _GraphItem &ia;
110 110
        const _GraphItem &ib;
111 111
      };
112 112
    };
113 113

	
114 114
    /// \brief An empty base directed graph class.
115 115
    ///
116 116
    /// This class provides the minimal set of features needed for a
117 117
    /// directed graph structure. All digraph concepts have to be
118 118
    /// conform to this base directed graph. It just provides types
119 119
    /// for nodes and arcs and functions to get the source and the
120 120
    /// target of the arcs.
121 121
    class BaseDigraphComponent {
122 122
    public:
123 123

	
124 124
      typedef BaseDigraphComponent Digraph;
125 125

	
126 126
      /// \brief Node class of the digraph.
127 127
      ///
128 128
      /// This class represents the Nodes of the digraph.
129 129
      ///
130 130
      typedef GraphItem<'n'> Node;
131 131

	
132 132
      /// \brief Arc class of the digraph.
133 133
      ///
134 134
      /// This class represents the Arcs of the digraph.
135 135
      ///
136 136
      typedef GraphItem<'e'> Arc;
137 137

	
138 138
      /// \brief Gives back the target node of an arc.
139 139
      ///
140 140
      /// Gives back the target node of an arc.
141 141
      ///
142 142
      Node target(const Arc&) const { return INVALID;}
143 143

	
144 144
      /// \brief Gives back the source node of an arc.
145 145
      ///
146 146
      /// Gives back the source node of an arc.
147 147
      ///
148 148
      Node source(const Arc&) const { return INVALID;}
149 149

	
150 150
      /// \brief Gives back the opposite node on the given arc.
151 151
      ///
152 152
      /// Gives back the opposite node on the given arc.
153 153
      Node oppositeNode(const Node&, const Arc&) const {
154 154
        return INVALID;
155 155
      }
156 156

	
157 157
      template <typename _Digraph>
158 158
      struct Constraints {
159 159
        typedef typename _Digraph::Node Node;
160 160
        typedef typename _Digraph::Arc Arc;
161 161

	
162 162
        void constraints() {
163 163
          checkConcept<GraphItem<'n'>, Node>();
164 164
          checkConcept<GraphItem<'a'>, Arc>();
165 165
          {
166 166
            Node n;
167 167
            Arc e(INVALID);
168 168
            n = digraph.source(e);
169 169
            n = digraph.target(e);
170 170
            n = digraph.oppositeNode(n, e);
171 171
          }
172 172
        }
173 173

	
174 174
        const _Digraph& digraph;
175 175
      };
176 176
    };
177 177

	
178 178
    /// \brief An empty base undirected graph class.
179 179
    ///
180 180
    /// This class provides the minimal set of features needed for an
181 181
    /// undirected graph structure. All undirected graph concepts have
182 182
    /// to be conform to this base graph. It just provides types for
183 183
    /// nodes, arcs and edges and functions to get the
184 184
    /// source and the target of the arcs and edges,
185 185
    /// conversion from arcs to edges and function to get
186 186
    /// both direction of the edges.
187 187
    class BaseGraphComponent : public BaseDigraphComponent {
188 188
    public:
189 189
      typedef BaseDigraphComponent::Node Node;
190 190
      typedef BaseDigraphComponent::Arc Arc;
191 191
      /// \brief Undirected arc class of the graph.
192 192
      ///
193 193
      /// This class represents the edges of the graph.
194 194
      /// The undirected graphs can be used as a directed graph which
195 195
      /// for each arc contains the opposite arc too so the graph is
196 196
      /// bidirected. The edge represents two opposite
197 197
      /// directed arcs.
198 198
      class Edge : public GraphItem<'u'> {
199 199
      public:
200 200
        typedef GraphItem<'u'> Parent;
201 201
        /// \brief Default constructor.
202 202
        ///
203 203
        /// \warning The default constructor is not required to set
204 204
        /// the item to some well-defined value. So you should consider it
205 205
        /// as uninitialized.
206 206
        Edge() {}
207 207
        /// \brief Copy constructor.
208 208
        ///
209 209
        /// Copy constructor.
210 210
        ///
211 211
        Edge(const Edge &) : Parent() {}
212 212
        /// \brief Invalid constructor \& conversion.
213 213
        ///
214 214
        /// This constructor initializes the item to be invalid.
215 215
        /// \sa Invalid for more details.
216 216
        Edge(Invalid) {}
217 217
        /// \brief Converter from arc to edge.
218 218
        ///
219 219
        /// Besides the core graph item functionality each arc should
220 220
        /// be convertible to the represented edge.
221 221
        Edge(const Arc&) {}
222 222
        /// \brief Assign arc to edge.
223 223
        ///
224 224
        /// Besides the core graph item functionality each arc should
225 225
        /// be convertible to the represented edge.
226 226
        Edge& operator=(const Arc&) { return *this; }
227 227
      };
228 228

	
229 229
      /// \brief Returns the direction of the arc.
230 230
      ///
231 231
      /// Returns the direction of the arc. Each arc represents an
232 232
      /// edge with a direction. It gives back the
233 233
      /// direction.
234 234
      bool direction(const Arc&) const { return true; }
235 235

	
236 236
      /// \brief Returns the directed arc.
237 237
      ///
238 238
      /// Returns the directed arc from its direction and the
239 239
      /// represented edge.
240 240
      Arc direct(const Edge&, bool) const { return INVALID;}
241 241

	
242 242
      /// \brief Returns the directed arc.
243 243
      ///
244 244
      /// Returns the directed arc from its source and the
245 245
      /// represented edge.
246 246
      Arc direct(const Edge&, const Node&) const { return INVALID;}
247 247

	
248 248
      /// \brief Returns the opposite arc.
249 249
      ///
250 250
      /// Returns the opposite arc. It is the arc representing the
251 251
      /// same edge and has opposite direction.
252 252
      Arc oppositeArc(const Arc&) const { return INVALID;}
253 253

	
254 254
      /// \brief Gives back one ending of an edge.
255 255
      ///
256 256
      /// Gives back one ending of an edge.
257 257
      Node u(const Edge&) const { return INVALID;}
258 258

	
259 259
      /// \brief Gives back the other ending of an edge.
260 260
      ///
261 261
      /// Gives back the other ending of an edge.
262 262
      Node v(const Edge&) const { return INVALID;}
263 263

	
264 264
      template <typename _Graph>
265 265
      struct Constraints {
266 266
        typedef typename _Graph::Node Node;
267 267
        typedef typename _Graph::Arc Arc;
268 268
        typedef typename _Graph::Edge Edge;
269 269

	
270 270
        void constraints() {
271 271
          checkConcept<BaseDigraphComponent, _Graph>();
272 272
          checkConcept<GraphItem<'u'>, Edge>();
273 273
          {
274 274
            Node n;
275 275
            Edge ue(INVALID);
276 276
            Arc e;
277 277
            n = graph.u(ue);
278 278
            n = graph.v(ue);
279 279
            e = graph.direct(ue, true);
280 280
            e = graph.direct(ue, n);
281 281
            e = graph.oppositeArc(e);
282 282
            ue = e;
283 283
            bool d = graph.direction(e);
284 284
            ignore_unused_variable_warning(d);
285 285
          }
286 286
        }
287 287

	
288 288
        const _Graph& graph;
289 289
      };
290 290

	
291 291
    };
292 292

	
293 293
    /// \brief An empty idable base digraph class.
294 294
    ///
295 295
    /// This class provides beside the core digraph features
296 296
    /// core id functions for the digraph structure.
297 297
    /// The most of the base digraphs should be conform to this concept.
298 298
    /// The id's are unique and immutable.
299 299
    template <typename _Base = BaseDigraphComponent>
300 300
    class IDableDigraphComponent : public _Base {
301 301
    public:
302 302

	
303 303
      typedef _Base Base;
304 304
      typedef typename Base::Node Node;
305 305
      typedef typename Base::Arc Arc;
306 306

	
307 307
      /// \brief Gives back an unique integer id for the Node.
308 308
      ///
309 309
      /// Gives back an unique integer id for the Node.
310 310
      ///
311 311
      int id(const Node&) const { return -1;}
312 312

	
313 313
      /// \brief Gives back the node by the unique id.
314 314
      ///
315 315
      /// Gives back the node by the unique id.
316 316
      /// If the digraph does not contain node with the given id
317 317
      /// then the result of the function is undetermined.
318 318
      Node nodeFromId(int) const { return INVALID;}
319 319

	
320 320
      /// \brief Gives back an unique integer id for the Arc.
321 321
      ///
322 322
      /// Gives back an unique integer id for the Arc.
323 323
      ///
324 324
      int id(const Arc&) const { return -1;}
325 325

	
326 326
      /// \brief Gives back the arc by the unique id.
327 327
      ///
328 328
      /// Gives back the arc by the unique id.
329 329
      /// If the digraph does not contain arc with the given id
330 330
      /// then the result of the function is undetermined.
331 331
      Arc arcFromId(int) const { return INVALID;}
332 332

	
333 333
      /// \brief Gives back an integer greater or equal to the maximum
334 334
      /// Node id.
335 335
      ///
336 336
      /// Gives back an integer greater or equal to the maximum Node
337 337
      /// id.
338 338
      int maxNodeId() const { return -1;}
339 339

	
340 340
      /// \brief Gives back an integer greater or equal to the maximum
341 341
      /// Arc id.
342 342
      ///
343 343
      /// Gives back an integer greater or equal to the maximum Arc
344 344
      /// id.
345 345
      int maxArcId() const { return -1;}
346 346

	
347 347
      template <typename _Digraph>
348 348
      struct Constraints {
349 349

	
350 350
        void constraints() {
351 351
          checkConcept<Base, _Digraph >();
352 352
          typename _Digraph::Node node;
353 353
          int nid = digraph.id(node);
354 354
          nid = digraph.id(node);
355 355
          node = digraph.nodeFromId(nid);
356 356
          typename _Digraph::Arc arc;
357 357
          int eid = digraph.id(arc);
358 358
          eid = digraph.id(arc);
359 359
          arc = digraph.arcFromId(eid);
360 360

	
361 361
          nid = digraph.maxNodeId();
362 362
          ignore_unused_variable_warning(nid);
363 363
          eid = digraph.maxArcId();
364 364
          ignore_unused_variable_warning(eid);
365 365
        }
366 366

	
367 367
        const _Digraph& digraph;
368 368
      };
369 369
    };
370 370

	
371 371
    /// \brief An empty idable base undirected graph class.
372 372
    ///
373 373
    /// This class provides beside the core undirected graph features
374 374
    /// core id functions for the undirected graph structure.  The
375 375
    /// most of the base undirected graphs should be conform to this
376 376
    /// concept.  The id's are unique and immutable.
377 377
    template <typename _Base = BaseGraphComponent>
378 378
    class IDableGraphComponent : public IDableDigraphComponent<_Base> {
379 379
    public:
380 380

	
381 381
      typedef _Base Base;
382 382
      typedef typename Base::Edge Edge;
383 383

	
384 384
      using IDableDigraphComponent<_Base>::id;
385 385

	
386 386
      /// \brief Gives back an unique integer id for the Edge.
387 387
      ///
388 388
      /// Gives back an unique integer id for the Edge.
389 389
      ///
390 390
      int id(const Edge&) const { return -1;}
391 391

	
392 392
      /// \brief Gives back the edge by the unique id.
393 393
      ///
394 394
      /// Gives back the edge by the unique id.  If the
395 395
      /// graph does not contain arc with the given id then the
396 396
      /// result of the function is undetermined.
397 397
      Edge edgeFromId(int) const { return INVALID;}
398 398

	
399 399
      /// \brief Gives back an integer greater or equal to the maximum
400 400
      /// Edge id.
401 401
      ///
402 402
      /// Gives back an integer greater or equal to the maximum Edge
403 403
      /// id.
404 404
      int maxEdgeId() const { return -1;}
405 405

	
406 406
      template <typename _Graph>
407 407
      struct Constraints {
408 408

	
409 409
        void constraints() {
410 410
          checkConcept<Base, _Graph >();
411 411
          checkConcept<IDableDigraphComponent<Base>, _Graph >();
412 412
          typename _Graph::Edge edge;
413 413
          int ueid = graph.id(edge);
414 414
          ueid = graph.id(edge);
415 415
          edge = graph.edgeFromId(ueid);
416 416
          ueid = graph.maxEdgeId();
417 417
          ignore_unused_variable_warning(ueid);
418 418
        }
419 419

	
420 420
        const _Graph& graph;
421 421
      };
422 422
    };
423 423

	
424 424
    /// \brief Skeleton class for graph NodeIt and ArcIt
425 425
    ///
426 426
    /// Skeleton class for graph NodeIt and ArcIt.
427 427
    ///
428 428
    template <typename _Graph, typename _Item>
429 429
    class GraphItemIt : public _Item {
430 430
    public:
431 431
      /// \brief Default constructor.
432 432
      ///
433 433
      /// @warning The default constructor sets the iterator
434 434
      /// to an undefined value.
435 435
      GraphItemIt() {}
436 436
      /// \brief Copy constructor.
437 437
      ///
438 438
      /// Copy constructor.
439 439
      ///
440 440
      GraphItemIt(const GraphItemIt& ) {}
441 441
      /// \brief Sets the iterator to the first item.
442 442
      ///
443 443
      /// Sets the iterator to the first item of \c the graph.
444 444
      ///
445 445
      explicit GraphItemIt(const _Graph&) {}
446 446
      /// \brief Invalid constructor \& conversion.
447 447
      ///
448 448
      /// This constructor initializes the item to be invalid.
449 449
      /// \sa Invalid for more details.
450 450
      GraphItemIt(Invalid) {}
451 451
      /// \brief Assign operator for items.
452 452
      ///
453 453
      /// The items are assignable.
454 454
      ///
455 455
      GraphItemIt& operator=(const GraphItemIt&) { return *this; }
456 456
      /// \brief Next item.
457 457
      ///
458 458
      /// Assign the iterator to the next item.
459 459
      ///
460 460
      GraphItemIt& operator++() { return *this; }
461 461
      /// \brief Equality operator
462 462
      ///
463 463
      /// Two iterators are equal if and only if they point to the
464 464
      /// same object or both are invalid.
465 465
      bool operator==(const GraphItemIt&) const { return true;}
466 466
      /// \brief Inequality operator
467 467
      ///
468 468
      /// \sa operator==(Node n)
469 469
      ///
470 470
      bool operator!=(const GraphItemIt&) const { return true;}
471 471

	
472 472
      template<typename _GraphItemIt>
473 473
      struct Constraints {
474 474
        void constraints() {
475 475
          _GraphItemIt it1(g);
476 476
          _GraphItemIt it2;
477 477

	
478 478
          it2 = ++it1;
479 479
          ++it2 = it1;
480 480
          ++(++it1);
481 481

	
482 482
          _Item bi = it1;
483 483
          bi = it2;
484 484
        }
485 485
        _Graph& g;
486 486
      };
487 487
    };
488 488

	
489 489
    /// \brief Skeleton class for graph InArcIt and OutArcIt
490 490
    ///
491 491
    /// \note Because InArcIt and OutArcIt may not inherit from the same
492 492
    /// base class, the _selector is a additional template parameter. For
493 493
    /// InArcIt you should instantiate it with character 'i' and for
494 494
    /// OutArcIt with 'o'.
495 495
    template <typename _Graph,
496 496
              typename _Item = typename _Graph::Arc,
497 497
              typename _Base = typename _Graph::Node,
498 498
              char _selector = '0'>
499 499
    class GraphIncIt : public _Item {
500 500
    public:
501 501
      /// \brief Default constructor.
502 502
      ///
503 503
      /// @warning The default constructor sets the iterator
504 504
      /// to an undefined value.
505 505
      GraphIncIt() {}
506 506
      /// \brief Copy constructor.
507 507
      ///
508 508
      /// Copy constructor.
509 509
      ///
510 510
      GraphIncIt(GraphIncIt const& gi) : _Item(gi) {}
511 511
      /// \brief Sets the iterator to the first arc incoming into or outgoing
512 512
      /// from the node.
513 513
      ///
514 514
      /// Sets the iterator to the first arc incoming into or outgoing
515 515
      /// from the node.
516 516
      ///
517 517
      explicit GraphIncIt(const _Graph&, const _Base&) {}
518 518
      /// \brief Invalid constructor \& conversion.
519 519
      ///
520 520
      /// This constructor initializes the item to be invalid.
521 521
      /// \sa Invalid for more details.
522 522
      GraphIncIt(Invalid) {}
523 523
      /// \brief Assign operator for iterators.
524 524
      ///
525 525
      /// The iterators are assignable.
526 526
      ///
527 527
      GraphIncIt& operator=(GraphIncIt const&) { return *this; }
528 528
      /// \brief Next item.
529 529
      ///
530 530
      /// Assign the iterator to the next item.
531 531
      ///
532 532
      GraphIncIt& operator++() { return *this; }
533 533

	
534 534
      /// \brief Equality operator
535 535
      ///
536 536
      /// Two iterators are equal if and only if they point to the
537 537
      /// same object or both are invalid.
538 538
      bool operator==(const GraphIncIt&) const { return true;}
539 539

	
540 540
      /// \brief Inequality operator
541 541
      ///
542 542
      /// \sa operator==(Node n)
543 543
      ///
544 544
      bool operator!=(const GraphIncIt&) const { return true;}
545 545

	
546 546
      template <typename _GraphIncIt>
547 547
      struct Constraints {
548 548
        void constraints() {
549 549
          checkConcept<GraphItem<_selector>, _GraphIncIt>();
550 550
          _GraphIncIt it1(graph, node);
551 551
          _GraphIncIt it2;
552 552

	
553 553
          it2 = ++it1;
554 554
          ++it2 = it1;
555 555
          ++(++it1);
556 556
          _Item e = it1;
557 557
          e = it2;
558 558

	
559 559
        }
560 560

	
561 561
        _Item arc;
562 562
        _Base node;
563 563
        _Graph graph;
564 564
        _GraphIncIt it;
565 565
      };
566 566
    };
567 567

	
568 568

	
569 569
    /// \brief An empty iterable digraph class.
570 570
    ///
571 571
    /// This class provides beside the core digraph features
572 572
    /// iterator based iterable interface for the digraph structure.
573 573
    /// This concept is part of the Digraph concept.
574 574
    template <typename _Base = BaseDigraphComponent>
575 575
    class IterableDigraphComponent : public _Base {
576 576

	
577 577
    public:
578 578

	
579 579
      typedef _Base Base;
580 580
      typedef typename Base::Node Node;
581 581
      typedef typename Base::Arc Arc;
582 582

	
583 583
      typedef IterableDigraphComponent Digraph;
584 584

	
585 585
      /// \name Base iteration
586 586
      ///
587 587
      /// This interface provides functions for iteration on digraph items
588 588
      ///
589 589
      /// @{
590 590

	
591 591
      /// \brief Gives back the first node in the iterating order.
592 592
      ///
593 593
      /// Gives back the first node in the iterating order.
594 594
      ///
595 595
      void first(Node&) const {}
596 596

	
597 597
      /// \brief Gives back the next node in the iterating order.
598 598
      ///
599 599
      /// Gives back the next node in the iterating order.
600 600
      ///
601 601
      void next(Node&) const {}
602 602

	
603 603
      /// \brief Gives back the first arc in the iterating order.
604 604
      ///
605 605
      /// Gives back the first arc in the iterating order.
606 606
      ///
607 607
      void first(Arc&) const {}
608 608

	
609 609
      /// \brief Gives back the next arc in the iterating order.
610 610
      ///
611 611
      /// Gives back the next arc in the iterating order.
612 612
      ///
613 613
      void next(Arc&) const {}
614 614

	
615 615

	
616 616
      /// \brief Gives back the first of the arcs point to the given
617 617
      /// node.
618 618
      ///
619 619
      /// Gives back the first of the arcs point to the given node.
620 620
      ///
621 621
      void firstIn(Arc&, const Node&) const {}
622 622

	
623 623
      /// \brief Gives back the next of the arcs points to the given
624 624
      /// node.
625 625
      ///
626 626
      /// Gives back the next of the arcs points to the given node.
627 627
      ///
628 628
      void nextIn(Arc&) const {}
629 629

	
630 630
      /// \brief Gives back the first of the arcs start from the
631 631
      /// given node.
632 632
      ///
633 633
      /// Gives back the first of the arcs start from the given node.
634 634
      ///
635 635
      void firstOut(Arc&, const Node&) const {}
636 636

	
637 637
      /// \brief Gives back the next of the arcs start from the given
638 638
      /// node.
639 639
      ///
640 640
      /// Gives back the next of the arcs start from the given node.
641 641
      ///
642 642
      void nextOut(Arc&) const {}
643 643

	
644 644
      /// @}
645 645

	
646 646
      /// \name Class based iteration
647 647
      ///
648 648
      /// This interface provides functions for iteration on digraph items
649 649
      ///
650 650
      /// @{
651 651

	
652 652
      /// \brief This iterator goes through each node.
653 653
      ///
654 654
      /// This iterator goes through each node.
655 655
      ///
656 656
      typedef GraphItemIt<Digraph, Node> NodeIt;
657 657

	
658 658
      /// \brief This iterator goes through each node.
659 659
      ///
660 660
      /// This iterator goes through each node.
661 661
      ///
662 662
      typedef GraphItemIt<Digraph, Arc> ArcIt;
663 663

	
664 664
      /// \brief This iterator goes trough the incoming arcs of a node.
665 665
      ///
666 666
      /// This iterator goes trough the \e inccoming arcs of a certain node
667 667
      /// of a digraph.
668 668
      typedef GraphIncIt<Digraph, Arc, Node, 'i'> InArcIt;
669 669

	
670 670
      /// \brief This iterator goes trough the outgoing arcs of a node.
671 671
      ///
672 672
      /// This iterator goes trough the \e outgoing arcs of a certain node
673 673
      /// of a digraph.
674 674
      typedef GraphIncIt<Digraph, Arc, Node, 'o'> OutArcIt;
675 675

	
676 676
      /// \brief The base node of the iterator.
677 677
      ///
678 678
      /// Gives back the base node of the iterator.
679 679
      /// It is always the target of the pointed arc.
680 680
      Node baseNode(const InArcIt&) const { return INVALID; }
681 681

	
682 682
      /// \brief The running node of the iterator.
683 683
      ///
684 684
      /// Gives back the running node of the iterator.
685 685
      /// It is always the source of the pointed arc.
686 686
      Node runningNode(const InArcIt&) const { return INVALID; }
687 687

	
688 688
      /// \brief The base node of the iterator.
689 689
      ///
690 690
      /// Gives back the base node of the iterator.
691 691
      /// It is always the source of the pointed arc.
692 692
      Node baseNode(const OutArcIt&) const { return INVALID; }
693 693

	
694 694
      /// \brief The running node of the iterator.
695 695
      ///
696 696
      /// Gives back the running node of the iterator.
697 697
      /// It is always the target of the pointed arc.
698 698
      Node runningNode(const OutArcIt&) const { return INVALID; }
699 699

	
700 700
      /// @}
701 701

	
702 702
      template <typename _Digraph>
703 703
      struct Constraints {
704 704
        void constraints() {
705 705
          checkConcept<Base, _Digraph>();
706 706

	
707 707
          {
708 708
            typename _Digraph::Node node(INVALID);
709 709
            typename _Digraph::Arc arc(INVALID);
710 710
            {
711 711
              digraph.first(node);
712 712
              digraph.next(node);
713 713
            }
714 714
            {
715 715
              digraph.first(arc);
716 716
              digraph.next(arc);
717 717
            }
718 718
            {
719 719
              digraph.firstIn(arc, node);
720 720
              digraph.nextIn(arc);
721 721
            }
722 722
            {
723 723
              digraph.firstOut(arc, node);
724 724
              digraph.nextOut(arc);
725 725
            }
726 726
          }
727 727

	
728 728
          {
729 729
            checkConcept<GraphItemIt<_Digraph, typename _Digraph::Arc>,
730 730
              typename _Digraph::ArcIt >();
731 731
            checkConcept<GraphItemIt<_Digraph, typename _Digraph::Node>,
732 732
              typename _Digraph::NodeIt >();
733 733
            checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc,
734 734
              typename _Digraph::Node, 'i'>, typename _Digraph::InArcIt>();
735 735
            checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc,
736 736
              typename _Digraph::Node, 'o'>, typename _Digraph::OutArcIt>();
737 737

	
738 738
            typename _Digraph::Node n;
739 739
            typename _Digraph::InArcIt ieit(INVALID);
740 740
            typename _Digraph::OutArcIt oeit(INVALID);
741 741
            n = digraph.baseNode(ieit);
742 742
            n = digraph.runningNode(ieit);
743 743
            n = digraph.baseNode(oeit);
744 744
            n = digraph.runningNode(oeit);
745 745
            ignore_unused_variable_warning(n);
746 746
          }
747 747
        }
748 748

	
749 749
        const _Digraph& digraph;
750 750

	
751 751
      };
752 752
    };
753 753

	
754 754
    /// \brief An empty iterable undirected graph class.
755 755
    ///
756 756
    /// This class provides beside the core graph features iterator
757 757
    /// based iterable interface for the undirected graph structure.
758 758
    /// This concept is part of the Graph concept.
759 759
    template <typename _Base = BaseGraphComponent>
760 760
    class IterableGraphComponent : public IterableDigraphComponent<_Base> {
761 761
    public:
762 762

	
763 763
      typedef _Base Base;
764 764
      typedef typename Base::Node Node;
765 765
      typedef typename Base::Arc Arc;
766 766
      typedef typename Base::Edge Edge;
767 767

	
768 768

	
769 769
      typedef IterableGraphComponent Graph;
770 770

	
771 771
      /// \name Base iteration
772 772
      ///
773 773
      /// This interface provides functions for iteration on graph items
774 774
      /// @{
775 775

	
776 776
      using IterableDigraphComponent<_Base>::first;
777 777
      using IterableDigraphComponent<_Base>::next;
778 778

	
779 779
      /// \brief Gives back the first edge in the iterating
780 780
      /// order.
781 781
      ///
782 782
      /// Gives back the first edge in the iterating order.
783 783
      ///
784 784
      void first(Edge&) const {}
785 785

	
786 786
      /// \brief Gives back the next edge in the iterating
787 787
      /// order.
788 788
      ///
789 789
      /// Gives back the next edge in the iterating order.
790 790
      ///
791 791
      void next(Edge&) const {}
792 792

	
793 793

	
794 794
      /// \brief Gives back the first of the edges from the
795 795
      /// given node.
796 796
      ///
797 797
      /// Gives back the first of the edges from the given
798 798
      /// node. The bool parameter gives back that direction which
799 799
      /// gives a good direction of the edge so the source of the
800 800
      /// directed arc is the given node.
801 801
      void firstInc(Edge&, bool&, const Node&) const {}
802 802

	
803 803
      /// \brief Gives back the next of the edges from the
804 804
      /// given node.
805 805
      ///
806 806
      /// Gives back the next of the edges from the given
807 807
      /// node. The bool parameter should be used as the \c firstInc()
808 808
      /// use it.
809 809
      void nextInc(Edge&, bool&) const {}
810 810

	
811 811
      using IterableDigraphComponent<_Base>::baseNode;
812 812
      using IterableDigraphComponent<_Base>::runningNode;
813 813

	
814 814
      /// @}
815 815

	
816 816
      /// \name Class based iteration
817 817
      ///
818 818
      /// This interface provides functions for iteration on graph items
819 819
      ///
820 820
      /// @{
821 821

	
822 822
      /// \brief This iterator goes through each node.
823 823
      ///
824 824
      /// This iterator goes through each node.
825 825
      typedef GraphItemIt<Graph, Edge> EdgeIt;
826 826
      /// \brief This iterator goes trough the incident arcs of a
827 827
      /// node.
828 828
      ///
829 829
      /// This iterator goes trough the incident arcs of a certain
830 830
      /// node of a graph.
831 831
      typedef GraphIncIt<Graph, Edge, Node, 'u'> IncEdgeIt;
832 832
      /// \brief The base node of the iterator.
833 833
      ///
834 834
      /// Gives back the base node of the iterator.
835 835
      Node baseNode(const IncEdgeIt&) const { return INVALID; }
836 836

	
837 837
      /// \brief The running node of the iterator.
838 838
      ///
839 839
      /// Gives back the running node of the iterator.
840 840
      Node runningNode(const IncEdgeIt&) const { return INVALID; }
841 841

	
842 842
      /// @}
843 843

	
844 844
      template <typename _Graph>
845 845
      struct Constraints {
846 846
        void constraints() {
847 847
          checkConcept<IterableDigraphComponent<Base>, _Graph>();
848 848

	
849 849
          {
850 850
            typename _Graph::Node node(INVALID);
851 851
            typename _Graph::Edge edge(INVALID);
852 852
            bool dir;
853 853
            {
854 854
              graph.first(edge);
855 855
              graph.next(edge);
856 856
            }
857 857
            {
858 858
              graph.firstInc(edge, dir, node);
859 859
              graph.nextInc(edge, dir);
860 860
            }
861 861

	
862 862
          }
863 863

	
864 864
          {
865 865
            checkConcept<GraphItemIt<_Graph, typename _Graph::Edge>,
866 866
              typename _Graph::EdgeIt >();
867 867
            checkConcept<GraphIncIt<_Graph, typename _Graph::Edge,
868 868
              typename _Graph::Node, 'u'>, typename _Graph::IncEdgeIt>();
869 869

	
870 870
            typename _Graph::Node n;
871 871
            typename _Graph::IncEdgeIt ueit(INVALID);
872 872
            n = graph.baseNode(ueit);
873 873
            n = graph.runningNode(ueit);
874 874
          }
875 875
        }
876 876

	
877 877
        const _Graph& graph;
878 878

	
879 879
      };
880 880
    };
881 881

	
882 882
    /// \brief An empty alteration notifier digraph class.
883 883
    ///
884 884
    /// This class provides beside the core digraph features alteration
885 885
    /// notifier interface for the digraph structure.  This implements
886 886
    /// an observer-notifier pattern for each digraph item. More
887 887
    /// obsevers can be registered into the notifier and whenever an
888 888
    /// alteration occured in the digraph all the observers will
889 889
    /// notified about it.
890 890
    template <typename _Base = BaseDigraphComponent>
891 891
    class AlterableDigraphComponent : public _Base {
892 892
    public:
893 893

	
894 894
      typedef _Base Base;
895 895
      typedef typename Base::Node Node;
896 896
      typedef typename Base::Arc Arc;
897 897

	
898 898

	
899 899
      /// The node observer registry.
900 900
      typedef AlterationNotifier<AlterableDigraphComponent, Node>
901 901
      NodeNotifier;
902 902
      /// The arc observer registry.
903 903
      typedef AlterationNotifier<AlterableDigraphComponent, Arc>
904 904
      ArcNotifier;
905 905

	
906 906
      /// \brief Gives back the node alteration notifier.
907 907
      ///
908 908
      /// Gives back the node alteration notifier.
909 909
      NodeNotifier& notifier(Node) const {
910 910
        return NodeNotifier();
911 911
      }
912 912

	
913 913
      /// \brief Gives back the arc alteration notifier.
914 914
      ///
915 915
      /// Gives back the arc alteration notifier.
916 916
      ArcNotifier& notifier(Arc) const {
917 917
        return ArcNotifier();
918 918
      }
919 919

	
920 920
      template <typename _Digraph>
921 921
      struct Constraints {
922 922
        void constraints() {
923 923
          checkConcept<Base, _Digraph>();
924 924
          typename _Digraph::NodeNotifier& nn
925 925
            = digraph.notifier(typename _Digraph::Node());
926 926

	
927 927
          typename _Digraph::ArcNotifier& en
928 928
            = digraph.notifier(typename _Digraph::Arc());
929 929

	
930 930
          ignore_unused_variable_warning(nn);
931 931
          ignore_unused_variable_warning(en);
932 932
        }
933 933

	
934 934
        const _Digraph& digraph;
935 935

	
936 936
      };
937 937

	
938 938
    };
939 939

	
940 940
    /// \brief An empty alteration notifier undirected graph class.
941 941
    ///
942 942
    /// This class provides beside the core graph features alteration
943 943
    /// notifier interface for the graph structure.  This implements
944 944
    /// an observer-notifier pattern for each graph item. More
945 945
    /// obsevers can be registered into the notifier and whenever an
946 946
    /// alteration occured in the graph all the observers will
947 947
    /// notified about it.
948 948
    template <typename _Base = BaseGraphComponent>
949 949
    class AlterableGraphComponent : public AlterableDigraphComponent<_Base> {
950 950
    public:
951 951

	
952 952
      typedef _Base Base;
953 953
      typedef typename Base::Edge Edge;
954 954

	
955 955

	
956 956
      /// The arc observer registry.
957 957
      typedef AlterationNotifier<AlterableGraphComponent, Edge>
958 958
      EdgeNotifier;
959 959

	
960 960
      /// \brief Gives back the arc alteration notifier.
961 961
      ///
962 962
      /// Gives back the arc alteration notifier.
963 963
      EdgeNotifier& notifier(Edge) const {
964 964
        return EdgeNotifier();
965 965
      }
966 966

	
967 967
      template <typename _Graph>
968 968
      struct Constraints {
969 969
        void constraints() {
970 970
          checkConcept<AlterableGraphComponent<Base>, _Graph>();
971 971
          typename _Graph::EdgeNotifier& uen
972 972
            = graph.notifier(typename _Graph::Edge());
973 973
          ignore_unused_variable_warning(uen);
974 974
        }
975 975

	
976 976
        const _Graph& graph;
977 977

	
978 978
      };
979 979

	
980 980
    };
981 981

	
982 982
    /// \brief Class describing the concept of graph maps
983 983
    ///
984 984
    /// This class describes the common interface of the graph maps
985
    /// (NodeMap, ArcMap), that is \ref maps-page "maps" which can be used to
985
    /// (NodeMap, ArcMap), that is maps that can be used to
986 986
    /// associate data to graph descriptors (nodes or arcs).
987 987
    template <typename _Graph, typename _Item, typename _Value>
988 988
    class GraphMap : public ReadWriteMap<_Item, _Value> {
989 989
    public:
990 990

	
991 991
      typedef ReadWriteMap<_Item, _Value> Parent;
992 992

	
993 993
      /// The graph type of the map.
994 994
      typedef _Graph Graph;
995 995
      /// The key type of the map.
996 996
      typedef _Item Key;
997 997
      /// The value type of the map.
998 998
      typedef _Value Value;
999 999

	
1000 1000
      /// \brief Construct a new map.
1001 1001
      ///
1002 1002
      /// Construct a new map for the graph.
1003 1003
      explicit GraphMap(const Graph&) {}
1004 1004
      /// \brief Construct a new map with default value.
1005 1005
      ///
1006 1006
      /// Construct a new map for the graph and initalise the values.
1007 1007
      GraphMap(const Graph&, const Value&) {}
1008 1008

	
1009 1009
    private:
1010 1010
      /// \brief Copy constructor.
1011 1011
      ///
1012 1012
      /// Copy Constructor.
1013 1013
      GraphMap(const GraphMap&) : Parent() {}
1014 1014

	
1015 1015
      /// \brief Assign operator.
1016 1016
      ///
1017 1017
      /// Assign operator. It does not mofify the underlying graph,
1018 1018
      /// it just iterates on the current item set and set the  map
1019 1019
      /// with the value returned by the assigned map.
1020 1020
      template <typename CMap>
1021 1021
      GraphMap& operator=(const CMap&) {
1022 1022
        checkConcept<ReadMap<Key, Value>, CMap>();
1023 1023
        return *this;
1024 1024
      }
1025 1025

	
1026 1026
    public:
1027 1027
      template<typename _Map>
1028 1028
      struct Constraints {
1029 1029
        void constraints() {
1030 1030
          checkConcept<ReadWriteMap<Key, Value>, _Map >();
1031 1031
          // Construction with a graph parameter
1032 1032
          _Map a(g);
1033 1033
          // Constructor with a graph and a default value parameter
1034 1034
          _Map a2(g,t);
1035 1035
          // Copy constructor.
1036 1036
          // _Map b(c);
1037 1037

	
1038 1038
          // ReadMap<Key, Value> cmap;
1039 1039
          // b = cmap;
1040 1040

	
1041 1041
          ignore_unused_variable_warning(a);
1042 1042
          ignore_unused_variable_warning(a2);
1043 1043
          // ignore_unused_variable_warning(b);
1044 1044
        }
1045 1045

	
1046 1046
        const _Map &c;
1047 1047
        const Graph &g;
1048 1048
        const typename GraphMap::Value &t;
1049 1049
      };
1050 1050

	
1051 1051
    };
1052 1052

	
1053 1053
    /// \brief An empty mappable digraph class.
1054 1054
    ///
1055 1055
    /// This class provides beside the core digraph features
1056 1056
    /// map interface for the digraph structure.
1057 1057
    /// This concept is part of the Digraph concept.
1058 1058
    template <typename _Base = BaseDigraphComponent>
1059 1059
    class MappableDigraphComponent : public _Base  {
1060 1060
    public:
1061 1061

	
1062 1062
      typedef _Base Base;
1063 1063
      typedef typename Base::Node Node;
1064 1064
      typedef typename Base::Arc Arc;
1065 1065

	
1066 1066
      typedef MappableDigraphComponent Digraph;
1067 1067

	
1068 1068
      /// \brief ReadWrite map of the nodes.
1069 1069
      ///
1070 1070
      /// ReadWrite map of the nodes.
1071 1071
      ///
1072 1072
      template <typename _Value>
1073 1073
      class NodeMap : public GraphMap<Digraph, Node, _Value> {
1074 1074
      public:
1075 1075
        typedef GraphMap<MappableDigraphComponent, Node, _Value> Parent;
1076 1076

	
1077 1077
        /// \brief Construct a new map.
1078 1078
        ///
1079 1079
        /// Construct a new map for the digraph.
1080 1080
        explicit NodeMap(const MappableDigraphComponent& digraph)
1081 1081
          : Parent(digraph) {}
1082 1082

	
1083 1083
        /// \brief Construct a new map with default value.
1084 1084
        ///
1085 1085
        /// Construct a new map for the digraph and initalise the values.
1086 1086
        NodeMap(const MappableDigraphComponent& digraph, const _Value& value)
1087 1087
          : Parent(digraph, value) {}
1088 1088

	
1089 1089
      private:
1090 1090
        /// \brief Copy constructor.
1091 1091
        ///
1092 1092
        /// Copy Constructor.
1093 1093
        NodeMap(const NodeMap& nm) : Parent(nm) {}
1094 1094

	
1095 1095
        /// \brief Assign operator.
1096 1096
        ///
1097 1097
        /// Assign operator.
1098 1098
        template <typename CMap>
1099 1099
        NodeMap& operator=(const CMap&) {
1100 1100
          checkConcept<ReadMap<Node, _Value>, CMap>();
1101 1101
          return *this;
1102 1102
        }
1103 1103

	
1104 1104
      };
1105 1105

	
1106 1106
      /// \brief ReadWrite map of the arcs.
1107 1107
      ///
1108 1108
      /// ReadWrite map of the arcs.
1109 1109
      ///
1110 1110
      template <typename _Value>
1111 1111
      class ArcMap : public GraphMap<Digraph, Arc, _Value> {
1112 1112
      public:
1113 1113
        typedef GraphMap<MappableDigraphComponent, Arc, _Value> Parent;
1114 1114

	
1115 1115
        /// \brief Construct a new map.
1116 1116
        ///
1117 1117
        /// Construct a new map for the digraph.
1118 1118
        explicit ArcMap(const MappableDigraphComponent& digraph)
1119 1119
          : Parent(digraph) {}
1120 1120

	
1121 1121
        /// \brief Construct a new map with default value.
1122 1122
        ///
1123 1123
        /// Construct a new map for the digraph and initalise the values.
1124 1124
        ArcMap(const MappableDigraphComponent& digraph, const _Value& value)
1125 1125
          : Parent(digraph, value) {}
1126 1126

	
1127 1127
      private:
1128 1128
        /// \brief Copy constructor.
1129 1129
        ///
1130 1130
        /// Copy Constructor.
1131 1131
        ArcMap(const ArcMap& nm) : Parent(nm) {}
1132 1132

	
1133 1133
        /// \brief Assign operator.
1134 1134
        ///
1135 1135
        /// Assign operator.
1136 1136
        template <typename CMap>
1137 1137
        ArcMap& operator=(const CMap&) {
1138 1138
          checkConcept<ReadMap<Arc, _Value>, CMap>();
1139 1139
          return *this;
1140 1140
        }
1141 1141

	
1142 1142
      };
1143 1143

	
1144 1144

	
1145 1145
      template <typename _Digraph>
1146 1146
      struct Constraints {
1147 1147

	
1148 1148
        struct Dummy {
1149 1149
          int value;
1150 1150
          Dummy() : value(0) {}
1151 1151
          Dummy(int _v) : value(_v) {}
1152 1152
        };
1153 1153

	
1154 1154
        void constraints() {
1155 1155
          checkConcept<Base, _Digraph>();
1156 1156
          { // int map test
1157 1157
            typedef typename _Digraph::template NodeMap<int> IntNodeMap;
1158 1158
            checkConcept<GraphMap<_Digraph, typename _Digraph::Node, int>,
1159 1159
              IntNodeMap >();
1160 1160
          } { // bool map test
1161 1161
            typedef typename _Digraph::template NodeMap<bool> BoolNodeMap;
1162 1162
            checkConcept<GraphMap<_Digraph, typename _Digraph::Node, bool>,
1163 1163
              BoolNodeMap >();
1164 1164
          } { // Dummy map test
1165 1165
            typedef typename _Digraph::template NodeMap<Dummy> DummyNodeMap;
1166 1166
            checkConcept<GraphMap<_Digraph, typename _Digraph::Node, Dummy>,
1167 1167
              DummyNodeMap >();
1168 1168
          }
1169 1169

	
1170 1170
          { // int map test
1171 1171
            typedef typename _Digraph::template ArcMap<int> IntArcMap;
1172 1172
            checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, int>,
1173 1173
              IntArcMap >();
1174 1174
          } { // bool map test
1175 1175
            typedef typename _Digraph::template ArcMap<bool> BoolArcMap;
1176 1176
            checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, bool>,
1177 1177
              BoolArcMap >();
1178 1178
          } { // Dummy map test
1179 1179
            typedef typename _Digraph::template ArcMap<Dummy> DummyArcMap;
1180 1180
            checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, Dummy>,
1181 1181
              DummyArcMap >();
1182 1182
          }
1183 1183
        }
1184 1184

	
1185 1185
        _Digraph& digraph;
1186 1186
      };
1187 1187
    };
1188 1188

	
1189 1189
    /// \brief An empty mappable base bipartite graph class.
1190 1190
    ///
1191 1191
    /// This class provides beside the core graph features
1192 1192
    /// map interface for the graph structure.
1193 1193
    /// This concept is part of the Graph concept.
1194 1194
    template <typename _Base = BaseGraphComponent>
1195 1195
    class MappableGraphComponent : public MappableDigraphComponent<_Base>  {
1196 1196
    public:
1197 1197

	
1198 1198
      typedef _Base Base;
1199 1199
      typedef typename Base::Edge Edge;
1200 1200

	
1201 1201
      typedef MappableGraphComponent Graph;
1202 1202

	
1203 1203
      /// \brief ReadWrite map of the edges.
1204 1204
      ///
1205 1205
      /// ReadWrite map of the edges.
1206 1206
      ///
1207 1207
      template <typename _Value>
1208 1208
      class EdgeMap : public GraphMap<Graph, Edge, _Value> {
1209 1209
      public:
1210 1210
        typedef GraphMap<MappableGraphComponent, Edge, _Value> Parent;
1211 1211

	
1212 1212
        /// \brief Construct a new map.
1213 1213
        ///
1214 1214
        /// Construct a new map for the graph.
1215 1215
        explicit EdgeMap(const MappableGraphComponent& graph)
1216 1216
          : Parent(graph) {}
1217 1217

	
1218 1218
        /// \brief Construct a new map with default value.
1219 1219
        ///
1220 1220
        /// Construct a new map for the graph and initalise the values.
1221 1221
        EdgeMap(const MappableGraphComponent& graph, const _Value& value)
1222 1222
          : Parent(graph, value) {}
1223 1223

	
1224 1224
      private:
1225 1225
        /// \brief Copy constructor.
1226 1226
        ///
1227 1227
        /// Copy Constructor.
1228 1228
        EdgeMap(const EdgeMap& nm) : Parent(nm) {}
1229 1229

	
1230 1230
        /// \brief Assign operator.
1231 1231
        ///
1232 1232
        /// Assign operator.
1233 1233
        template <typename CMap>
1234 1234
        EdgeMap& operator=(const CMap&) {
1235 1235
          checkConcept<ReadMap<Edge, _Value>, CMap>();
1236 1236
          return *this;
1237 1237
        }
1238 1238

	
1239 1239
      };
1240 1240

	
1241 1241

	
1242 1242
      template <typename _Graph>
1243 1243
      struct Constraints {
1244 1244

	
1245 1245
        struct Dummy {
1246 1246
          int value;
1247 1247
          Dummy() : value(0) {}
1248 1248
          Dummy(int _v) : value(_v) {}
1249 1249
        };
1250 1250

	
1251 1251
        void constraints() {
1252 1252
          checkConcept<MappableGraphComponent<Base>, _Graph>();
1253 1253

	
1254 1254
          { // int map test
1255 1255
            typedef typename _Graph::template EdgeMap<int> IntEdgeMap;
1256 1256
            checkConcept<GraphMap<_Graph, typename _Graph::Edge, int>,
1257 1257
              IntEdgeMap >();
1258 1258
          } { // bool map test
1259 1259
            typedef typename _Graph::template EdgeMap<bool> BoolEdgeMap;
1260 1260
            checkConcept<GraphMap<_Graph, typename _Graph::Edge, bool>,
1261 1261
              BoolEdgeMap >();
1262 1262
          } { // Dummy map test
1263 1263
            typedef typename _Graph::template EdgeMap<Dummy> DummyEdgeMap;
1264 1264
            checkConcept<GraphMap<_Graph, typename _Graph::Edge, Dummy>,
1265 1265
              DummyEdgeMap >();
1266 1266
          }
1267 1267
        }
1268 1268

	
1269 1269
        _Graph& graph;
1270 1270
      };
1271 1271
    };
1272 1272

	
1273 1273
    /// \brief An empty extendable digraph class.
1274 1274
    ///
1275 1275
    /// This class provides beside the core digraph features digraph
1276 1276
    /// extendable interface for the digraph structure.  The main
1277 1277
    /// difference between the base and this interface is that the
1278 1278
    /// digraph alterations should handled already on this level.
1279 1279
    template <typename _Base = BaseDigraphComponent>
1280 1280
    class ExtendableDigraphComponent : public _Base {
1281 1281
    public:
1282 1282
      typedef _Base Base;
1283 1283

	
1284 1284
      typedef typename _Base::Node Node;
1285 1285
      typedef typename _Base::Arc Arc;
1286 1286

	
1287 1287
      /// \brief Adds a new node to the digraph.
1288 1288
      ///
1289 1289
      /// Adds a new node to the digraph.
1290 1290
      ///
1291 1291
      Node addNode() {
1292 1292
        return INVALID;
1293 1293
      }
1294 1294

	
1295 1295
      /// \brief Adds a new arc connects the given two nodes.
1296 1296
      ///
1297 1297
      /// Adds a new arc connects the the given two nodes.
1298 1298
      Arc addArc(const Node&, const Node&) {
1299 1299
        return INVALID;
1300 1300
      }
1301 1301

	
1302 1302
      template <typename _Digraph>
1303 1303
      struct Constraints {
1304 1304
        void constraints() {
1305 1305
          checkConcept<Base, _Digraph>();
1306 1306
          typename _Digraph::Node node_a, node_b;
1307 1307
          node_a = digraph.addNode();
1308 1308
          node_b = digraph.addNode();
1309 1309
          typename _Digraph::Arc arc;
1310 1310
          arc = digraph.addArc(node_a, node_b);
1311 1311
        }
1312 1312

	
1313 1313
        _Digraph& digraph;
1314 1314
      };
1315 1315
    };
1316 1316

	
1317 1317
    /// \brief An empty extendable base undirected graph class.
1318 1318
    ///
1319 1319
    /// This class provides beside the core undirected graph features
1320 1320
    /// core undircted graph extend interface for the graph structure.
1321 1321
    /// The main difference between the base and this interface is
1322 1322
    /// that the graph alterations should handled already on this
1323 1323
    /// level.
1324 1324
    template <typename _Base = BaseGraphComponent>
1325 1325
    class ExtendableGraphComponent : public _Base {
1326 1326
    public:
1327 1327

	
1328 1328
      typedef _Base Base;
1329 1329
      typedef typename _Base::Node Node;
1330 1330
      typedef typename _Base::Edge Edge;
1331 1331

	
1332 1332
      /// \brief Adds a new node to the graph.
1333 1333
      ///
1334 1334
      /// Adds a new node to the graph.
1335 1335
      ///
1336 1336
      Node addNode() {
1337 1337
        return INVALID;
1338 1338
      }
1339 1339

	
1340 1340
      /// \brief Adds a new arc connects the given two nodes.
1341 1341
      ///
1342 1342
      /// Adds a new arc connects the the given two nodes.
1343 1343
      Edge addArc(const Node&, const Node&) {
1344 1344
        return INVALID;
1345 1345
      }
1346 1346

	
1347 1347
      template <typename _Graph>
1348 1348
      struct Constraints {
1349 1349
        void constraints() {
1350 1350
          checkConcept<Base, _Graph>();
1351 1351
          typename _Graph::Node node_a, node_b;
1352 1352
          node_a = graph.addNode();
1353 1353
          node_b = graph.addNode();
1354 1354
          typename _Graph::Edge edge;
1355 1355
          edge = graph.addEdge(node_a, node_b);
1356 1356
        }
1357 1357

	
1358 1358
        _Graph& graph;
1359 1359
      };
1360 1360
    };
1361 1361

	
1362 1362
    /// \brief An empty erasable digraph class.
1363 1363
    ///
1364 1364
    /// This class provides beside the core digraph features core erase
1365 1365
    /// functions for the digraph structure. The main difference between
1366 1366
    /// the base and this interface is that the digraph alterations
1367 1367
    /// should handled already on this level.
1368 1368
    template <typename _Base = BaseDigraphComponent>
1369 1369
    class ErasableDigraphComponent : public _Base {
1370 1370
    public:
1371 1371

	
1372 1372
      typedef _Base Base;
1373 1373
      typedef typename Base::Node Node;
1374 1374
      typedef typename Base::Arc Arc;
1375 1375

	
1376 1376
      /// \brief Erase a node from the digraph.
1377 1377
      ///
1378 1378
      /// Erase a node from the digraph. This function should
1379 1379
      /// erase all arcs connecting to the node.
1380 1380
      void erase(const Node&) {}
1381 1381

	
1382 1382
      /// \brief Erase an arc from the digraph.
1383 1383
      ///
1384 1384
      /// Erase an arc from the digraph.
1385 1385
      ///
1386 1386
      void erase(const Arc&) {}
1387 1387

	
1388 1388
      template <typename _Digraph>
1389 1389
      struct Constraints {
1390 1390
        void constraints() {
1391 1391
          checkConcept<Base, _Digraph>();
1392 1392
          typename _Digraph::Node node;
1393 1393
          digraph.erase(node);
1394 1394
          typename _Digraph::Arc arc;
1395 1395
          digraph.erase(arc);
1396 1396
        }
1397 1397

	
1398 1398
        _Digraph& digraph;
1399 1399
      };
1400 1400
    };
1401 1401

	
1402 1402
    /// \brief An empty erasable base undirected graph class.
1403 1403
    ///
1404 1404
    /// This class provides beside the core undirected graph features
1405 1405
    /// core erase functions for the undirceted graph structure. The
1406 1406
    /// main difference between the base and this interface is that
1407 1407
    /// the graph alterations should handled already on this level.
1408 1408
    template <typename _Base = BaseGraphComponent>
1409 1409
    class ErasableGraphComponent : public _Base {
1410 1410
    public:
1411 1411

	
1412 1412
      typedef _Base Base;
1413 1413
      typedef typename Base::Node Node;
1414 1414
      typedef typename Base::Edge Edge;
1415 1415

	
1416 1416
      /// \brief Erase a node from the graph.
1417 1417
      ///
1418 1418
      /// Erase a node from the graph. This function should erase
1419 1419
      /// arcs connecting to the node.
1420 1420
      void erase(const Node&) {}
1421 1421

	
1422 1422
      /// \brief Erase an arc from the graph.
1423 1423
      ///
1424 1424
      /// Erase an arc from the graph.
1425 1425
      ///
1426 1426
      void erase(const Edge&) {}
1427 1427

	
1428 1428
      template <typename _Graph>
1429 1429
      struct Constraints {
1430 1430
        void constraints() {
1431 1431
          checkConcept<Base, _Graph>();
1432 1432
          typename _Graph::Node node;
1433 1433
          graph.erase(node);
1434 1434
          typename _Graph::Edge edge;
1435 1435
          graph.erase(edge);
1436 1436
        }
1437 1437

	
1438 1438
        _Graph& graph;
1439 1439
      };
1440 1440
    };
1441 1441

	
1442 1442
    /// \brief An empty clearable base digraph class.
1443 1443
    ///
1444 1444
    /// This class provides beside the core digraph features core clear
1445 1445
    /// functions for the digraph structure. The main difference between
1446 1446
    /// the base and this interface is that the digraph alterations
1447 1447
    /// should handled already on this level.
1448 1448
    template <typename _Base = BaseDigraphComponent>
1449 1449
    class ClearableDigraphComponent : public _Base {
1450 1450
    public:
1451 1451

	
1452 1452
      typedef _Base Base;
1453 1453

	
1454 1454
      /// \brief Erase all nodes and arcs from the digraph.
1455 1455
      ///
1456 1456
      /// Erase all nodes and arcs from the digraph.
1457 1457
      ///
1458 1458
      void clear() {}
1459 1459

	
1460 1460
      template <typename _Digraph>
1461 1461
      struct Constraints {
1462 1462
        void constraints() {
1463 1463
          checkConcept<Base, _Digraph>();
1464 1464
          digraph.clear();
1465 1465
        }
1466 1466

	
1467 1467
        _Digraph digraph;
1468 1468
      };
1469 1469
    };
1470 1470

	
1471 1471
    /// \brief An empty clearable base undirected graph class.
1472 1472
    ///
1473 1473
    /// This class provides beside the core undirected graph features
1474 1474
    /// core clear functions for the undirected graph structure. The
1475 1475
    /// main difference between the base and this interface is that
1476 1476
    /// the graph alterations should handled already on this level.
1477 1477
    template <typename _Base = BaseGraphComponent>
1478 1478
    class ClearableGraphComponent : public ClearableDigraphComponent<_Base> {
1479 1479
    public:
1480 1480

	
1481 1481
      typedef _Base Base;
1482 1482

	
1483 1483
      template <typename _Graph>
1484 1484
      struct Constraints {
1485 1485
        void constraints() {
1486 1486
          checkConcept<ClearableGraphComponent<Base>, _Graph>();
1487 1487
        }
1488 1488

	
1489 1489
        _Graph graph;
1490 1490
      };
1491 1491
    };
1492 1492

	
1493 1493
  }
1494 1494

	
1495 1495
}
1496 1496

	
1497 1497
#endif
Ignore white space 6 line context
... ...
@@ -21,1824 +21,1824 @@
21 21

	
22 22
#include <vector>
23 23
#include <algorithm>
24 24

	
25 25
#include <lemon/bits/enable_if.h>
26 26
#include <lemon/bits/traits.h>
27 27

	
28 28
///\file
29 29
///\brief LEMON core utilities.
30 30
///
31 31
///This header file contains core utilities for LEMON.
32 32
///It is automatically included by all graph types, therefore it usually
33 33
///do not have to be included directly.
34 34

	
35 35
namespace lemon {
36 36

	
37 37
  /// \brief Dummy type to make it easier to create invalid iterators.
38 38
  ///
39 39
  /// Dummy type to make it easier to create invalid iterators.
40 40
  /// See \ref INVALID for the usage.
41 41
  struct Invalid {
42 42
  public:
43 43
    bool operator==(Invalid) { return true;  }
44 44
    bool operator!=(Invalid) { return false; }
45 45
    bool operator< (Invalid) { return false; }
46 46
  };
47 47

	
48 48
  /// \brief Invalid iterators.
49 49
  ///
50 50
  /// \ref Invalid is a global type that converts to each iterator
51 51
  /// in such a way that the value of the target iterator will be invalid.
52 52
#ifdef LEMON_ONLY_TEMPLATES
53 53
  const Invalid INVALID = Invalid();
54 54
#else
55 55
  extern const Invalid INVALID;
56 56
#endif
57 57

	
58 58
  /// \addtogroup gutils
59 59
  /// @{
60 60

	
61 61
  ///Create convenience typedefs for the digraph types and iterators
62 62

	
63 63
  ///This \c \#define creates convenient type definitions for the following
64 64
  ///types of \c Digraph: \c Node,  \c NodeIt, \c Arc, \c ArcIt, \c InArcIt,
65 65
  ///\c OutArcIt, \c BoolNodeMap, \c IntNodeMap, \c DoubleNodeMap,
66 66
  ///\c BoolArcMap, \c IntArcMap, \c DoubleArcMap.
67 67
  ///
68 68
  ///\note If the graph type is a dependent type, ie. the graph type depend
69 69
  ///on a template parameter, then use \c TEMPLATE_DIGRAPH_TYPEDEFS()
70 70
  ///macro.
71 71
#define DIGRAPH_TYPEDEFS(Digraph)                                       \
72 72
  typedef Digraph::Node Node;                                           \
73 73
  typedef Digraph::NodeIt NodeIt;                                       \
74 74
  typedef Digraph::Arc Arc;                                             \
75 75
  typedef Digraph::ArcIt ArcIt;                                         \
76 76
  typedef Digraph::InArcIt InArcIt;                                     \
77 77
  typedef Digraph::OutArcIt OutArcIt;                                   \
78 78
  typedef Digraph::NodeMap<bool> BoolNodeMap;                           \
79 79
  typedef Digraph::NodeMap<int> IntNodeMap;                             \
80 80
  typedef Digraph::NodeMap<double> DoubleNodeMap;                       \
81 81
  typedef Digraph::ArcMap<bool> BoolArcMap;                             \
82 82
  typedef Digraph::ArcMap<int> IntArcMap;                               \
83 83
  typedef Digraph::ArcMap<double> DoubleArcMap
84 84

	
85 85
  ///Create convenience typedefs for the digraph types and iterators
86 86

	
87 87
  ///\see DIGRAPH_TYPEDEFS
88 88
  ///
89 89
  ///\note Use this macro, if the graph type is a dependent type,
90 90
  ///ie. the graph type depend on a template parameter.
91 91
#define TEMPLATE_DIGRAPH_TYPEDEFS(Digraph)                              \
92 92
  typedef typename Digraph::Node Node;                                  \
93 93
  typedef typename Digraph::NodeIt NodeIt;                              \
94 94
  typedef typename Digraph::Arc Arc;                                    \
95 95
  typedef typename Digraph::ArcIt ArcIt;                                \
96 96
  typedef typename Digraph::InArcIt InArcIt;                            \
97 97
  typedef typename Digraph::OutArcIt OutArcIt;                          \
98 98
  typedef typename Digraph::template NodeMap<bool> BoolNodeMap;         \
99 99
  typedef typename Digraph::template NodeMap<int> IntNodeMap;           \
100 100
  typedef typename Digraph::template NodeMap<double> DoubleNodeMap;     \
101 101
  typedef typename Digraph::template ArcMap<bool> BoolArcMap;           \
102 102
  typedef typename Digraph::template ArcMap<int> IntArcMap;             \
103 103
  typedef typename Digraph::template ArcMap<double> DoubleArcMap
104 104

	
105 105
  ///Create convenience typedefs for the graph types and iterators
106 106

	
107 107
  ///This \c \#define creates the same convenient type definitions as defined
108 108
  ///by \ref DIGRAPH_TYPEDEFS(Graph) and six more, namely it creates
109 109
  ///\c Edge, \c EdgeIt, \c IncEdgeIt, \c BoolEdgeMap, \c IntEdgeMap,
110 110
  ///\c DoubleEdgeMap.
111 111
  ///
112 112
  ///\note If the graph type is a dependent type, ie. the graph type depend
113 113
  ///on a template parameter, then use \c TEMPLATE_GRAPH_TYPEDEFS()
114 114
  ///macro.
115 115
#define GRAPH_TYPEDEFS(Graph)                                           \
116 116
  DIGRAPH_TYPEDEFS(Graph);                                              \
117 117
  typedef Graph::Edge Edge;                                             \
118 118
  typedef Graph::EdgeIt EdgeIt;                                         \
119 119
  typedef Graph::IncEdgeIt IncEdgeIt;                                   \
120 120
  typedef Graph::EdgeMap<bool> BoolEdgeMap;                             \
121 121
  typedef Graph::EdgeMap<int> IntEdgeMap;                               \
122 122
  typedef Graph::EdgeMap<double> DoubleEdgeMap
123 123

	
124 124
  ///Create convenience typedefs for the graph types and iterators
125 125

	
126 126
  ///\see GRAPH_TYPEDEFS
127 127
  ///
128 128
  ///\note Use this macro, if the graph type is a dependent type,
129 129
  ///ie. the graph type depend on a template parameter.
130 130
#define TEMPLATE_GRAPH_TYPEDEFS(Graph)                                  \
131 131
  TEMPLATE_DIGRAPH_TYPEDEFS(Graph);                                     \
132 132
  typedef typename Graph::Edge Edge;                                    \
133 133
  typedef typename Graph::EdgeIt EdgeIt;                                \
134 134
  typedef typename Graph::IncEdgeIt IncEdgeIt;                          \
135 135
  typedef typename Graph::template EdgeMap<bool> BoolEdgeMap;           \
136 136
  typedef typename Graph::template EdgeMap<int> IntEdgeMap;             \
137 137
  typedef typename Graph::template EdgeMap<double> DoubleEdgeMap
138 138

	
139 139
  /// \brief Function to count the items in a graph.
140 140
  ///
141 141
  /// This function counts the items (nodes, arcs etc.) in a graph.
142 142
  /// The complexity of the function is linear because
143 143
  /// it iterates on all of the items.
144 144
  template <typename Graph, typename Item>
145 145
  inline int countItems(const Graph& g) {
146 146
    typedef typename ItemSetTraits<Graph, Item>::ItemIt ItemIt;
147 147
    int num = 0;
148 148
    for (ItemIt it(g); it != INVALID; ++it) {
149 149
      ++num;
150 150
    }
151 151
    return num;
152 152
  }
153 153

	
154 154
  // Node counting:
155 155

	
156 156
  namespace _core_bits {
157 157

	
158 158
    template <typename Graph, typename Enable = void>
159 159
    struct CountNodesSelector {
160 160
      static int count(const Graph &g) {
161 161
        return countItems<Graph, typename Graph::Node>(g);
162 162
      }
163 163
    };
164 164

	
165 165
    template <typename Graph>
166 166
    struct CountNodesSelector<
167 167
      Graph, typename
168 168
      enable_if<typename Graph::NodeNumTag, void>::type>
169 169
    {
170 170
      static int count(const Graph &g) {
171 171
        return g.nodeNum();
172 172
      }
173 173
    };
174 174
  }
175 175

	
176 176
  /// \brief Function to count the nodes in the graph.
177 177
  ///
178 178
  /// This function counts the nodes in the graph.
179 179
  /// The complexity of the function is <em>O</em>(<em>n</em>), but for some
180 180
  /// graph structures it is specialized to run in <em>O</em>(1).
181 181
  ///
182 182
  /// \note If the graph contains a \c nodeNum() member function and a
183 183
  /// \c NodeNumTag tag then this function calls directly the member
184 184
  /// function to query the cardinality of the node set.
185 185
  template <typename Graph>
186 186
  inline int countNodes(const Graph& g) {
187 187
    return _core_bits::CountNodesSelector<Graph>::count(g);
188 188
  }
189 189

	
190 190
  // Arc counting:
191 191

	
192 192
  namespace _core_bits {
193 193

	
194 194
    template <typename Graph, typename Enable = void>
195 195
    struct CountArcsSelector {
196 196
      static int count(const Graph &g) {
197 197
        return countItems<Graph, typename Graph::Arc>(g);
198 198
      }
199 199
    };
200 200

	
201 201
    template <typename Graph>
202 202
    struct CountArcsSelector<
203 203
      Graph,
204 204
      typename enable_if<typename Graph::ArcNumTag, void>::type>
205 205
    {
206 206
      static int count(const Graph &g) {
207 207
        return g.arcNum();
208 208
      }
209 209
    };
210 210
  }
211 211

	
212 212
  /// \brief Function to count the arcs in the graph.
213 213
  ///
214 214
  /// This function counts the arcs in the graph.
215 215
  /// The complexity of the function is <em>O</em>(<em>m</em>), but for some
216 216
  /// graph structures it is specialized to run in <em>O</em>(1).
217 217
  ///
218 218
  /// \note If the graph contains a \c arcNum() member function and a
219 219
  /// \c ArcNumTag tag then this function calls directly the member
220 220
  /// function to query the cardinality of the arc set.
221 221
  template <typename Graph>
222 222
  inline int countArcs(const Graph& g) {
223 223
    return _core_bits::CountArcsSelector<Graph>::count(g);
224 224
  }
225 225

	
226 226
  // Edge counting:
227 227

	
228 228
  namespace _core_bits {
229 229

	
230 230
    template <typename Graph, typename Enable = void>
231 231
    struct CountEdgesSelector {
232 232
      static int count(const Graph &g) {
233 233
        return countItems<Graph, typename Graph::Edge>(g);
234 234
      }
235 235
    };
236 236

	
237 237
    template <typename Graph>
238 238
    struct CountEdgesSelector<
239 239
      Graph,
240 240
      typename enable_if<typename Graph::EdgeNumTag, void>::type>
241 241
    {
242 242
      static int count(const Graph &g) {
243 243
        return g.edgeNum();
244 244
      }
245 245
    };
246 246
  }
247 247

	
248 248
  /// \brief Function to count the edges in the graph.
249 249
  ///
250 250
  /// This function counts the edges in the graph.
251 251
  /// The complexity of the function is <em>O</em>(<em>m</em>), but for some
252 252
  /// graph structures it is specialized to run in <em>O</em>(1).
253 253
  ///
254 254
  /// \note If the graph contains a \c edgeNum() member function and a
255 255
  /// \c EdgeNumTag tag then this function calls directly the member
256 256
  /// function to query the cardinality of the edge set.
257 257
  template <typename Graph>
258 258
  inline int countEdges(const Graph& g) {
259 259
    return _core_bits::CountEdgesSelector<Graph>::count(g);
260 260

	
261 261
  }
262 262

	
263 263

	
264 264
  template <typename Graph, typename DegIt>
265 265
  inline int countNodeDegree(const Graph& _g, const typename Graph::Node& _n) {
266 266
    int num = 0;
267 267
    for (DegIt it(_g, _n); it != INVALID; ++it) {
268 268
      ++num;
269 269
    }
270 270
    return num;
271 271
  }
272 272

	
273 273
  /// \brief Function to count the number of the out-arcs from node \c n.
274 274
  ///
275 275
  /// This function counts the number of the out-arcs from node \c n
276 276
  /// in the graph \c g.
277 277
  template <typename Graph>
278 278
  inline int countOutArcs(const Graph& g,  const typename Graph::Node& n) {
279 279
    return countNodeDegree<Graph, typename Graph::OutArcIt>(g, n);
280 280
  }
281 281

	
282 282
  /// \brief Function to count the number of the in-arcs to node \c n.
283 283
  ///
284 284
  /// This function counts the number of the in-arcs to node \c n
285 285
  /// in the graph \c g.
286 286
  template <typename Graph>
287 287
  inline int countInArcs(const Graph& g,  const typename Graph::Node& n) {
288 288
    return countNodeDegree<Graph, typename Graph::InArcIt>(g, n);
289 289
  }
290 290

	
291 291
  /// \brief Function to count the number of the inc-edges to node \c n.
292 292
  ///
293 293
  /// This function counts the number of the inc-edges to node \c n
294 294
  /// in the undirected graph \c g.
295 295
  template <typename Graph>
296 296
  inline int countIncEdges(const Graph& g,  const typename Graph::Node& n) {
297 297
    return countNodeDegree<Graph, typename Graph::IncEdgeIt>(g, n);
298 298
  }
299 299

	
300 300
  namespace _core_bits {
301 301

	
302 302
    template <typename Digraph, typename Item, typename RefMap>
303 303
    class MapCopyBase {
304 304
    public:
305 305
      virtual void copy(const Digraph& from, const RefMap& refMap) = 0;
306 306

	
307 307
      virtual ~MapCopyBase() {}
308 308
    };
309 309

	
310 310
    template <typename Digraph, typename Item, typename RefMap,
311 311
              typename FromMap, typename ToMap>
312 312
    class MapCopy : public MapCopyBase<Digraph, Item, RefMap> {
313 313
    public:
314 314

	
315 315
      MapCopy(const FromMap& map, ToMap& tmap)
316 316
        : _map(map), _tmap(tmap) {}
317 317

	
318 318
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
319 319
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
320 320
        for (ItemIt it(digraph); it != INVALID; ++it) {
321 321
          _tmap.set(refMap[it], _map[it]);
322 322
        }
323 323
      }
324 324

	
325 325
    private:
326 326
      const FromMap& _map;
327 327
      ToMap& _tmap;
328 328
    };
329 329

	
330 330
    template <typename Digraph, typename Item, typename RefMap, typename It>
331 331
    class ItemCopy : public MapCopyBase<Digraph, Item, RefMap> {
332 332
    public:
333 333

	
334 334
      ItemCopy(const Item& item, It& it) : _item(item), _it(it) {}
335 335

	
336 336
      virtual void copy(const Digraph&, const RefMap& refMap) {
337 337
        _it = refMap[_item];
338 338
      }
339 339

	
340 340
    private:
341 341
      Item _item;
342 342
      It& _it;
343 343
    };
344 344

	
345 345
    template <typename Digraph, typename Item, typename RefMap, typename Ref>
346 346
    class RefCopy : public MapCopyBase<Digraph, Item, RefMap> {
347 347
    public:
348 348

	
349 349
      RefCopy(Ref& map) : _map(map) {}
350 350

	
351 351
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
352 352
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
353 353
        for (ItemIt it(digraph); it != INVALID; ++it) {
354 354
          _map.set(it, refMap[it]);
355 355
        }
356 356
      }
357 357

	
358 358
    private:
359 359
      Ref& _map;
360 360
    };
361 361

	
362 362
    template <typename Digraph, typename Item, typename RefMap,
363 363
              typename CrossRef>
364 364
    class CrossRefCopy : public MapCopyBase<Digraph, Item, RefMap> {
365 365
    public:
366 366

	
367 367
      CrossRefCopy(CrossRef& cmap) : _cmap(cmap) {}
368 368

	
369 369
      virtual void copy(const Digraph& digraph, const RefMap& refMap) {
370 370
        typedef typename ItemSetTraits<Digraph, Item>::ItemIt ItemIt;
371 371
        for (ItemIt it(digraph); it != INVALID; ++it) {
372 372
          _cmap.set(refMap[it], it);
373 373
        }
374 374
      }
375 375

	
376 376
    private:
377 377
      CrossRef& _cmap;
378 378
    };
379 379

	
380 380
    template <typename Digraph, typename Enable = void>
381 381
    struct DigraphCopySelector {
382 382
      template <typename From, typename NodeRefMap, typename ArcRefMap>
383 383
      static void copy(const From& from, Digraph &to,
384 384
                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
385 385
        for (typename From::NodeIt it(from); it != INVALID; ++it) {
386 386
          nodeRefMap[it] = to.addNode();
387 387
        }
388 388
        for (typename From::ArcIt it(from); it != INVALID; ++it) {
389 389
          arcRefMap[it] = to.addArc(nodeRefMap[from.source(it)],
390 390
                                    nodeRefMap[from.target(it)]);
391 391
        }
392 392
      }
393 393
    };
394 394

	
395 395
    template <typename Digraph>
396 396
    struct DigraphCopySelector<
397 397
      Digraph,
398 398
      typename enable_if<typename Digraph::BuildTag, void>::type>
399 399
    {
400 400
      template <typename From, typename NodeRefMap, typename ArcRefMap>
401 401
      static void copy(const From& from, Digraph &to,
402 402
                       NodeRefMap& nodeRefMap, ArcRefMap& arcRefMap) {
403 403
        to.build(from, nodeRefMap, arcRefMap);
404 404
      }
405 405
    };
406 406

	
407 407
    template <typename Graph, typename Enable = void>
408 408
    struct GraphCopySelector {
409 409
      template <typename From, typename NodeRefMap, typename EdgeRefMap>
410 410
      static void copy(const From& from, Graph &to,
411 411
                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
412 412
        for (typename From::NodeIt it(from); it != INVALID; ++it) {
413 413
          nodeRefMap[it] = to.addNode();
414 414
        }
415 415
        for (typename From::EdgeIt it(from); it != INVALID; ++it) {
416 416
          edgeRefMap[it] = to.addEdge(nodeRefMap[from.u(it)],
417 417
                                      nodeRefMap[from.v(it)]);
418 418
        }
419 419
      }
420 420
    };
421 421

	
422 422
    template <typename Graph>
423 423
    struct GraphCopySelector<
424 424
      Graph,
425 425
      typename enable_if<typename Graph::BuildTag, void>::type>
426 426
    {
427 427
      template <typename From, typename NodeRefMap, typename EdgeRefMap>
428 428
      static void copy(const From& from, Graph &to,
429 429
                       NodeRefMap& nodeRefMap, EdgeRefMap& edgeRefMap) {
430 430
        to.build(from, nodeRefMap, edgeRefMap);
431 431
      }
432 432
    };
433 433

	
434 434
  }
435 435

	
436 436
  /// \brief Class to copy a digraph.
437 437
  ///
438 438
  /// Class to copy a digraph to another digraph (duplicate a digraph). The
439 439
  /// simplest way of using it is through the \c digraphCopy() function.
440 440
  ///
441 441
  /// This class not only make a copy of a digraph, but it can create
442 442
  /// references and cross references between the nodes and arcs of
443 443
  /// the two digraphs, and it can copy maps to use with the newly created
444 444
  /// digraph.
445 445
  ///
446 446
  /// To make a copy from a digraph, first an instance of DigraphCopy
447 447
  /// should be created, then the data belongs to the digraph should
448 448
  /// assigned to copy. In the end, the \c run() member should be
449 449
  /// called.
450 450
  ///
451 451
  /// The next code copies a digraph with several data:
452 452
  ///\code
453 453
  ///  DigraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
454 454
  ///  // Create references for the nodes
455 455
  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
456 456
  ///  cg.nodeRef(nr);
457 457
  ///  // Create cross references (inverse) for the arcs
458 458
  ///  NewGraph::ArcMap<OrigGraph::Arc> acr(new_graph);
459 459
  ///  cg.arcCrossRef(acr);
460 460
  ///  // Copy an arc map
461 461
  ///  OrigGraph::ArcMap<double> oamap(orig_graph);
462 462
  ///  NewGraph::ArcMap<double> namap(new_graph);
463 463
  ///  cg.arcMap(oamap, namap);
464 464
  ///  // Copy a node
465 465
  ///  OrigGraph::Node on;
466 466
  ///  NewGraph::Node nn;
467 467
  ///  cg.node(on, nn);
468 468
  ///  // Execute copying
469 469
  ///  cg.run();
470 470
  ///\endcode
471 471
  template <typename From, typename To>
472 472
  class DigraphCopy {
473 473
  private:
474 474

	
475 475
    typedef typename From::Node Node;
476 476
    typedef typename From::NodeIt NodeIt;
477 477
    typedef typename From::Arc Arc;
478 478
    typedef typename From::ArcIt ArcIt;
479 479

	
480 480
    typedef typename To::Node TNode;
481 481
    typedef typename To::Arc TArc;
482 482

	
483 483
    typedef typename From::template NodeMap<TNode> NodeRefMap;
484 484
    typedef typename From::template ArcMap<TArc> ArcRefMap;
485 485

	
486 486
  public:
487 487

	
488 488
    /// \brief Constructor of DigraphCopy.
489 489
    ///
490 490
    /// Constructor of DigraphCopy for copying the content of the
491 491
    /// \c from digraph into the \c to digraph.
492 492
    DigraphCopy(const From& from, To& to)
493 493
      : _from(from), _to(to) {}
494 494

	
495 495
    /// \brief Destructor of DigraphCopy
496 496
    ///
497 497
    /// Destructor of DigraphCopy.
498 498
    ~DigraphCopy() {
499 499
      for (int i = 0; i < int(_node_maps.size()); ++i) {
500 500
        delete _node_maps[i];
501 501
      }
502 502
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
503 503
        delete _arc_maps[i];
504 504
      }
505 505

	
506 506
    }
507 507

	
508 508
    /// \brief Copy the node references into the given map.
509 509
    ///
510 510
    /// This function copies the node references into the given map.
511 511
    /// The parameter should be a map, whose key type is the Node type of
512 512
    /// the source digraph, while the value type is the Node type of the
513 513
    /// destination digraph.
514 514
    template <typename NodeRef>
515 515
    DigraphCopy& nodeRef(NodeRef& map) {
516 516
      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
517 517
                           NodeRefMap, NodeRef>(map));
518 518
      return *this;
519 519
    }
520 520

	
521 521
    /// \brief Copy the node cross references into the given map.
522 522
    ///
523 523
    /// This function copies the node cross references (reverse references)
524 524
    /// into the given map. The parameter should be a map, whose key type
525 525
    /// is the Node type of the destination digraph, while the value type is
526 526
    /// the Node type of the source digraph.
527 527
    template <typename NodeCrossRef>
528 528
    DigraphCopy& nodeCrossRef(NodeCrossRef& map) {
529 529
      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
530 530
                           NodeRefMap, NodeCrossRef>(map));
531 531
      return *this;
532 532
    }
533 533

	
534 534
    /// \brief Make a copy of the given node map.
535 535
    ///
536 536
    /// This function makes a copy of the given node map for the newly
537 537
    /// created digraph.
538 538
    /// The key type of the new map \c tmap should be the Node type of the
539 539
    /// destination digraph, and the key type of the original map \c map
540 540
    /// should be the Node type of the source digraph.
541 541
    template <typename FromMap, typename ToMap>
542 542
    DigraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
543 543
      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
544 544
                           NodeRefMap, FromMap, ToMap>(map, tmap));
545 545
      return *this;
546 546
    }
547 547

	
548 548
    /// \brief Make a copy of the given node.
549 549
    ///
550 550
    /// This function makes a copy of the given node.
551 551
    DigraphCopy& node(const Node& node, TNode& tnode) {
552 552
      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
553 553
                           NodeRefMap, TNode>(node, tnode));
554 554
      return *this;
555 555
    }
556 556

	
557 557
    /// \brief Copy the arc references into the given map.
558 558
    ///
559 559
    /// This function copies the arc references into the given map.
560 560
    /// The parameter should be a map, whose key type is the Arc type of
561 561
    /// the source digraph, while the value type is the Arc type of the
562 562
    /// destination digraph.
563 563
    template <typename ArcRef>
564 564
    DigraphCopy& arcRef(ArcRef& map) {
565 565
      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
566 566
                          ArcRefMap, ArcRef>(map));
567 567
      return *this;
568 568
    }
569 569

	
570 570
    /// \brief Copy the arc cross references into the given map.
571 571
    ///
572 572
    /// This function copies the arc cross references (reverse references)
573 573
    /// into the given map. The parameter should be a map, whose key type
574 574
    /// is the Arc type of the destination digraph, while the value type is
575 575
    /// the Arc type of the source digraph.
576 576
    template <typename ArcCrossRef>
577 577
    DigraphCopy& arcCrossRef(ArcCrossRef& map) {
578 578
      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
579 579
                          ArcRefMap, ArcCrossRef>(map));
580 580
      return *this;
581 581
    }
582 582

	
583 583
    /// \brief Make a copy of the given arc map.
584 584
    ///
585 585
    /// This function makes a copy of the given arc map for the newly
586 586
    /// created digraph.
587 587
    /// The key type of the new map \c tmap should be the Arc type of the
588 588
    /// destination digraph, and the key type of the original map \c map
589 589
    /// should be the Arc type of the source digraph.
590 590
    template <typename FromMap, typename ToMap>
591 591
    DigraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
592 592
      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
593 593
                          ArcRefMap, FromMap, ToMap>(map, tmap));
594 594
      return *this;
595 595
    }
596 596

	
597 597
    /// \brief Make a copy of the given arc.
598 598
    ///
599 599
    /// This function makes a copy of the given arc.
600 600
    DigraphCopy& arc(const Arc& arc, TArc& tarc) {
601 601
      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
602 602
                          ArcRefMap, TArc>(arc, tarc));
603 603
      return *this;
604 604
    }
605 605

	
606 606
    /// \brief Execute copying.
607 607
    ///
608 608
    /// This function executes the copying of the digraph along with the
609 609
    /// copying of the assigned data.
610 610
    void run() {
611 611
      NodeRefMap nodeRefMap(_from);
612 612
      ArcRefMap arcRefMap(_from);
613 613
      _core_bits::DigraphCopySelector<To>::
614 614
        copy(_from, _to, nodeRefMap, arcRefMap);
615 615
      for (int i = 0; i < int(_node_maps.size()); ++i) {
616 616
        _node_maps[i]->copy(_from, nodeRefMap);
617 617
      }
618 618
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
619 619
        _arc_maps[i]->copy(_from, arcRefMap);
620 620
      }
621 621
    }
622 622

	
623 623
  protected:
624 624

	
625 625
    const From& _from;
626 626
    To& _to;
627 627

	
628 628
    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
629 629
      _node_maps;
630 630

	
631 631
    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
632 632
      _arc_maps;
633 633

	
634 634
  };
635 635

	
636 636
  /// \brief Copy a digraph to another digraph.
637 637
  ///
638 638
  /// This function copies a digraph to another digraph.
639 639
  /// The complete usage of it is detailed in the DigraphCopy class, but
640 640
  /// a short example shows a basic work:
641 641
  ///\code
642 642
  /// digraphCopy(src, trg).nodeRef(nr).arcCrossRef(acr).run();
643 643
  ///\endcode
644 644
  ///
645 645
  /// After the copy the \c nr map will contain the mapping from the
646 646
  /// nodes of the \c from digraph to the nodes of the \c to digraph and
647 647
  /// \c acr will contain the mapping from the arcs of the \c to digraph
648 648
  /// to the arcs of the \c from digraph.
649 649
  ///
650 650
  /// \see DigraphCopy
651 651
  template <typename From, typename To>
652 652
  DigraphCopy<From, To> digraphCopy(const From& from, To& to) {
653 653
    return DigraphCopy<From, To>(from, to);
654 654
  }
655 655

	
656 656
  /// \brief Class to copy a graph.
657 657
  ///
658 658
  /// Class to copy a graph to another graph (duplicate a graph). The
659 659
  /// simplest way of using it is through the \c graphCopy() function.
660 660
  ///
661 661
  /// This class not only make a copy of a graph, but it can create
662 662
  /// references and cross references between the nodes, edges and arcs of
663 663
  /// the two graphs, and it can copy maps for using with the newly created
664 664
  /// graph.
665 665
  ///
666 666
  /// To make a copy from a graph, first an instance of GraphCopy
667 667
  /// should be created, then the data belongs to the graph should
668 668
  /// assigned to copy. In the end, the \c run() member should be
669 669
  /// called.
670 670
  ///
671 671
  /// The next code copies a graph with several data:
672 672
  ///\code
673 673
  ///  GraphCopy<OrigGraph, NewGraph> cg(orig_graph, new_graph);
674 674
  ///  // Create references for the nodes
675 675
  ///  OrigGraph::NodeMap<NewGraph::Node> nr(orig_graph);
676 676
  ///  cg.nodeRef(nr);
677 677
  ///  // Create cross references (inverse) for the edges
678 678
  ///  NewGraph::EdgeMap<OrigGraph::Edge> ecr(new_graph);
679 679
  ///  cg.edgeCrossRef(ecr);
680 680
  ///  // Copy an edge map
681 681
  ///  OrigGraph::EdgeMap<double> oemap(orig_graph);
682 682
  ///  NewGraph::EdgeMap<double> nemap(new_graph);
683 683
  ///  cg.edgeMap(oemap, nemap);
684 684
  ///  // Copy a node
685 685
  ///  OrigGraph::Node on;
686 686
  ///  NewGraph::Node nn;
687 687
  ///  cg.node(on, nn);
688 688
  ///  // Execute copying
689 689
  ///  cg.run();
690 690
  ///\endcode
691 691
  template <typename From, typename To>
692 692
  class GraphCopy {
693 693
  private:
694 694

	
695 695
    typedef typename From::Node Node;
696 696
    typedef typename From::NodeIt NodeIt;
697 697
    typedef typename From::Arc Arc;
698 698
    typedef typename From::ArcIt ArcIt;
699 699
    typedef typename From::Edge Edge;
700 700
    typedef typename From::EdgeIt EdgeIt;
701 701

	
702 702
    typedef typename To::Node TNode;
703 703
    typedef typename To::Arc TArc;
704 704
    typedef typename To::Edge TEdge;
705 705

	
706 706
    typedef typename From::template NodeMap<TNode> NodeRefMap;
707 707
    typedef typename From::template EdgeMap<TEdge> EdgeRefMap;
708 708

	
709 709
    struct ArcRefMap {
710 710
      ArcRefMap(const From& from, const To& to,
711 711
                const EdgeRefMap& edge_ref, const NodeRefMap& node_ref)
712 712
        : _from(from), _to(to),
713 713
          _edge_ref(edge_ref), _node_ref(node_ref) {}
714 714

	
715 715
      typedef typename From::Arc Key;
716 716
      typedef typename To::Arc Value;
717 717

	
718 718
      Value operator[](const Key& key) const {
719 719
        bool forward = _from.u(key) != _from.v(key) ?
720 720
          _node_ref[_from.source(key)] ==
721 721
          _to.source(_to.direct(_edge_ref[key], true)) :
722 722
          _from.direction(key);
723 723
        return _to.direct(_edge_ref[key], forward);
724 724
      }
725 725

	
726 726
      const From& _from;
727 727
      const To& _to;
728 728
      const EdgeRefMap& _edge_ref;
729 729
      const NodeRefMap& _node_ref;
730 730
    };
731 731

	
732 732
  public:
733 733

	
734 734
    /// \brief Constructor of GraphCopy.
735 735
    ///
736 736
    /// Constructor of GraphCopy for copying the content of the
737 737
    /// \c from graph into the \c to graph.
738 738
    GraphCopy(const From& from, To& to)
739 739
      : _from(from), _to(to) {}
740 740

	
741 741
    /// \brief Destructor of GraphCopy
742 742
    ///
743 743
    /// Destructor of GraphCopy.
744 744
    ~GraphCopy() {
745 745
      for (int i = 0; i < int(_node_maps.size()); ++i) {
746 746
        delete _node_maps[i];
747 747
      }
748 748
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
749 749
        delete _arc_maps[i];
750 750
      }
751 751
      for (int i = 0; i < int(_edge_maps.size()); ++i) {
752 752
        delete _edge_maps[i];
753 753
      }
754 754
    }
755 755

	
756 756
    /// \brief Copy the node references into the given map.
757 757
    ///
758 758
    /// This function copies the node references into the given map.
759 759
    /// The parameter should be a map, whose key type is the Node type of
760 760
    /// the source graph, while the value type is the Node type of the
761 761
    /// destination graph.
762 762
    template <typename NodeRef>
763 763
    GraphCopy& nodeRef(NodeRef& map) {
764 764
      _node_maps.push_back(new _core_bits::RefCopy<From, Node,
765 765
                           NodeRefMap, NodeRef>(map));
766 766
      return *this;
767 767
    }
768 768

	
769 769
    /// \brief Copy the node cross references into the given map.
770 770
    ///
771 771
    /// This function copies the node cross references (reverse references)
772 772
    /// into the given map. The parameter should be a map, whose key type
773 773
    /// is the Node type of the destination graph, while the value type is
774 774
    /// the Node type of the source graph.
775 775
    template <typename NodeCrossRef>
776 776
    GraphCopy& nodeCrossRef(NodeCrossRef& map) {
777 777
      _node_maps.push_back(new _core_bits::CrossRefCopy<From, Node,
778 778
                           NodeRefMap, NodeCrossRef>(map));
779 779
      return *this;
780 780
    }
781 781

	
782 782
    /// \brief Make a copy of the given node map.
783 783
    ///
784 784
    /// This function makes a copy of the given node map for the newly
785 785
    /// created graph.
786 786
    /// The key type of the new map \c tmap should be the Node type of the
787 787
    /// destination graph, and the key type of the original map \c map
788 788
    /// should be the Node type of the source graph.
789 789
    template <typename FromMap, typename ToMap>
790 790
    GraphCopy& nodeMap(const FromMap& map, ToMap& tmap) {
791 791
      _node_maps.push_back(new _core_bits::MapCopy<From, Node,
792 792
                           NodeRefMap, FromMap, ToMap>(map, tmap));
793 793
      return *this;
794 794
    }
795 795

	
796 796
    /// \brief Make a copy of the given node.
797 797
    ///
798 798
    /// This function makes a copy of the given node.
799 799
    GraphCopy& node(const Node& node, TNode& tnode) {
800 800
      _node_maps.push_back(new _core_bits::ItemCopy<From, Node,
801 801
                           NodeRefMap, TNode>(node, tnode));
802 802
      return *this;
803 803
    }
804 804

	
805 805
    /// \brief Copy the arc references into the given map.
806 806
    ///
807 807
    /// This function copies the arc references into the given map.
808 808
    /// The parameter should be a map, whose key type is the Arc type of
809 809
    /// the source graph, while the value type is the Arc type of the
810 810
    /// destination graph.
811 811
    template <typename ArcRef>
812 812
    GraphCopy& arcRef(ArcRef& map) {
813 813
      _arc_maps.push_back(new _core_bits::RefCopy<From, Arc,
814 814
                          ArcRefMap, ArcRef>(map));
815 815
      return *this;
816 816
    }
817 817

	
818 818
    /// \brief Copy the arc cross references into the given map.
819 819
    ///
820 820
    /// This function copies the arc cross references (reverse references)
821 821
    /// into the given map. The parameter should be a map, whose key type
822 822
    /// is the Arc type of the destination graph, while the value type is
823 823
    /// the Arc type of the source graph.
824 824
    template <typename ArcCrossRef>
825 825
    GraphCopy& arcCrossRef(ArcCrossRef& map) {
826 826
      _arc_maps.push_back(new _core_bits::CrossRefCopy<From, Arc,
827 827
                          ArcRefMap, ArcCrossRef>(map));
828 828
      return *this;
829 829
    }
830 830

	
831 831
    /// \brief Make a copy of the given arc map.
832 832
    ///
833 833
    /// This function makes a copy of the given arc map for the newly
834 834
    /// created graph.
835 835
    /// The key type of the new map \c tmap should be the Arc type of the
836 836
    /// destination graph, and the key type of the original map \c map
837 837
    /// should be the Arc type of the source graph.
838 838
    template <typename FromMap, typename ToMap>
839 839
    GraphCopy& arcMap(const FromMap& map, ToMap& tmap) {
840 840
      _arc_maps.push_back(new _core_bits::MapCopy<From, Arc,
841 841
                          ArcRefMap, FromMap, ToMap>(map, tmap));
842 842
      return *this;
843 843
    }
844 844

	
845 845
    /// \brief Make a copy of the given arc.
846 846
    ///
847 847
    /// This function makes a copy of the given arc.
848 848
    GraphCopy& arc(const Arc& arc, TArc& tarc) {
849 849
      _arc_maps.push_back(new _core_bits::ItemCopy<From, Arc,
850 850
                          ArcRefMap, TArc>(arc, tarc));
851 851
      return *this;
852 852
    }
853 853

	
854 854
    /// \brief Copy the edge references into the given map.
855 855
    ///
856 856
    /// This function copies the edge references into the given map.
857 857
    /// The parameter should be a map, whose key type is the Edge type of
858 858
    /// the source graph, while the value type is the Edge type of the
859 859
    /// destination graph.
860 860
    template <typename EdgeRef>
861 861
    GraphCopy& edgeRef(EdgeRef& map) {
862 862
      _edge_maps.push_back(new _core_bits::RefCopy<From, Edge,
863 863
                           EdgeRefMap, EdgeRef>(map));
864 864
      return *this;
865 865
    }
866 866

	
867 867
    /// \brief Copy the edge cross references into the given map.
868 868
    ///
869 869
    /// This function copies the edge cross references (reverse references)
870 870
    /// into the given map. The parameter should be a map, whose key type
871 871
    /// is the Edge type of the destination graph, while the value type is
872 872
    /// the Edge type of the source graph.
873 873
    template <typename EdgeCrossRef>
874 874
    GraphCopy& edgeCrossRef(EdgeCrossRef& map) {
875 875
      _edge_maps.push_back(new _core_bits::CrossRefCopy<From,
876 876
                           Edge, EdgeRefMap, EdgeCrossRef>(map));
877 877
      return *this;
878 878
    }
879 879

	
880 880
    /// \brief Make a copy of the given edge map.
881 881
    ///
882 882
    /// This function makes a copy of the given edge map for the newly
883 883
    /// created graph.
884 884
    /// The key type of the new map \c tmap should be the Edge type of the
885 885
    /// destination graph, and the key type of the original map \c map
886 886
    /// should be the Edge type of the source graph.
887 887
    template <typename FromMap, typename ToMap>
888 888
    GraphCopy& edgeMap(const FromMap& map, ToMap& tmap) {
889 889
      _edge_maps.push_back(new _core_bits::MapCopy<From, Edge,
890 890
                           EdgeRefMap, FromMap, ToMap>(map, tmap));
891 891
      return *this;
892 892
    }
893 893

	
894 894
    /// \brief Make a copy of the given edge.
895 895
    ///
896 896
    /// This function makes a copy of the given edge.
897 897
    GraphCopy& edge(const Edge& edge, TEdge& tedge) {
898 898
      _edge_maps.push_back(new _core_bits::ItemCopy<From, Edge,
899 899
                           EdgeRefMap, TEdge>(edge, tedge));
900 900
      return *this;
901 901
    }
902 902

	
903 903
    /// \brief Execute copying.
904 904
    ///
905 905
    /// This function executes the copying of the graph along with the
906 906
    /// copying of the assigned data.
907 907
    void run() {
908 908
      NodeRefMap nodeRefMap(_from);
909 909
      EdgeRefMap edgeRefMap(_from);
910 910
      ArcRefMap arcRefMap(_from, _to, edgeRefMap, nodeRefMap);
911 911
      _core_bits::GraphCopySelector<To>::
912 912
        copy(_from, _to, nodeRefMap, edgeRefMap);
913 913
      for (int i = 0; i < int(_node_maps.size()); ++i) {
914 914
        _node_maps[i]->copy(_from, nodeRefMap);
915 915
      }
916 916
      for (int i = 0; i < int(_edge_maps.size()); ++i) {
917 917
        _edge_maps[i]->copy(_from, edgeRefMap);
918 918
      }
919 919
      for (int i = 0; i < int(_arc_maps.size()); ++i) {
920 920
        _arc_maps[i]->copy(_from, arcRefMap);
921 921
      }
922 922
    }
923 923

	
924 924
  private:
925 925

	
926 926
    const From& _from;
927 927
    To& _to;
928 928

	
929 929
    std::vector<_core_bits::MapCopyBase<From, Node, NodeRefMap>* >
930 930
      _node_maps;
931 931

	
932 932
    std::vector<_core_bits::MapCopyBase<From, Arc, ArcRefMap>* >
933 933
      _arc_maps;
934 934

	
935 935
    std::vector<_core_bits::MapCopyBase<From, Edge, EdgeRefMap>* >
936 936
      _edge_maps;
937 937

	
938 938
  };
939 939

	
940 940
  /// \brief Copy a graph to another graph.
941 941
  ///
942 942
  /// This function copies a graph to another graph.
943 943
  /// The complete usage of it is detailed in the GraphCopy class,
944 944
  /// but a short example shows a basic work:
945 945
  ///\code
946 946
  /// graphCopy(src, trg).nodeRef(nr).edgeCrossRef(ecr).run();
947 947
  ///\endcode
948 948
  ///
949 949
  /// After the copy the \c nr map will contain the mapping from the
950 950
  /// nodes of the \c from graph to the nodes of the \c to graph and
951 951
  /// \c ecr will contain the mapping from the edges of the \c to graph
952 952
  /// to the edges of the \c from graph.
953 953
  ///
954 954
  /// \see GraphCopy
955 955
  template <typename From, typename To>
956 956
  GraphCopy<From, To>
957 957
  graphCopy(const From& from, To& to) {
958 958
    return GraphCopy<From, To>(from, to);
959 959
  }
960 960

	
961 961
  namespace _core_bits {
962 962

	
963 963
    template <typename Graph, typename Enable = void>
964 964
    struct FindArcSelector {
965 965
      typedef typename Graph::Node Node;
966 966
      typedef typename Graph::Arc Arc;
967 967
      static Arc find(const Graph &g, Node u, Node v, Arc e) {
968 968
        if (e == INVALID) {
969 969
          g.firstOut(e, u);
970 970
        } else {
971 971
          g.nextOut(e);
972 972
        }
973 973
        while (e != INVALID && g.target(e) != v) {
974 974
          g.nextOut(e);
975 975
        }
976 976
        return e;
977 977
      }
978 978
    };
979 979

	
980 980
    template <typename Graph>
981 981
    struct FindArcSelector<
982 982
      Graph,
983 983
      typename enable_if<typename Graph::FindArcTag, void>::type>
984 984
    {
985 985
      typedef typename Graph::Node Node;
986 986
      typedef typename Graph::Arc Arc;
987 987
      static Arc find(const Graph &g, Node u, Node v, Arc prev) {
988 988
        return g.findArc(u, v, prev);
989 989
      }
990 990
    };
991 991
  }
992 992

	
993 993
  /// \brief Find an arc between two nodes of a digraph.
994 994
  ///
995 995
  /// This function finds an arc from node \c u to node \c v in the
996 996
  /// digraph \c g.
997 997
  ///
998 998
  /// If \c prev is \ref INVALID (this is the default value), then
999 999
  /// it finds the first arc from \c u to \c v. Otherwise it looks for
1000 1000
  /// the next arc from \c u to \c v after \c prev.
1001 1001
  /// \return The found arc or \ref INVALID if there is no such an arc.
1002 1002
  ///
1003 1003
  /// Thus you can iterate through each arc from \c u to \c v as it follows.
1004 1004
  ///\code
1005 1005
  /// for(Arc e = findArc(g,u,v); e != INVALID; e = findArc(g,u,v,e)) {
1006 1006
  ///   ...
1007 1007
  /// }
1008 1008
  ///\endcode
1009 1009
  ///
1010 1010
  /// \note \ref ConArcIt provides iterator interface for the same
1011 1011
  /// functionality.
1012 1012
  ///
1013 1013
  ///\sa ConArcIt
1014 1014
  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
1015 1015
  template <typename Graph>
1016 1016
  inline typename Graph::Arc
1017 1017
  findArc(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1018 1018
          typename Graph::Arc prev = INVALID) {
1019 1019
    return _core_bits::FindArcSelector<Graph>::find(g, u, v, prev);
1020 1020
  }
1021 1021

	
1022 1022
  /// \brief Iterator for iterating on parallel arcs connecting the same nodes.
1023 1023
  ///
1024 1024
  /// Iterator for iterating on parallel arcs connecting the same nodes. It is
1025 1025
  /// a higher level interface for the \ref findArc() function. You can
1026 1026
  /// use it the following way:
1027 1027
  ///\code
1028 1028
  /// for (ConArcIt<Graph> it(g, src, trg); it != INVALID; ++it) {
1029 1029
  ///   ...
1030 1030
  /// }
1031 1031
  ///\endcode
1032 1032
  ///
1033 1033
  ///\sa findArc()
1034 1034
  ///\sa ArcLookUp, AllArcLookUp, DynArcLookUp
1035 1035
  template <typename _Graph>
1036 1036
  class ConArcIt : public _Graph::Arc {
1037 1037
  public:
1038 1038

	
1039 1039
    typedef _Graph Graph;
1040 1040
    typedef typename Graph::Arc Parent;
1041 1041

	
1042 1042
    typedef typename Graph::Arc Arc;
1043 1043
    typedef typename Graph::Node Node;
1044 1044

	
1045 1045
    /// \brief Constructor.
1046 1046
    ///
1047 1047
    /// Construct a new ConArcIt iterating on the arcs that
1048 1048
    /// connects nodes \c u and \c v.
1049 1049
    ConArcIt(const Graph& g, Node u, Node v) : _graph(g) {
1050 1050
      Parent::operator=(findArc(_graph, u, v));
1051 1051
    }
1052 1052

	
1053 1053
    /// \brief Constructor.
1054 1054
    ///
1055 1055
    /// Construct a new ConArcIt that continues the iterating from arc \c a.
1056 1056
    ConArcIt(const Graph& g, Arc a) : Parent(a), _graph(g) {}
1057 1057

	
1058 1058
    /// \brief Increment operator.
1059 1059
    ///
1060 1060
    /// It increments the iterator and gives back the next arc.
1061 1061
    ConArcIt& operator++() {
1062 1062
      Parent::operator=(findArc(_graph, _graph.source(*this),
1063 1063
                                _graph.target(*this), *this));
1064 1064
      return *this;
1065 1065
    }
1066 1066
  private:
1067 1067
    const Graph& _graph;
1068 1068
  };
1069 1069

	
1070 1070
  namespace _core_bits {
1071 1071

	
1072 1072
    template <typename Graph, typename Enable = void>
1073 1073
    struct FindEdgeSelector {
1074 1074
      typedef typename Graph::Node Node;
1075 1075
      typedef typename Graph::Edge Edge;
1076 1076
      static Edge find(const Graph &g, Node u, Node v, Edge e) {
1077 1077
        bool b;
1078 1078
        if (u != v) {
1079 1079
          if (e == INVALID) {
1080 1080
            g.firstInc(e, b, u);
1081 1081
          } else {
1082 1082
            b = g.u(e) == u;
1083 1083
            g.nextInc(e, b);
1084 1084
          }
1085 1085
          while (e != INVALID && (b ? g.v(e) : g.u(e)) != v) {
1086 1086
            g.nextInc(e, b);
1087 1087
          }
1088 1088
        } else {
1089 1089
          if (e == INVALID) {
1090 1090
            g.firstInc(e, b, u);
1091 1091
          } else {
1092 1092
            b = true;
1093 1093
            g.nextInc(e, b);
1094 1094
          }
1095 1095
          while (e != INVALID && (!b || g.v(e) != v)) {
1096 1096
            g.nextInc(e, b);
1097 1097
          }
1098 1098
        }
1099 1099
        return e;
1100 1100
      }
1101 1101
    };
1102 1102

	
1103 1103
    template <typename Graph>
1104 1104
    struct FindEdgeSelector<
1105 1105
      Graph,
1106 1106
      typename enable_if<typename Graph::FindEdgeTag, void>::type>
1107 1107
    {
1108 1108
      typedef typename Graph::Node Node;
1109 1109
      typedef typename Graph::Edge Edge;
1110 1110
      static Edge find(const Graph &g, Node u, Node v, Edge prev) {
1111 1111
        return g.findEdge(u, v, prev);
1112 1112
      }
1113 1113
    };
1114 1114
  }
1115 1115

	
1116 1116
  /// \brief Find an edge between two nodes of a graph.
1117 1117
  ///
1118 1118
  /// This function finds an edge from node \c u to node \c v in graph \c g.
1119 1119
  /// If node \c u and node \c v is equal then each loop edge
1120 1120
  /// will be enumerated once.
1121 1121
  ///
1122 1122
  /// If \c prev is \ref INVALID (this is the default value), then
1123 1123
  /// it finds the first edge from \c u to \c v. Otherwise it looks for
1124 1124
  /// the next edge from \c u to \c v after \c prev.
1125 1125
  /// \return The found edge or \ref INVALID if there is no such an edge.
1126 1126
  ///
1127 1127
  /// Thus you can iterate through each edge between \c u and \c v
1128 1128
  /// as it follows.
1129 1129
  ///\code
1130 1130
  /// for(Edge e = findEdge(g,u,v); e != INVALID; e = findEdge(g,u,v,e)) {
1131 1131
  ///   ...
1132 1132
  /// }
1133 1133
  ///\endcode
1134 1134
  ///
1135 1135
  /// \note \ref ConEdgeIt provides iterator interface for the same
1136 1136
  /// functionality.
1137 1137
  ///
1138 1138
  ///\sa ConEdgeIt
1139 1139
  template <typename Graph>
1140 1140
  inline typename Graph::Edge
1141 1141
  findEdge(const Graph &g, typename Graph::Node u, typename Graph::Node v,
1142 1142
            typename Graph::Edge p = INVALID) {
1143 1143
    return _core_bits::FindEdgeSelector<Graph>::find(g, u, v, p);
1144 1144
  }
1145 1145

	
1146 1146
  /// \brief Iterator for iterating on parallel edges connecting the same nodes.
1147 1147
  ///
1148 1148
  /// Iterator for iterating on parallel edges connecting the same nodes.
1149 1149
  /// It is a higher level interface for the findEdge() function. You can
1150 1150
  /// use it the following way:
1151 1151
  ///\code
1152 1152
  /// for (ConEdgeIt<Graph> it(g, u, v); it != INVALID; ++it) {
1153 1153
  ///   ...
1154 1154
  /// }
1155 1155
  ///\endcode
1156 1156
  ///
1157 1157
  ///\sa findEdge()
1158 1158
  template <typename _Graph>
1159 1159
  class ConEdgeIt : public _Graph::Edge {
1160 1160
  public:
1161 1161

	
1162 1162
    typedef _Graph Graph;
1163 1163
    typedef typename Graph::Edge Parent;
1164 1164

	
1165 1165
    typedef typename Graph::Edge Edge;
1166 1166
    typedef typename Graph::Node Node;
1167 1167

	
1168 1168
    /// \brief Constructor.
1169 1169
    ///
1170 1170
    /// Construct a new ConEdgeIt iterating on the edges that
1171 1171
    /// connects nodes \c u and \c v.
1172 1172
    ConEdgeIt(const Graph& g, Node u, Node v) : _graph(g) {
1173 1173
      Parent::operator=(findEdge(_graph, u, v));
1174 1174
    }
1175 1175

	
1176 1176
    /// \brief Constructor.
1177 1177
    ///
1178 1178
    /// Construct a new ConEdgeIt that continues iterating from edge \c e.
1179 1179
    ConEdgeIt(const Graph& g, Edge e) : Parent(e), _graph(g) {}
1180 1180

	
1181 1181
    /// \brief Increment operator.
1182 1182
    ///
1183 1183
    /// It increments the iterator and gives back the next edge.
1184 1184
    ConEdgeIt& operator++() {
1185 1185
      Parent::operator=(findEdge(_graph, _graph.u(*this),
1186 1186
                                 _graph.v(*this), *this));
1187 1187
      return *this;
1188 1188
    }
1189 1189
  private:
1190 1190
    const Graph& _graph;
1191 1191
  };
1192 1192

	
1193 1193

	
1194 1194
  ///Dynamic arc look-up between given endpoints.
1195 1195

	
1196 1196
  ///Using this class, you can find an arc in a digraph from a given
1197 1197
  ///source to a given target in amortized time <em>O</em>(log<em>d</em>),
1198 1198
  ///where <em>d</em> is the out-degree of the source node.
1199 1199
  ///
1200 1200
  ///It is possible to find \e all parallel arcs between two nodes with
1201 1201
  ///the \c operator() member.
1202 1202
  ///
1203 1203
  ///This is a dynamic data structure. Consider to use \ref ArcLookUp or
1204 1204
  ///\ref AllArcLookUp if your digraph is not changed so frequently.
1205 1205
  ///
1206 1206
  ///This class uses a self-adjusting binary search tree, the Splay tree
1207 1207
  ///of Sleator and Tarjan to guarantee the logarithmic amortized
1208 1208
  ///time bound for arc look-ups. This class also guarantees the
1209 1209
  ///optimal time bound in a constant factor for any distribution of
1210 1210
  ///queries.
1211 1211
  ///
1212 1212
  ///\tparam G The type of the underlying digraph.
1213 1213
  ///
1214 1214
  ///\sa ArcLookUp
1215 1215
  ///\sa AllArcLookUp
1216 1216
  template<class G>
1217 1217
  class DynArcLookUp
1218 1218
    : protected ItemSetTraits<G, typename G::Arc>::ItemNotifier::ObserverBase
1219 1219
  {
1220 1220
  public:
1221 1221
    typedef typename ItemSetTraits<G, typename G::Arc>
1222 1222
    ::ItemNotifier::ObserverBase Parent;
1223 1223

	
1224 1224
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
1225 1225
    typedef G Digraph;
1226 1226

	
1227 1227
  protected:
1228 1228

	
1229 1229
    class AutoNodeMap : public ItemSetTraits<G, Node>::template Map<Arc>::Type {
1230 1230
    public:
1231 1231

	
1232 1232
      typedef typename ItemSetTraits<G, Node>::template Map<Arc>::Type Parent;
1233 1233

	
1234 1234
      AutoNodeMap(const G& digraph) : Parent(digraph, INVALID) {}
1235 1235

	
1236 1236
      virtual void add(const Node& node) {
1237 1237
        Parent::add(node);
1238 1238
        Parent::set(node, INVALID);
1239 1239
      }
1240 1240

	
1241 1241
      virtual void add(const std::vector<Node>& nodes) {
1242 1242
        Parent::add(nodes);
1243 1243
        for (int i = 0; i < int(nodes.size()); ++i) {
1244 1244
          Parent::set(nodes[i], INVALID);
1245 1245
        }
1246 1246
      }
1247 1247

	
1248 1248
      virtual void build() {
1249 1249
        Parent::build();
1250 1250
        Node it;
1251 1251
        typename Parent::Notifier* nf = Parent::notifier();
1252 1252
        for (nf->first(it); it != INVALID; nf->next(it)) {
1253 1253
          Parent::set(it, INVALID);
1254 1254
        }
1255 1255
      }
1256 1256
    };
1257 1257

	
1258 1258
    const Digraph &_g;
1259 1259
    AutoNodeMap _head;
1260 1260
    typename Digraph::template ArcMap<Arc> _parent;
1261 1261
    typename Digraph::template ArcMap<Arc> _left;
1262 1262
    typename Digraph::template ArcMap<Arc> _right;
1263 1263

	
1264 1264
    class ArcLess {
1265 1265
      const Digraph &g;
1266 1266
    public:
1267 1267
      ArcLess(const Digraph &_g) : g(_g) {}
1268 1268
      bool operator()(Arc a,Arc b) const
1269 1269
      {
1270 1270
        return g.target(a)<g.target(b);
1271 1271
      }
1272 1272
    };
1273 1273

	
1274 1274
  public:
1275 1275

	
1276 1276
    ///Constructor
1277 1277

	
1278 1278
    ///Constructor.
1279 1279
    ///
1280 1280
    ///It builds up the search database.
1281 1281
    DynArcLookUp(const Digraph &g)
1282 1282
      : _g(g),_head(g),_parent(g),_left(g),_right(g)
1283 1283
    {
1284 1284
      Parent::attach(_g.notifier(typename Digraph::Arc()));
1285 1285
      refresh();
1286 1286
    }
1287 1287

	
1288 1288
  protected:
1289 1289

	
1290 1290
    virtual void add(const Arc& arc) {
1291 1291
      insert(arc);
1292 1292
    }
1293 1293

	
1294 1294
    virtual void add(const std::vector<Arc>& arcs) {
1295 1295
      for (int i = 0; i < int(arcs.size()); ++i) {
1296 1296
        insert(arcs[i]);
1297 1297
      }
1298 1298
    }
1299 1299

	
1300 1300
    virtual void erase(const Arc& arc) {
1301 1301
      remove(arc);
1302 1302
    }
1303 1303

	
1304 1304
    virtual void erase(const std::vector<Arc>& arcs) {
1305 1305
      for (int i = 0; i < int(arcs.size()); ++i) {
1306 1306
        remove(arcs[i]);
1307 1307
      }
1308 1308
    }
1309 1309

	
1310 1310
    virtual void build() {
1311 1311
      refresh();
1312 1312
    }
1313 1313

	
1314 1314
    virtual void clear() {
1315 1315
      for(NodeIt n(_g);n!=INVALID;++n) {
1316 1316
        _head.set(n, INVALID);
1317 1317
      }
1318 1318
    }
1319 1319

	
1320 1320
    void insert(Arc arc) {
1321 1321
      Node s = _g.source(arc);
1322 1322
      Node t = _g.target(arc);
1323 1323
      _left.set(arc, INVALID);
1324 1324
      _right.set(arc, INVALID);
1325 1325

	
1326 1326
      Arc e = _head[s];
1327 1327
      if (e == INVALID) {
1328 1328
        _head.set(s, arc);
1329 1329
        _parent.set(arc, INVALID);
1330 1330
        return;
1331 1331
      }
1332 1332
      while (true) {
1333 1333
        if (t < _g.target(e)) {
1334 1334
          if (_left[e] == INVALID) {
1335 1335
            _left.set(e, arc);
1336 1336
            _parent.set(arc, e);
1337 1337
            splay(arc);
1338 1338
            return;
1339 1339
          } else {
1340 1340
            e = _left[e];
1341 1341
          }
1342 1342
        } else {
1343 1343
          if (_right[e] == INVALID) {
1344 1344
            _right.set(e, arc);
1345 1345
            _parent.set(arc, e);
1346 1346
            splay(arc);
1347 1347
            return;
1348 1348
          } else {
1349 1349
            e = _right[e];
1350 1350
          }
1351 1351
        }
1352 1352
      }
1353 1353
    }
1354 1354

	
1355 1355
    void remove(Arc arc) {
1356 1356
      if (_left[arc] == INVALID) {
1357 1357
        if (_right[arc] != INVALID) {
1358 1358
          _parent.set(_right[arc], _parent[arc]);
1359 1359
        }
1360 1360
        if (_parent[arc] != INVALID) {
1361 1361
          if (_left[_parent[arc]] == arc) {
1362 1362
            _left.set(_parent[arc], _right[arc]);
1363 1363
          } else {
1364 1364
            _right.set(_parent[arc], _right[arc]);
1365 1365
          }
1366 1366
        } else {
1367 1367
          _head.set(_g.source(arc), _right[arc]);
1368 1368
        }
1369 1369
      } else if (_right[arc] == INVALID) {
1370 1370
        _parent.set(_left[arc], _parent[arc]);
1371 1371
        if (_parent[arc] != INVALID) {
1372 1372
          if (_left[_parent[arc]] == arc) {
1373 1373
            _left.set(_parent[arc], _left[arc]);
1374 1374
          } else {
1375 1375
            _right.set(_parent[arc], _left[arc]);
1376 1376
          }
1377 1377
        } else {
1378 1378
          _head.set(_g.source(arc), _left[arc]);
1379 1379
        }
1380 1380
      } else {
1381 1381
        Arc e = _left[arc];
1382 1382
        if (_right[e] != INVALID) {
1383 1383
          e = _right[e];
1384 1384
          while (_right[e] != INVALID) {
1385 1385
            e = _right[e];
1386 1386
          }
1387 1387
          Arc s = _parent[e];
1388 1388
          _right.set(_parent[e], _left[e]);
1389 1389
          if (_left[e] != INVALID) {
1390 1390
            _parent.set(_left[e], _parent[e]);
1391 1391
          }
1392 1392

	
1393 1393
          _left.set(e, _left[arc]);
1394 1394
          _parent.set(_left[arc], e);
1395 1395
          _right.set(e, _right[arc]);
1396 1396
          _parent.set(_right[arc], e);
1397 1397

	
1398 1398
          _parent.set(e, _parent[arc]);
1399 1399
          if (_parent[arc] != INVALID) {
1400 1400
            if (_left[_parent[arc]] == arc) {
1401 1401
              _left.set(_parent[arc], e);
1402 1402
            } else {
1403 1403
              _right.set(_parent[arc], e);
1404 1404
            }
1405 1405
          }
1406 1406
          splay(s);
1407 1407
        } else {
1408 1408
          _right.set(e, _right[arc]);
1409 1409
          _parent.set(_right[arc], e);
1410 1410
          _parent.set(e, _parent[arc]);
1411 1411

	
1412 1412
          if (_parent[arc] != INVALID) {
1413 1413
            if (_left[_parent[arc]] == arc) {
1414 1414
              _left.set(_parent[arc], e);
1415 1415
            } else {
1416 1416
              _right.set(_parent[arc], e);
1417 1417
            }
1418 1418
          } else {
1419 1419
            _head.set(_g.source(arc), e);
1420 1420
          }
1421 1421
        }
1422 1422
      }
1423 1423
    }
1424 1424

	
1425 1425
    Arc refreshRec(std::vector<Arc> &v,int a,int b)
1426 1426
    {
1427 1427
      int m=(a+b)/2;
1428 1428
      Arc me=v[m];
1429 1429
      if (a < m) {
1430 1430
        Arc left = refreshRec(v,a,m-1);
1431 1431
        _left.set(me, left);
1432 1432
        _parent.set(left, me);
1433 1433
      } else {
1434 1434
        _left.set(me, INVALID);
1435 1435
      }
1436 1436
      if (m < b) {
1437 1437
        Arc right = refreshRec(v,m+1,b);
1438 1438
        _right.set(me, right);
1439 1439
        _parent.set(right, me);
1440 1440
      } else {
1441 1441
        _right.set(me, INVALID);
1442 1442
      }
1443 1443
      return me;
1444 1444
    }
1445 1445

	
1446 1446
    void refresh() {
1447 1447
      for(NodeIt n(_g);n!=INVALID;++n) {
1448 1448
        std::vector<Arc> v;
1449 1449
        for(OutArcIt a(_g,n);a!=INVALID;++a) v.push_back(a);
1450 1450
        if (!v.empty()) {
1451 1451
          std::sort(v.begin(),v.end(),ArcLess(_g));
1452 1452
          Arc head = refreshRec(v,0,v.size()-1);
1453 1453
          _head.set(n, head);
1454 1454
          _parent.set(head, INVALID);
1455 1455
        }
1456 1456
        else _head.set(n, INVALID);
1457 1457
      }
1458 1458
    }
1459 1459

	
1460 1460
    void zig(Arc v) {
1461 1461
      Arc w = _parent[v];
1462 1462
      _parent.set(v, _parent[w]);
1463 1463
      _parent.set(w, v);
1464 1464
      _left.set(w, _right[v]);
1465 1465
      _right.set(v, w);
1466 1466
      if (_parent[v] != INVALID) {
1467 1467
        if (_right[_parent[v]] == w) {
1468 1468
          _right.set(_parent[v], v);
1469 1469
        } else {
1470 1470
          _left.set(_parent[v], v);
1471 1471
        }
1472 1472
      }
1473 1473
      if (_left[w] != INVALID){
1474 1474
        _parent.set(_left[w], w);
1475 1475
      }
1476 1476
    }
1477 1477

	
1478 1478
    void zag(Arc v) {
1479 1479
      Arc w = _parent[v];
1480 1480
      _parent.set(v, _parent[w]);
1481 1481
      _parent.set(w, v);
1482 1482
      _right.set(w, _left[v]);
1483 1483
      _left.set(v, w);
1484 1484
      if (_parent[v] != INVALID){
1485 1485
        if (_left[_parent[v]] == w) {
1486 1486
          _left.set(_parent[v], v);
1487 1487
        } else {
1488 1488
          _right.set(_parent[v], v);
1489 1489
        }
1490 1490
      }
1491 1491
      if (_right[w] != INVALID){
1492 1492
        _parent.set(_right[w], w);
1493 1493
      }
1494 1494
    }
1495 1495

	
1496 1496
    void splay(Arc v) {
1497 1497
      while (_parent[v] != INVALID) {
1498 1498
        if (v == _left[_parent[v]]) {
1499 1499
          if (_parent[_parent[v]] == INVALID) {
1500 1500
            zig(v);
1501 1501
          } else {
1502 1502
            if (_parent[v] == _left[_parent[_parent[v]]]) {
1503 1503
              zig(_parent[v]);
1504 1504
              zig(v);
1505 1505
            } else {
1506 1506
              zig(v);
1507 1507
              zag(v);
1508 1508
            }
1509 1509
          }
1510 1510
        } else {
1511 1511
          if (_parent[_parent[v]] == INVALID) {
1512 1512
            zag(v);
1513 1513
          } else {
1514 1514
            if (_parent[v] == _left[_parent[_parent[v]]]) {
1515 1515
              zag(v);
1516 1516
              zig(v);
1517 1517
            } else {
1518 1518
              zag(_parent[v]);
1519 1519
              zag(v);
1520 1520
            }
1521 1521
          }
1522 1522
        }
1523 1523
      }
1524 1524
      _head[_g.source(v)] = v;
1525 1525
    }
1526 1526

	
1527 1527

	
1528 1528
  public:
1529 1529

	
1530 1530
    ///Find an arc between two nodes.
1531 1531

	
1532 1532
    ///Find an arc between two nodes.
1533 1533
    ///\param s The source node.
1534 1534
    ///\param t The target node.
1535 1535
    ///\param p The previous arc between \c s and \c t. It it is INVALID or
1536 1536
    ///not given, the operator finds the first appropriate arc.
1537 1537
    ///\return An arc from \c s to \c t after \c p or
1538 1538
    ///\ref INVALID if there is no more.
1539 1539
    ///
1540 1540
    ///For example, you can count the number of arcs from \c u to \c v in the
1541 1541
    ///following way.
1542 1542
    ///\code
1543 1543
    ///DynArcLookUp<ListDigraph> ae(g);
1544 1544
    ///...
1545 1545
    ///int n = 0;
1546 1546
    ///for(Arc a = ae(u,v); a != INVALID; a = ae(u,v,a)) n++;
1547 1547
    ///\endcode
1548 1548
    ///
1549 1549
    ///Finding the arcs take at most <em>O</em>(log<em>d</em>)
1550 1550
    ///amortized time, specifically, the time complexity of the lookups
1551 1551
    ///is equal to the optimal search tree implementation for the
1552 1552
    ///current query distribution in a constant factor.
1553 1553
    ///
1554 1554
    ///\note This is a dynamic data structure, therefore the data
1555 1555
    ///structure is updated after each graph alteration. Thus although
1556 1556
    ///this data structure is theoretically faster than \ref ArcLookUp
1557
    ///and \ref AllArcLookup, it often provides worse performance than
1557
    ///and \ref AllArcLookUp, it often provides worse performance than
1558 1558
    ///them.
1559 1559
    Arc operator()(Node s, Node t, Arc p = INVALID) const  {
1560 1560
      if (p == INVALID) {
1561 1561
        Arc a = _head[s];
1562 1562
        if (a == INVALID) return INVALID;
1563 1563
        Arc r = INVALID;
1564 1564
        while (true) {
1565 1565
          if (_g.target(a) < t) {
1566 1566
            if (_right[a] == INVALID) {
1567 1567
              const_cast<DynArcLookUp&>(*this).splay(a);
1568 1568
              return r;
1569 1569
            } else {
1570 1570
              a = _right[a];
1571 1571
            }
1572 1572
          } else {
1573 1573
            if (_g.target(a) == t) {
1574 1574
              r = a;
1575 1575
            }
1576 1576
            if (_left[a] == INVALID) {
1577 1577
              const_cast<DynArcLookUp&>(*this).splay(a);
1578 1578
              return r;
1579 1579
            } else {
1580 1580
              a = _left[a];
1581 1581
            }
1582 1582
          }
1583 1583
        }
1584 1584
      } else {
1585 1585
        Arc a = p;
1586 1586
        if (_right[a] != INVALID) {
1587 1587
          a = _right[a];
1588 1588
          while (_left[a] != INVALID) {
1589 1589
            a = _left[a];
1590 1590
          }
1591 1591
          const_cast<DynArcLookUp&>(*this).splay(a);
1592 1592
        } else {
1593 1593
          while (_parent[a] != INVALID && _right[_parent[a]] ==  a) {
1594 1594
            a = _parent[a];
1595 1595
          }
1596 1596
          if (_parent[a] == INVALID) {
1597 1597
            return INVALID;
1598 1598
          } else {
1599 1599
            a = _parent[a];
1600 1600
            const_cast<DynArcLookUp&>(*this).splay(a);
1601 1601
          }
1602 1602
        }
1603 1603
        if (_g.target(a) == t) return a;
1604 1604
        else return INVALID;
1605 1605
      }
1606 1606
    }
1607 1607

	
1608 1608
  };
1609 1609

	
1610 1610
  ///Fast arc look-up between given endpoints.
1611 1611

	
1612 1612
  ///Using this class, you can find an arc in a digraph from a given
1613 1613
  ///source to a given target in time <em>O</em>(log<em>d</em>),
1614 1614
  ///where <em>d</em> is the out-degree of the source node.
1615 1615
  ///
1616 1616
  ///It is not possible to find \e all parallel arcs between two nodes.
1617 1617
  ///Use \ref AllArcLookUp for this purpose.
1618 1618
  ///
1619 1619
  ///\warning This class is static, so you should call refresh() (or at
1620 1620
  ///least refresh(Node)) to refresh this data structure whenever the
1621 1621
  ///digraph changes. This is a time consuming (superlinearly proportional
1622 1622
  ///(<em>O</em>(<em>m</em> log<em>m</em>)) to the number of arcs).
1623 1623
  ///
1624 1624
  ///\tparam G The type of the underlying digraph.
1625 1625
  ///
1626 1626
  ///\sa DynArcLookUp
1627 1627
  ///\sa AllArcLookUp
1628 1628
  template<class G>
1629 1629
  class ArcLookUp
1630 1630
  {
1631 1631
  public:
1632 1632
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
1633 1633
    typedef G Digraph;
1634 1634

	
1635 1635
  protected:
1636 1636
    const Digraph &_g;
1637 1637
    typename Digraph::template NodeMap<Arc> _head;
1638 1638
    typename Digraph::template ArcMap<Arc> _left;
1639 1639
    typename Digraph::template ArcMap<Arc> _right;
1640 1640

	
1641 1641
    class ArcLess {
1642 1642
      const Digraph &g;
1643 1643
    public:
1644 1644
      ArcLess(const Digraph &_g) : g(_g) {}
1645 1645
      bool operator()(Arc a,Arc b) const
1646 1646
      {
1647 1647
        return g.target(a)<g.target(b);
1648 1648
      }
1649 1649
    };
1650 1650

	
1651 1651
  public:
1652 1652

	
1653 1653
    ///Constructor
1654 1654

	
1655 1655
    ///Constructor.
1656 1656
    ///
1657 1657
    ///It builds up the search database, which remains valid until the digraph
1658 1658
    ///changes.
1659 1659
    ArcLookUp(const Digraph &g) :_g(g),_head(g),_left(g),_right(g) {refresh();}
1660 1660

	
1661 1661
  private:
1662 1662
    Arc refreshRec(std::vector<Arc> &v,int a,int b)
1663 1663
    {
1664 1664
      int m=(a+b)/2;
1665 1665
      Arc me=v[m];
1666 1666
      _left[me] = a<m?refreshRec(v,a,m-1):INVALID;
1667 1667
      _right[me] = m<b?refreshRec(v,m+1,b):INVALID;
1668 1668
      return me;
1669 1669
    }
1670 1670
  public:
1671 1671
    ///Refresh the search data structure at a node.
1672 1672

	
1673 1673
    ///Build up the search database of node \c n.
1674 1674
    ///
1675 1675
    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em>
1676 1676
    ///is the number of the outgoing arcs of \c n.
1677 1677
    void refresh(Node n)
1678 1678
    {
1679 1679
      std::vector<Arc> v;
1680 1680
      for(OutArcIt e(_g,n);e!=INVALID;++e) v.push_back(e);
1681 1681
      if(v.size()) {
1682 1682
        std::sort(v.begin(),v.end(),ArcLess(_g));
1683 1683
        _head[n]=refreshRec(v,0,v.size()-1);
1684 1684
      }
1685 1685
      else _head[n]=INVALID;
1686 1686
    }
1687 1687
    ///Refresh the full data structure.
1688 1688

	
1689 1689
    ///Build up the full search database. In fact, it simply calls
1690 1690
    ///\ref refresh(Node) "refresh(n)" for each node \c n.
1691 1691
    ///
1692 1692
    ///It runs in time <em>O</em>(<em>m</em> log<em>D</em>), where <em>m</em> is
1693 1693
    ///the number of the arcs in the digraph and <em>D</em> is the maximum
1694 1694
    ///out-degree of the digraph.
1695 1695
    void refresh()
1696 1696
    {
1697 1697
      for(NodeIt n(_g);n!=INVALID;++n) refresh(n);
1698 1698
    }
1699 1699

	
1700 1700
    ///Find an arc between two nodes.
1701 1701

	
1702
    ///Find an arc between two nodes in time <em>O</em>(log<em>d</em>), where
1703
    ///<em>d</em> is the number of outgoing arcs of \c s.
1702
    ///Find an arc between two nodes in time <em>O</em>(log<em>d</em>),
1703
    ///where <em>d</em> is the number of outgoing arcs of \c s.
1704 1704
    ///\param s The source node.
1705 1705
    ///\param t The target node.
1706 1706
    ///\return An arc from \c s to \c t if there exists,
1707 1707
    ///\ref INVALID otherwise.
1708 1708
    ///
1709 1709
    ///\warning If you change the digraph, refresh() must be called before using
1710 1710
    ///this operator. If you change the outgoing arcs of
1711 1711
    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
1712 1712
    Arc operator()(Node s, Node t) const
1713 1713
    {
1714 1714
      Arc e;
1715 1715
      for(e=_head[s];
1716 1716
          e!=INVALID&&_g.target(e)!=t;
1717 1717
          e = t < _g.target(e)?_left[e]:_right[e]) ;
1718 1718
      return e;
1719 1719
    }
1720 1720

	
1721 1721
  };
1722 1722

	
1723 1723
  ///Fast look-up of all arcs between given endpoints.
1724 1724

	
1725 1725
  ///This class is the same as \ref ArcLookUp, with the addition
1726 1726
  ///that it makes it possible to find all parallel arcs between given
1727 1727
  ///endpoints.
1728 1728
  ///
1729 1729
  ///\warning This class is static, so you should call refresh() (or at
1730 1730
  ///least refresh(Node)) to refresh this data structure whenever the
1731 1731
  ///digraph changes. This is a time consuming (superlinearly proportional
1732 1732
  ///(<em>O</em>(<em>m</em> log<em>m</em>)) to the number of arcs).
1733 1733
  ///
1734 1734
  ///\tparam G The type of the underlying digraph.
1735 1735
  ///
1736 1736
  ///\sa DynArcLookUp
1737 1737
  ///\sa ArcLookUp
1738 1738
  template<class G>
1739 1739
  class AllArcLookUp : public ArcLookUp<G>
1740 1740
  {
1741 1741
    using ArcLookUp<G>::_g;
1742 1742
    using ArcLookUp<G>::_right;
1743 1743
    using ArcLookUp<G>::_left;
1744 1744
    using ArcLookUp<G>::_head;
1745 1745

	
1746 1746
    TEMPLATE_DIGRAPH_TYPEDEFS(G);
1747 1747
    typedef G Digraph;
1748 1748

	
1749 1749
    typename Digraph::template ArcMap<Arc> _next;
1750 1750

	
1751 1751
    Arc refreshNext(Arc head,Arc next=INVALID)
1752 1752
    {
1753 1753
      if(head==INVALID) return next;
1754 1754
      else {
1755 1755
        next=refreshNext(_right[head],next);
1756 1756
        _next[head]=( next!=INVALID && _g.target(next)==_g.target(head))
1757 1757
          ? next : INVALID;
1758 1758
        return refreshNext(_left[head],head);
1759 1759
      }
1760 1760
    }
1761 1761

	
1762 1762
    void refreshNext()
1763 1763
    {
1764 1764
      for(NodeIt n(_g);n!=INVALID;++n) refreshNext(_head[n]);
1765 1765
    }
1766 1766

	
1767 1767
  public:
1768 1768
    ///Constructor
1769 1769

	
1770 1770
    ///Constructor.
1771 1771
    ///
1772 1772
    ///It builds up the search database, which remains valid until the digraph
1773 1773
    ///changes.
1774 1774
    AllArcLookUp(const Digraph &g) : ArcLookUp<G>(g), _next(g) {refreshNext();}
1775 1775

	
1776 1776
    ///Refresh the data structure at a node.
1777 1777

	
1778 1778
    ///Build up the search database of node \c n.
1779 1779
    ///
1780 1780
    ///It runs in time <em>O</em>(<em>d</em> log<em>d</em>), where <em>d</em> is
1781 1781
    ///the number of the outgoing arcs of \c n.
1782 1782
    void refresh(Node n)
1783 1783
    {
1784 1784
      ArcLookUp<G>::refresh(n);
1785 1785
      refreshNext(_head[n]);
1786 1786
    }
1787 1787

	
1788 1788
    ///Refresh the full data structure.
1789 1789

	
1790 1790
    ///Build up the full search database. In fact, it simply calls
1791 1791
    ///\ref refresh(Node) "refresh(n)" for each node \c n.
1792 1792
    ///
1793 1793
    ///It runs in time <em>O</em>(<em>m</em> log<em>D</em>), where <em>m</em> is
1794 1794
    ///the number of the arcs in the digraph and <em>D</em> is the maximum
1795 1795
    ///out-degree of the digraph.
1796 1796
    void refresh()
1797 1797
    {
1798 1798
      for(NodeIt n(_g);n!=INVALID;++n) refresh(_head[n]);
1799 1799
    }
1800 1800

	
1801 1801
    ///Find an arc between two nodes.
1802 1802

	
1803 1803
    ///Find an arc between two nodes.
1804 1804
    ///\param s The source node.
1805 1805
    ///\param t The target node.
1806 1806
    ///\param prev The previous arc between \c s and \c t. It it is INVALID or
1807 1807
    ///not given, the operator finds the first appropriate arc.
1808 1808
    ///\return An arc from \c s to \c t after \c prev or
1809 1809
    ///\ref INVALID if there is no more.
1810 1810
    ///
1811 1811
    ///For example, you can count the number of arcs from \c u to \c v in the
1812 1812
    ///following way.
1813 1813
    ///\code
1814 1814
    ///AllArcLookUp<ListDigraph> ae(g);
1815 1815
    ///...
1816 1816
    ///int n = 0;
1817 1817
    ///for(Arc a = ae(u,v); a != INVALID; a=ae(u,v,a)) n++;
1818 1818
    ///\endcode
1819 1819
    ///
1820
    ///Finding the first arc take <em>O</em>(log<em>d</em>) time, where
1821
    ///<em>d</em> is the number of outgoing arcs of \c s. Then, the
1820
    ///Finding the first arc take <em>O</em>(log<em>d</em>) time,
1821
    ///where <em>d</em> is the number of outgoing arcs of \c s. Then the
1822 1822
    ///consecutive arcs are found in constant time.
1823 1823
    ///
1824 1824
    ///\warning If you change the digraph, refresh() must be called before using
1825 1825
    ///this operator. If you change the outgoing arcs of
1826 1826
    ///a single node \c n, then \ref refresh(Node) "refresh(n)" is enough.
1827 1827
    ///
1828 1828
#ifdef DOXYGEN
1829 1829
    Arc operator()(Node s, Node t, Arc prev=INVALID) const {}
1830 1830
#else
1831 1831
    using ArcLookUp<G>::operator() ;
1832 1832
    Arc operator()(Node s, Node t, Arc prev) const
1833 1833
    {
1834 1834
      return prev==INVALID?(*this)(s,t):_next[prev];
1835 1835
    }
1836 1836
#endif
1837 1837

	
1838 1838
  };
1839 1839

	
1840 1840
  /// @}
1841 1841

	
1842 1842
} //namespace lemon
1843 1843

	
1844 1844
#endif
Ignore white space 3072 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_DFS_H
20 20
#define LEMON_DFS_H
21 21

	
22 22
///\ingroup search
23 23
///\file
24 24
///\brief DFS algorithm.
25 25

	
26 26
#include <lemon/list_graph.h>
27 27
#include <lemon/bits/path_dump.h>
28 28
#include <lemon/core.h>
29 29
#include <lemon/error.h>
30 30
#include <lemon/assert.h>
31 31
#include <lemon/maps.h>
32 32
#include <lemon/path.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  ///Default traits class of Dfs class.
37 37

	
38 38
  ///Default traits class of Dfs class.
39 39
  ///\tparam GR Digraph type.
40 40
  template<class GR>
41 41
  struct DfsDefaultTraits
42 42
  {
43 43
    ///The type of the digraph the algorithm runs on.
44 44
    typedef GR Digraph;
45 45

	
46 46
    ///\brief The type of the map that stores the predecessor
47 47
    ///arcs of the %DFS paths.
48 48
    ///
49 49
    ///The type of the map that stores the predecessor
50 50
    ///arcs of the %DFS paths.
51 51
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
52 52
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
53 53
    ///Instantiates a PredMap.
54 54

	
55 55
    ///This function instantiates a PredMap.
56 56
    ///\param g is the digraph, to which we would like to define the
57 57
    ///PredMap.
58 58
    static PredMap *createPredMap(const Digraph &g)
59 59
    {
60 60
      return new PredMap(g);
61 61
    }
62 62

	
63 63
    ///The type of the map that indicates which nodes are processed.
64 64

	
65 65
    ///The type of the map that indicates which nodes are processed.
66 66
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
67 67
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
68 68
    ///Instantiates a ProcessedMap.
69 69

	
70 70
    ///This function instantiates a ProcessedMap.
71 71
    ///\param g is the digraph, to which
72 72
    ///we would like to define the ProcessedMap
73 73
#ifdef DOXYGEN
74 74
    static ProcessedMap *createProcessedMap(const Digraph &g)
75 75
#else
76 76
    static ProcessedMap *createProcessedMap(const Digraph &)
77 77
#endif
78 78
    {
79 79
      return new ProcessedMap();
80 80
    }
81 81

	
82 82
    ///The type of the map that indicates which nodes are reached.
83 83

	
84 84
    ///The type of the map that indicates which nodes are reached.
85 85
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
86 86
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
87 87
    ///Instantiates a ReachedMap.
88 88

	
89 89
    ///This function instantiates a ReachedMap.
90 90
    ///\param g is the digraph, to which
91 91
    ///we would like to define the ReachedMap.
92 92
    static ReachedMap *createReachedMap(const Digraph &g)
93 93
    {
94 94
      return new ReachedMap(g);
95 95
    }
96 96

	
97 97
    ///The type of the map that stores the distances of the nodes.
98 98

	
99 99
    ///The type of the map that stores the distances of the nodes.
100 100
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
101 101
    typedef typename Digraph::template NodeMap<int> DistMap;
102 102
    ///Instantiates a DistMap.
103 103

	
104 104
    ///This function instantiates a DistMap.
105 105
    ///\param g is the digraph, to which we would like to define the
106 106
    ///DistMap.
107 107
    static DistMap *createDistMap(const Digraph &g)
108 108
    {
109 109
      return new DistMap(g);
110 110
    }
111 111
  };
112 112

	
113 113
  ///%DFS algorithm class.
114 114

	
115 115
  ///\ingroup search
116 116
  ///This class provides an efficient implementation of the %DFS algorithm.
117 117
  ///
118 118
  ///There is also a \ref dfs() "function-type interface" for the DFS
119 119
  ///algorithm, which is convenient in the simplier cases and it can be
120 120
  ///used easier.
121 121
  ///
122 122
  ///\tparam GR The type of the digraph the algorithm runs on.
123 123
  ///The default value is \ref ListDigraph. The value of GR is not used
124 124
  ///directly by \ref Dfs, it is only passed to \ref DfsDefaultTraits.
125 125
  ///\tparam TR Traits class to set various data types used by the algorithm.
126 126
  ///The default traits class is
127 127
  ///\ref DfsDefaultTraits "DfsDefaultTraits<GR>".
128 128
  ///See \ref DfsDefaultTraits for the documentation of
129 129
  ///a Dfs traits class.
130 130
#ifdef DOXYGEN
131 131
  template <typename GR,
132 132
            typename TR>
133 133
#else
134 134
  template <typename GR=ListDigraph,
135 135
            typename TR=DfsDefaultTraits<GR> >
136 136
#endif
137 137
  class Dfs {
138 138
  public:
139 139

	
140 140
    ///The type of the digraph the algorithm runs on.
141 141
    typedef typename TR::Digraph Digraph;
142 142

	
143 143
    ///\brief The type of the map that stores the predecessor arcs of the
144 144
    ///DFS paths.
145 145
    typedef typename TR::PredMap PredMap;
146 146
    ///The type of the map that stores the distances of the nodes.
147 147
    typedef typename TR::DistMap DistMap;
148 148
    ///The type of the map that indicates which nodes are reached.
149 149
    typedef typename TR::ReachedMap ReachedMap;
150 150
    ///The type of the map that indicates which nodes are processed.
151 151
    typedef typename TR::ProcessedMap ProcessedMap;
152 152
    ///The type of the paths.
153 153
    typedef PredMapPath<Digraph, PredMap> Path;
154 154

	
155 155
    ///The traits class.
156 156
    typedef TR Traits;
157 157

	
158 158
  private:
159 159

	
160 160
    typedef typename Digraph::Node Node;
161 161
    typedef typename Digraph::NodeIt NodeIt;
162 162
    typedef typename Digraph::Arc Arc;
163 163
    typedef typename Digraph::OutArcIt OutArcIt;
164 164

	
165 165
    //Pointer to the underlying digraph.
166 166
    const Digraph *G;
167 167
    //Pointer to the map of predecessor arcs.
168 168
    PredMap *_pred;
169 169
    //Indicates if _pred is locally allocated (true) or not.
170 170
    bool local_pred;
171 171
    //Pointer to the map of distances.
172 172
    DistMap *_dist;
173 173
    //Indicates if _dist is locally allocated (true) or not.
174 174
    bool local_dist;
175 175
    //Pointer to the map of reached status of the nodes.
176 176
    ReachedMap *_reached;
177 177
    //Indicates if _reached is locally allocated (true) or not.
178 178
    bool local_reached;
179 179
    //Pointer to the map of processed status of the nodes.
180 180
    ProcessedMap *_processed;
181 181
    //Indicates if _processed is locally allocated (true) or not.
182 182
    bool local_processed;
183 183

	
184 184
    std::vector<typename Digraph::OutArcIt> _stack;
185 185
    int _stack_head;
186 186

	
187 187
    //Creates the maps if necessary.
188 188
    void create_maps()
189 189
    {
190 190
      if(!_pred) {
191 191
        local_pred = true;
192 192
        _pred = Traits::createPredMap(*G);
193 193
      }
194 194
      if(!_dist) {
195 195
        local_dist = true;
196 196
        _dist = Traits::createDistMap(*G);
197 197
      }
198 198
      if(!_reached) {
199 199
        local_reached = true;
200 200
        _reached = Traits::createReachedMap(*G);
201 201
      }
202 202
      if(!_processed) {
203 203
        local_processed = true;
204 204
        _processed = Traits::createProcessedMap(*G);
205 205
      }
206 206
    }
207 207

	
208 208
  protected:
209 209

	
210 210
    Dfs() {}
211 211

	
212 212
  public:
213 213

	
214 214
    typedef Dfs Create;
215 215

	
216 216
    ///\name Named template parameters
217 217

	
218 218
    ///@{
219 219

	
220 220
    template <class T>
221 221
    struct SetPredMapTraits : public Traits {
222 222
      typedef T PredMap;
223 223
      static PredMap *createPredMap(const Digraph &)
224 224
      {
225 225
        LEMON_ASSERT(false, "PredMap is not initialized");
226 226
        return 0; // ignore warnings
227 227
      }
228 228
    };
229 229
    ///\brief \ref named-templ-param "Named parameter" for setting
230 230
    ///PredMap type.
231 231
    ///
232 232
    ///\ref named-templ-param "Named parameter" for setting
233 233
    ///PredMap type.
234 234
    template <class T>
235 235
    struct SetPredMap : public Dfs<Digraph, SetPredMapTraits<T> > {
236 236
      typedef Dfs<Digraph, SetPredMapTraits<T> > Create;
237 237
    };
238 238

	
239 239
    template <class T>
240 240
    struct SetDistMapTraits : public Traits {
241 241
      typedef T DistMap;
242 242
      static DistMap *createDistMap(const Digraph &)
243 243
      {
244 244
        LEMON_ASSERT(false, "DistMap is not initialized");
245 245
        return 0; // ignore warnings
246 246
      }
247 247
    };
248 248
    ///\brief \ref named-templ-param "Named parameter" for setting
249 249
    ///DistMap type.
250 250
    ///
251 251
    ///\ref named-templ-param "Named parameter" for setting
252 252
    ///DistMap type.
253 253
    template <class T>
254 254
    struct SetDistMap : public Dfs< Digraph, SetDistMapTraits<T> > {
255 255
      typedef Dfs<Digraph, SetDistMapTraits<T> > Create;
256 256
    };
257 257

	
258 258
    template <class T>
259 259
    struct SetReachedMapTraits : public Traits {
260 260
      typedef T ReachedMap;
261 261
      static ReachedMap *createReachedMap(const Digraph &)
262 262
      {
263 263
        LEMON_ASSERT(false, "ReachedMap is not initialized");
264 264
        return 0; // ignore warnings
265 265
      }
266 266
    };
267 267
    ///\brief \ref named-templ-param "Named parameter" for setting
268 268
    ///ReachedMap type.
269 269
    ///
270 270
    ///\ref named-templ-param "Named parameter" for setting
271 271
    ///ReachedMap type.
272 272
    template <class T>
273 273
    struct SetReachedMap : public Dfs< Digraph, SetReachedMapTraits<T> > {
274 274
      typedef Dfs< Digraph, SetReachedMapTraits<T> > Create;
275 275
    };
276 276

	
277 277
    template <class T>
278 278
    struct SetProcessedMapTraits : public Traits {
279 279
      typedef T ProcessedMap;
280 280
      static ProcessedMap *createProcessedMap(const Digraph &)
281 281
      {
282 282
        LEMON_ASSERT(false, "ProcessedMap is not initialized");
283 283
        return 0; // ignore warnings
284 284
      }
285 285
    };
286 286
    ///\brief \ref named-templ-param "Named parameter" for setting
287 287
    ///ProcessedMap type.
288 288
    ///
289 289
    ///\ref named-templ-param "Named parameter" for setting
290 290
    ///ProcessedMap type.
291 291
    template <class T>
292 292
    struct SetProcessedMap : public Dfs< Digraph, SetProcessedMapTraits<T> > {
293 293
      typedef Dfs< Digraph, SetProcessedMapTraits<T> > Create;
294 294
    };
295 295

	
296 296
    struct SetStandardProcessedMapTraits : public Traits {
297 297
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
298 298
      static ProcessedMap *createProcessedMap(const Digraph &g)
299 299
      {
300 300
        return new ProcessedMap(g);
301 301
      }
302 302
    };
303 303
    ///\brief \ref named-templ-param "Named parameter" for setting
304 304
    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
305 305
    ///
306 306
    ///\ref named-templ-param "Named parameter" for setting
307 307
    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
308 308
    ///If you don't set it explicitly, it will be automatically allocated.
309 309
    struct SetStandardProcessedMap :
310 310
      public Dfs< Digraph, SetStandardProcessedMapTraits > {
311 311
      typedef Dfs< Digraph, SetStandardProcessedMapTraits > Create;
312 312
    };
313 313

	
314 314
    ///@}
315 315

	
316 316
  public:
317 317

	
318 318
    ///Constructor.
319 319

	
320 320
    ///Constructor.
321 321
    ///\param g The digraph the algorithm runs on.
322 322
    Dfs(const Digraph &g) :
323 323
      G(&g),
324 324
      _pred(NULL), local_pred(false),
325 325
      _dist(NULL), local_dist(false),
326 326
      _reached(NULL), local_reached(false),
327 327
      _processed(NULL), local_processed(false)
328 328
    { }
329 329

	
330 330
    ///Destructor.
331 331
    ~Dfs()
332 332
    {
333 333
      if(local_pred) delete _pred;
334 334
      if(local_dist) delete _dist;
335 335
      if(local_reached) delete _reached;
336 336
      if(local_processed) delete _processed;
337 337
    }
338 338

	
339 339
    ///Sets the map that stores the predecessor arcs.
340 340

	
341 341
    ///Sets the map that stores the predecessor arcs.
342 342
    ///If you don't use this function before calling \ref run(),
343 343
    ///it will allocate one. The destructor deallocates this
344 344
    ///automatically allocated map, of course.
345 345
    ///\return <tt> (*this) </tt>
346 346
    Dfs &predMap(PredMap &m)
347 347
    {
348 348
      if(local_pred) {
349 349
        delete _pred;
350 350
        local_pred=false;
351 351
      }
352 352
      _pred = &m;
353 353
      return *this;
354 354
    }
355 355

	
356 356
    ///Sets the map that indicates which nodes are reached.
357 357

	
358 358
    ///Sets the map that indicates which nodes are reached.
359 359
    ///If you don't use this function before calling \ref run(),
360 360
    ///it will allocate one. The destructor deallocates this
361 361
    ///automatically allocated map, of course.
362 362
    ///\return <tt> (*this) </tt>
363 363
    Dfs &reachedMap(ReachedMap &m)
364 364
    {
365 365
      if(local_reached) {
366 366
        delete _reached;
367 367
        local_reached=false;
368 368
      }
369 369
      _reached = &m;
370 370
      return *this;
371 371
    }
372 372

	
373 373
    ///Sets the map that indicates which nodes are processed.
374 374

	
375 375
    ///Sets the map that indicates which nodes are processed.
376 376
    ///If you don't use this function before calling \ref run(),
377 377
    ///it will allocate one. The destructor deallocates this
378 378
    ///automatically allocated map, of course.
379 379
    ///\return <tt> (*this) </tt>
380 380
    Dfs &processedMap(ProcessedMap &m)
381 381
    {
382 382
      if(local_processed) {
383 383
        delete _processed;
384 384
        local_processed=false;
385 385
      }
386 386
      _processed = &m;
387 387
      return *this;
388 388
    }
389 389

	
390 390
    ///Sets the map that stores the distances of the nodes.
391 391

	
392 392
    ///Sets the map that stores the distances of the nodes calculated by
393 393
    ///the algorithm.
394 394
    ///If you don't use this function before calling \ref run(),
395 395
    ///it will allocate one. The destructor deallocates this
396 396
    ///automatically allocated map, of course.
397 397
    ///\return <tt> (*this) </tt>
398 398
    Dfs &distMap(DistMap &m)
399 399
    {
400 400
      if(local_dist) {
401 401
        delete _dist;
402 402
        local_dist=false;
403 403
      }
404 404
      _dist = &m;
405 405
      return *this;
406 406
    }
407 407

	
408 408
  public:
409 409

	
410 410
    ///\name Execution control
411 411
    ///The simplest way to execute the algorithm is to use
412 412
    ///one of the member functions called \ref lemon::Dfs::run() "run()".
413 413
    ///\n
414 414
    ///If you need more control on the execution, first you must call
415 415
    ///\ref lemon::Dfs::init() "init()", then you can add a source node
416 416
    ///with \ref lemon::Dfs::addSource() "addSource()".
417 417
    ///Finally \ref lemon::Dfs::start() "start()" will perform the
418 418
    ///actual path computation.
419 419

	
420 420
    ///@{
421 421

	
422 422
    ///Initializes the internal data structures.
423 423

	
424 424
    ///Initializes the internal data structures.
425 425
    ///
426 426
    void init()
427 427
    {
428 428
      create_maps();
429 429
      _stack.resize(countNodes(*G));
430 430
      _stack_head=-1;
431 431
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
432 432
        _pred->set(u,INVALID);
433 433
        _reached->set(u,false);
434 434
        _processed->set(u,false);
435 435
      }
436 436
    }
437 437

	
438 438
    ///Adds a new source node.
439 439

	
440 440
    ///Adds a new source node to the set of nodes to be processed.
441 441
    ///
442 442
    ///\pre The stack must be empty. (Otherwise the algorithm gives
443 443
    ///false results.)
444 444
    ///
445 445
    ///\warning Distances will be wrong (or at least strange) in case of
446 446
    ///multiple sources.
447 447
    void addSource(Node s)
448 448
    {
449 449
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
450 450
      if(!(*_reached)[s])
451 451
        {
452 452
          _reached->set(s,true);
453 453
          _pred->set(s,INVALID);
454 454
          OutArcIt e(*G,s);
455 455
          if(e!=INVALID) {
456 456
            _stack[++_stack_head]=e;
457 457
            _dist->set(s,_stack_head);
458 458
          }
459 459
          else {
460 460
            _processed->set(s,true);
461 461
            _dist->set(s,0);
462 462
          }
463 463
        }
464 464
    }
465 465

	
466 466
    ///Processes the next arc.
467 467

	
468 468
    ///Processes the next arc.
469 469
    ///
470 470
    ///\return The processed arc.
471 471
    ///
472 472
    ///\pre The stack must not be empty.
473 473
    Arc processNextArc()
474 474
    {
475 475
      Node m;
476 476
      Arc e=_stack[_stack_head];
477 477
      if(!(*_reached)[m=G->target(e)]) {
478 478
        _pred->set(m,e);
479 479
        _reached->set(m,true);
480 480
        ++_stack_head;
481 481
        _stack[_stack_head] = OutArcIt(*G, m);
482 482
        _dist->set(m,_stack_head);
483 483
      }
484 484
      else {
485 485
        m=G->source(e);
486 486
        ++_stack[_stack_head];
487 487
      }
488 488
      while(_stack_head>=0 && _stack[_stack_head]==INVALID) {
489 489
        _processed->set(m,true);
490 490
        --_stack_head;
491 491
        if(_stack_head>=0) {
492 492
          m=G->source(_stack[_stack_head]);
493 493
          ++_stack[_stack_head];
494 494
        }
495 495
      }
496 496
      return e;
497 497
    }
498 498

	
499 499
    ///Next arc to be processed.
500 500

	
501 501
    ///Next arc to be processed.
502 502
    ///
503 503
    ///\return The next arc to be processed or \c INVALID if the stack
504 504
    ///is empty.
505 505
    OutArcIt nextArc() const
506 506
    {
507 507
      return _stack_head>=0?_stack[_stack_head]:INVALID;
508 508
    }
509 509

	
510 510
    ///\brief Returns \c false if there are nodes
511 511
    ///to be processed.
512 512
    ///
513 513
    ///Returns \c false if there are nodes
514 514
    ///to be processed in the queue (stack).
515 515
    bool emptyQueue() const { return _stack_head<0; }
516 516

	
517 517
    ///Returns the number of the nodes to be processed.
518 518

	
519 519
    ///Returns the number of the nodes to be processed in the queue (stack).
520 520
    int queueSize() const { return _stack_head+1; }
521 521

	
522 522
    ///Executes the algorithm.
523 523

	
524 524
    ///Executes the algorithm.
525 525
    ///
526 526
    ///This method runs the %DFS algorithm from the root node
527 527
    ///in order to compute the DFS path to each node.
528 528
    ///
529 529
    /// The algorithm computes
530 530
    ///- the %DFS tree,
531 531
    ///- the distance of each node from the root in the %DFS tree.
532 532
    ///
533 533
    ///\pre init() must be called and a root node should be
534 534
    ///added with addSource() before using this function.
535 535
    ///
536 536
    ///\note <tt>d.start()</tt> is just a shortcut of the following code.
537 537
    ///\code
538 538
    ///  while ( !d.emptyQueue() ) {
539 539
    ///    d.processNextArc();
540 540
    ///  }
541 541
    ///\endcode
542 542
    void start()
543 543
    {
544 544
      while ( !emptyQueue() ) processNextArc();
545 545
    }
546 546

	
547 547
    ///Executes the algorithm until the given target node is reached.
548 548

	
549 549
    ///Executes the algorithm until the given target node is reached.
550 550
    ///
551 551
    ///This method runs the %DFS algorithm from the root node
552 552
    ///in order to compute the DFS path to \c t.
553 553
    ///
554 554
    ///The algorithm computes
555 555
    ///- the %DFS path to \c t,
556 556
    ///- the distance of \c t from the root in the %DFS tree.
557 557
    ///
558 558
    ///\pre init() must be called and a root node should be
559 559
    ///added with addSource() before using this function.
560 560
    void start(Node t)
561 561
    {
562 562
      while ( !emptyQueue() && G->target(_stack[_stack_head])!=t )
563 563
        processNextArc();
564 564
    }
565 565

	
566 566
    ///Executes the algorithm until a condition is met.
567 567

	
568 568
    ///Executes the algorithm until a condition is met.
569 569
    ///
570 570
    ///This method runs the %DFS algorithm from the root node
571 571
    ///until an arc \c a with <tt>am[a]</tt> true is found.
572 572
    ///
573 573
    ///\param am A \c bool (or convertible) arc map. The algorithm
574 574
    ///will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
575 575
    ///
576 576
    ///\return The reached arc \c a with <tt>am[a]</tt> true or
577 577
    ///\c INVALID if no such arc was found.
578 578
    ///
579 579
    ///\pre init() must be called and a root node should be
580 580
    ///added with addSource() before using this function.
581 581
    ///
582 582
    ///\warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
583 583
    ///not a node map.
584 584
    template<class ArcBoolMap>
585 585
    Arc start(const ArcBoolMap &am)
586 586
    {
587 587
      while ( !emptyQueue() && !am[_stack[_stack_head]] )
588 588
        processNextArc();
589 589
      return emptyQueue() ? INVALID : _stack[_stack_head];
590 590
    }
591 591

	
592 592
    ///Runs the algorithm from the given source node.
593 593

	
594 594
    ///This method runs the %DFS algorithm from node \c s
595 595
    ///in order to compute the DFS path to each node.
596 596
    ///
597 597
    ///The algorithm computes
598 598
    ///- the %DFS tree,
599 599
    ///- the distance of each node from the root in the %DFS tree.
600 600
    ///
601 601
    ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
602 602
    ///\code
603 603
    ///  d.init();
604 604
    ///  d.addSource(s);
605 605
    ///  d.start();
606 606
    ///\endcode
607 607
    void run(Node s) {
608 608
      init();
609 609
      addSource(s);
610 610
      start();
611 611
    }
612 612

	
613 613
    ///Finds the %DFS path between \c s and \c t.
614 614

	
615 615
    ///This method runs the %DFS algorithm from node \c s
616 616
    ///in order to compute the DFS path to node \c t
617 617
    ///(it stops searching when \c t is processed)
618 618
    ///
619 619
    ///\return \c true if \c t is reachable form \c s.
620 620
    ///
621 621
    ///\note Apart from the return value, <tt>d.run(s,t)</tt> is
622 622
    ///just a shortcut of the following code.
623 623
    ///\code
624 624
    ///  d.init();
625 625
    ///  d.addSource(s);
626 626
    ///  d.start(t);
627 627
    ///\endcode
628 628
    bool run(Node s,Node t) {
629 629
      init();
630 630
      addSource(s);
631 631
      start(t);
632 632
      return reached(t);
633 633
    }
634 634

	
635 635
    ///Runs the algorithm to visit all nodes in the digraph.
636 636

	
637 637
    ///This method runs the %DFS algorithm in order to compute the
638 638
    ///%DFS path to each node.
639 639
    ///
640 640
    ///The algorithm computes
641 641
    ///- the %DFS tree,
642 642
    ///- the distance of each node from the root in the %DFS tree.
643 643
    ///
644 644
    ///\note <tt>d.run()</tt> is just a shortcut of the following code.
645 645
    ///\code
646 646
    ///  d.init();
647 647
    ///  for (NodeIt n(digraph); n != INVALID; ++n) {
648 648
    ///    if (!d.reached(n)) {
649 649
    ///      d.addSource(n);
650 650
    ///      d.start();
651 651
    ///    }
652 652
    ///  }
653 653
    ///\endcode
654 654
    void run() {
655 655
      init();
656 656
      for (NodeIt it(*G); it != INVALID; ++it) {
657 657
        if (!reached(it)) {
658 658
          addSource(it);
659 659
          start();
660 660
        }
661 661
      }
662 662
    }
663 663

	
664 664
    ///@}
665 665

	
666 666
    ///\name Query Functions
667 667
    ///The result of the %DFS algorithm can be obtained using these
668 668
    ///functions.\n
669 669
    ///Either \ref lemon::Dfs::run() "run()" or \ref lemon::Dfs::start()
670 670
    ///"start()" must be called before using them.
671 671

	
672 672
    ///@{
673 673

	
674 674
    ///The DFS path to a node.
675 675

	
676 676
    ///Returns the DFS path to a node.
677 677
    ///
678 678
    ///\warning \c t should be reachable from the root.
679 679
    ///
680 680
    ///\pre Either \ref run() or \ref start() must be called before
681 681
    ///using this function.
682 682
    Path path(Node t) const { return Path(*G, *_pred, t); }
683 683

	
684 684
    ///The distance of a node from the root.
685 685

	
686 686
    ///Returns the distance of a node from the root.
687 687
    ///
688 688
    ///\warning If node \c v is not reachable from the root, then
689 689
    ///the return value of this function is undefined.
690 690
    ///
691 691
    ///\pre Either \ref run() or \ref start() must be called before
692 692
    ///using this function.
693 693
    int dist(Node v) const { return (*_dist)[v]; }
694 694

	
695 695
    ///Returns the 'previous arc' of the %DFS tree for a node.
696 696

	
697 697
    ///This function returns the 'previous arc' of the %DFS tree for the
698 698
    ///node \c v, i.e. it returns the last arc of a %DFS path from the
699 699
    ///root to \c v. It is \c INVALID
700 700
    ///if \c v is not reachable from the root(s) or if \c v is a root.
701 701
    ///
702 702
    ///The %DFS tree used here is equal to the %DFS tree used in
703 703
    ///\ref predNode().
704 704
    ///
705 705
    ///\pre Either \ref run() or \ref start() must be called before using
706 706
    ///this function.
707 707
    Arc predArc(Node v) const { return (*_pred)[v];}
708 708

	
709 709
    ///Returns the 'previous node' of the %DFS tree.
710 710

	
711 711
    ///This function returns the 'previous node' of the %DFS
712 712
    ///tree for the node \c v, i.e. it returns the last but one node
713 713
    ///from a %DFS path from the root to \c v. It is \c INVALID
714 714
    ///if \c v is not reachable from the root(s) or if \c v is a root.
715 715
    ///
716 716
    ///The %DFS tree used here is equal to the %DFS tree used in
717 717
    ///\ref predArc().
718 718
    ///
719 719
    ///\pre Either \ref run() or \ref start() must be called before
720 720
    ///using this function.
721 721
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
722 722
                                  G->source((*_pred)[v]); }
723 723

	
724 724
    ///\brief Returns a const reference to the node map that stores the
725 725
    ///distances of the nodes.
726 726
    ///
727 727
    ///Returns a const reference to the node map that stores the
728 728
    ///distances of the nodes calculated by the algorithm.
729 729
    ///
730 730
    ///\pre Either \ref run() or \ref init()
731 731
    ///must be called before using this function.
732 732
    const DistMap &distMap() const { return *_dist;}
733 733

	
734 734
    ///\brief Returns a const reference to the node map that stores the
735 735
    ///predecessor arcs.
736 736
    ///
737 737
    ///Returns a const reference to the node map that stores the predecessor
738 738
    ///arcs, which form the DFS tree.
739 739
    ///
740 740
    ///\pre Either \ref run() or \ref init()
741 741
    ///must be called before using this function.
742 742
    const PredMap &predMap() const { return *_pred;}
743 743

	
744 744
    ///Checks if a node is reachable from the root(s).
745 745

	
746 746
    ///Returns \c true if \c v is reachable from the root(s).
747 747
    ///\pre Either \ref run() or \ref start()
748 748
    ///must be called before using this function.
749 749
    bool reached(Node v) const { return (*_reached)[v]; }
750 750

	
751 751
    ///@}
752 752
  };
753 753

	
754 754
  ///Default traits class of dfs() function.
755 755

	
756 756
  ///Default traits class of dfs() function.
757 757
  ///\tparam GR Digraph type.
758 758
  template<class GR>
759 759
  struct DfsWizardDefaultTraits
760 760
  {
761 761
    ///The type of the digraph the algorithm runs on.
762 762
    typedef GR Digraph;
763 763

	
764 764
    ///\brief The type of the map that stores the predecessor
765 765
    ///arcs of the %DFS paths.
766 766
    ///
767 767
    ///The type of the map that stores the predecessor
768 768
    ///arcs of the %DFS paths.
769 769
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
770 770
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
771 771
    ///Instantiates a PredMap.
772 772

	
773 773
    ///This function instantiates a PredMap.
774 774
    ///\param g is the digraph, to which we would like to define the
775 775
    ///PredMap.
776 776
    static PredMap *createPredMap(const Digraph &g)
777 777
    {
778 778
      return new PredMap(g);
779 779
    }
780 780

	
781 781
    ///The type of the map that indicates which nodes are processed.
782 782

	
783 783
    ///The type of the map that indicates which nodes are processed.
784 784
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
785 785
    ///By default it is a NullMap.
786 786
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
787 787
    ///Instantiates a ProcessedMap.
788 788

	
789 789
    ///This function instantiates a ProcessedMap.
790 790
    ///\param g is the digraph, to which
791 791
    ///we would like to define the ProcessedMap.
792 792
#ifdef DOXYGEN
793 793
    static ProcessedMap *createProcessedMap(const Digraph &g)
794 794
#else
795 795
    static ProcessedMap *createProcessedMap(const Digraph &)
796 796
#endif
797 797
    {
798 798
      return new ProcessedMap();
799 799
    }
800 800

	
801 801
    ///The type of the map that indicates which nodes are reached.
802 802

	
803 803
    ///The type of the map that indicates which nodes are reached.
804 804
    ///It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
805 805
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
806 806
    ///Instantiates a ReachedMap.
807 807

	
808 808
    ///This function instantiates a ReachedMap.
809 809
    ///\param g is the digraph, to which
810 810
    ///we would like to define the ReachedMap.
811 811
    static ReachedMap *createReachedMap(const Digraph &g)
812 812
    {
813 813
      return new ReachedMap(g);
814 814
    }
815 815

	
816 816
    ///The type of the map that stores the distances of the nodes.
817 817

	
818 818
    ///The type of the map that stores the distances of the nodes.
819 819
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
820 820
    typedef typename Digraph::template NodeMap<int> DistMap;
821 821
    ///Instantiates a DistMap.
822 822

	
823 823
    ///This function instantiates a DistMap.
824 824
    ///\param g is the digraph, to which we would like to define
825 825
    ///the DistMap
826 826
    static DistMap *createDistMap(const Digraph &g)
827 827
    {
828 828
      return new DistMap(g);
829 829
    }
830 830

	
831 831
    ///The type of the DFS paths.
832 832

	
833 833
    ///The type of the DFS paths.
834 834
    ///It must meet the \ref concepts::Path "Path" concept.
835 835
    typedef lemon::Path<Digraph> Path;
836 836
  };
837 837

	
838
  /// Default traits class used by \ref DfsWizard
838
  /// Default traits class used by DfsWizard
839 839

	
840 840
  /// To make it easier to use Dfs algorithm
841 841
  /// we have created a wizard class.
842 842
  /// This \ref DfsWizard class needs default traits,
843 843
  /// as well as the \ref Dfs class.
844 844
  /// The \ref DfsWizardBase is a class to be the default traits of the
845 845
  /// \ref DfsWizard class.
846 846
  template<class GR>
847 847
  class DfsWizardBase : public DfsWizardDefaultTraits<GR>
848 848
  {
849 849

	
850 850
    typedef DfsWizardDefaultTraits<GR> Base;
851 851
  protected:
852 852
    //The type of the nodes in the digraph.
853 853
    typedef typename Base::Digraph::Node Node;
854 854

	
855 855
    //Pointer to the digraph the algorithm runs on.
856 856
    void *_g;
857 857
    //Pointer to the map of reached nodes.
858 858
    void *_reached;
859 859
    //Pointer to the map of processed nodes.
860 860
    void *_processed;
861 861
    //Pointer to the map of predecessors arcs.
862 862
    void *_pred;
863 863
    //Pointer to the map of distances.
864 864
    void *_dist;
865 865
    //Pointer to the DFS path to the target node.
866 866
    void *_path;
867 867
    //Pointer to the distance of the target node.
868 868
    int *_di;
869 869

	
870 870
    public:
871 871
    /// Constructor.
872 872

	
873 873
    /// This constructor does not require parameters, therefore it initiates
874 874
    /// all of the attributes to \c 0.
875 875
    DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
876 876
                      _dist(0), _path(0), _di(0) {}
877 877

	
878 878
    /// Constructor.
879 879

	
880 880
    /// This constructor requires one parameter,
881 881
    /// others are initiated to \c 0.
882 882
    /// \param g The digraph the algorithm runs on.
883 883
    DfsWizardBase(const GR &g) :
884 884
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
885 885
      _reached(0), _processed(0), _pred(0), _dist(0),  _path(0), _di(0) {}
886 886

	
887 887
  };
888 888

	
889 889
  /// Auxiliary class for the function-type interface of DFS algorithm.
890 890

	
891 891
  /// This auxiliary class is created to implement the
892 892
  /// \ref dfs() "function-type interface" of \ref Dfs algorithm.
893 893
  /// It does not have own \ref run() method, it uses the functions
894 894
  /// and features of the plain \ref Dfs.
895 895
  ///
896 896
  /// This class should only be used through the \ref dfs() function,
897 897
  /// which makes it easier to use the algorithm.
898 898
  template<class TR>
899 899
  class DfsWizard : public TR
900 900
  {
901 901
    typedef TR Base;
902 902

	
903 903
    ///The type of the digraph the algorithm runs on.
904 904
    typedef typename TR::Digraph Digraph;
905 905

	
906 906
    typedef typename Digraph::Node Node;
907 907
    typedef typename Digraph::NodeIt NodeIt;
908 908
    typedef typename Digraph::Arc Arc;
909 909
    typedef typename Digraph::OutArcIt OutArcIt;
910 910

	
911 911
    ///\brief The type of the map that stores the predecessor
912 912
    ///arcs of the DFS paths.
913 913
    typedef typename TR::PredMap PredMap;
914 914
    ///\brief The type of the map that stores the distances of the nodes.
915 915
    typedef typename TR::DistMap DistMap;
916 916
    ///\brief The type of the map that indicates which nodes are reached.
917 917
    typedef typename TR::ReachedMap ReachedMap;
918 918
    ///\brief The type of the map that indicates which nodes are processed.
919 919
    typedef typename TR::ProcessedMap ProcessedMap;
920 920
    ///The type of the DFS paths
921 921
    typedef typename TR::Path Path;
922 922

	
923 923
  public:
924 924

	
925 925
    /// Constructor.
926 926
    DfsWizard() : TR() {}
927 927

	
928 928
    /// Constructor that requires parameters.
929 929

	
930 930
    /// Constructor that requires parameters.
931 931
    /// These parameters will be the default values for the traits class.
932 932
    /// \param g The digraph the algorithm runs on.
933 933
    DfsWizard(const Digraph &g) :
934 934
      TR(g) {}
935 935

	
936 936
    ///Copy constructor
937 937
    DfsWizard(const TR &b) : TR(b) {}
938 938

	
939 939
    ~DfsWizard() {}
940 940

	
941 941
    ///Runs DFS algorithm from the given source node.
942 942

	
943 943
    ///This method runs DFS algorithm from node \c s
944 944
    ///in order to compute the DFS path to each node.
945 945
    void run(Node s)
946 946
    {
947 947
      Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
948 948
      if (Base::_pred)
949 949
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
950 950
      if (Base::_dist)
951 951
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
952 952
      if (Base::_reached)
953 953
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
954 954
      if (Base::_processed)
955 955
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
956 956
      if (s!=INVALID)
957 957
        alg.run(s);
958 958
      else
959 959
        alg.run();
960 960
    }
961 961

	
962 962
    ///Finds the DFS path between \c s and \c t.
963 963

	
964 964
    ///This method runs DFS algorithm from node \c s
965 965
    ///in order to compute the DFS path to node \c t
966 966
    ///(it stops searching when \c t is processed).
967 967
    ///
968 968
    ///\return \c true if \c t is reachable form \c s.
969 969
    bool run(Node s, Node t)
970 970
    {
971 971
      Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
972 972
      if (Base::_pred)
973 973
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
974 974
      if (Base::_dist)
975 975
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
976 976
      if (Base::_reached)
977 977
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
978 978
      if (Base::_processed)
979 979
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
980 980
      alg.run(s,t);
981 981
      if (Base::_path)
982 982
        *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
983 983
      if (Base::_di)
984 984
        *Base::_di = alg.dist(t);
985 985
      return alg.reached(t);
986 986
      }
987 987

	
988 988
    ///Runs DFS algorithm to visit all nodes in the digraph.
989 989

	
990 990
    ///This method runs DFS algorithm in order to compute
991 991
    ///the DFS path to each node.
992 992
    void run()
993 993
    {
994 994
      run(INVALID);
995 995
    }
996 996

	
997 997
    template<class T>
998 998
    struct SetPredMapBase : public Base {
999 999
      typedef T PredMap;
1000 1000
      static PredMap *createPredMap(const Digraph &) { return 0; };
1001 1001
      SetPredMapBase(const TR &b) : TR(b) {}
1002 1002
    };
1003 1003
    ///\brief \ref named-func-param "Named parameter"
1004 1004
    ///for setting PredMap object.
1005 1005
    ///
1006 1006
    ///\ref named-func-param "Named parameter"
1007 1007
    ///for setting PredMap object.
1008 1008
    template<class T>
1009 1009
    DfsWizard<SetPredMapBase<T> > predMap(const T &t)
1010 1010
    {
1011 1011
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1012 1012
      return DfsWizard<SetPredMapBase<T> >(*this);
1013 1013
    }
1014 1014

	
1015 1015
    template<class T>
1016 1016
    struct SetReachedMapBase : public Base {
1017 1017
      typedef T ReachedMap;
1018 1018
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1019 1019
      SetReachedMapBase(const TR &b) : TR(b) {}
1020 1020
    };
1021 1021
    ///\brief \ref named-func-param "Named parameter"
1022 1022
    ///for setting ReachedMap object.
1023 1023
    ///
1024 1024
    /// \ref named-func-param "Named parameter"
1025 1025
    ///for setting ReachedMap object.
1026 1026
    template<class T>
1027 1027
    DfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1028 1028
    {
1029 1029
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1030 1030
      return DfsWizard<SetReachedMapBase<T> >(*this);
1031 1031
    }
1032 1032

	
1033 1033
    template<class T>
1034 1034
    struct SetDistMapBase : public Base {
1035 1035
      typedef T DistMap;
1036 1036
      static DistMap *createDistMap(const Digraph &) { return 0; };
1037 1037
      SetDistMapBase(const TR &b) : TR(b) {}
1038 1038
    };
1039 1039
    ///\brief \ref named-func-param "Named parameter"
1040 1040
    ///for setting DistMap object.
1041 1041
    ///
1042 1042
    /// \ref named-func-param "Named parameter"
1043 1043
    ///for setting DistMap object.
1044 1044
    template<class T>
1045 1045
    DfsWizard<SetDistMapBase<T> > distMap(const T &t)
1046 1046
    {
1047 1047
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1048 1048
      return DfsWizard<SetDistMapBase<T> >(*this);
1049 1049
    }
1050 1050

	
1051 1051
    template<class T>
1052 1052
    struct SetProcessedMapBase : public Base {
1053 1053
      typedef T ProcessedMap;
1054 1054
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1055 1055
      SetProcessedMapBase(const TR &b) : TR(b) {}
1056 1056
    };
1057 1057
    ///\brief \ref named-func-param "Named parameter"
1058 1058
    ///for setting ProcessedMap object.
1059 1059
    ///
1060 1060
    /// \ref named-func-param "Named parameter"
1061 1061
    ///for setting ProcessedMap object.
1062 1062
    template<class T>
1063 1063
    DfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1064 1064
    {
1065 1065
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1066 1066
      return DfsWizard<SetProcessedMapBase<T> >(*this);
1067 1067
    }
1068 1068

	
1069 1069
    template<class T>
1070 1070
    struct SetPathBase : public Base {
1071 1071
      typedef T Path;
1072 1072
      SetPathBase(const TR &b) : TR(b) {}
1073 1073
    };
1074 1074
    ///\brief \ref named-func-param "Named parameter"
1075 1075
    ///for getting the DFS path to the target node.
1076 1076
    ///
1077 1077
    ///\ref named-func-param "Named parameter"
1078 1078
    ///for getting the DFS path to the target node.
1079 1079
    template<class T>
1080 1080
    DfsWizard<SetPathBase<T> > path(const T &t)
1081 1081
    {
1082 1082
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1083 1083
      return DfsWizard<SetPathBase<T> >(*this);
1084 1084
    }
1085 1085

	
1086 1086
    ///\brief \ref named-func-param "Named parameter"
1087 1087
    ///for getting the distance of the target node.
1088 1088
    ///
1089 1089
    ///\ref named-func-param "Named parameter"
1090 1090
    ///for getting the distance of the target node.
1091 1091
    DfsWizard dist(const int &d)
1092 1092
    {
1093 1093
      Base::_di=const_cast<int*>(&d);
1094 1094
      return *this;
1095 1095
    }
1096 1096

	
1097 1097
  };
1098 1098

	
1099 1099
  ///Function-type interface for DFS algorithm.
1100 1100

	
1101 1101
  ///\ingroup search
1102 1102
  ///Function-type interface for DFS algorithm.
1103 1103
  ///
1104 1104
  ///This function also has several \ref named-func-param "named parameters",
1105 1105
  ///they are declared as the members of class \ref DfsWizard.
1106 1106
  ///The following examples show how to use these parameters.
1107 1107
  ///\code
1108 1108
  ///  // Compute the DFS tree
1109 1109
  ///  dfs(g).predMap(preds).distMap(dists).run(s);
1110 1110
  ///
1111 1111
  ///  // Compute the DFS path from s to t
1112 1112
  ///  bool reached = dfs(g).path(p).dist(d).run(s,t);
1113 1113
  ///\endcode
1114 1114

	
1115 1115
  ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1116 1116
  ///to the end of the parameter list.
1117 1117
  ///\sa DfsWizard
1118 1118
  ///\sa Dfs
1119 1119
  template<class GR>
1120 1120
  DfsWizard<DfsWizardBase<GR> >
1121 1121
  dfs(const GR &digraph)
1122 1122
  {
1123 1123
    return DfsWizard<DfsWizardBase<GR> >(digraph);
1124 1124
  }
1125 1125

	
1126 1126
#ifdef DOXYGEN
1127 1127
  /// \brief Visitor class for DFS.
1128 1128
  ///
1129 1129
  /// This class defines the interface of the DfsVisit events, and
1130 1130
  /// it could be the base of a real visitor class.
1131 1131
  template <typename _Digraph>
1132 1132
  struct DfsVisitor {
1133 1133
    typedef _Digraph Digraph;
1134 1134
    typedef typename Digraph::Arc Arc;
1135 1135
    typedef typename Digraph::Node Node;
1136 1136
    /// \brief Called for the source node of the DFS.
1137 1137
    ///
1138 1138
    /// This function is called for the source node of the DFS.
1139 1139
    void start(const Node& node) {}
1140 1140
    /// \brief Called when the source node is leaved.
1141 1141
    ///
1142 1142
    /// This function is called when the source node is leaved.
1143 1143
    void stop(const Node& node) {}
1144 1144
    /// \brief Called when a node is reached first time.
1145 1145
    ///
1146 1146
    /// This function is called when a node is reached first time.
1147 1147
    void reach(const Node& node) {}
1148 1148
    /// \brief Called when an arc reaches a new node.
1149 1149
    ///
1150 1150
    /// This function is called when the DFS finds an arc whose target node
1151 1151
    /// is not reached yet.
1152 1152
    void discover(const Arc& arc) {}
1153 1153
    /// \brief Called when an arc is examined but its target node is
1154 1154
    /// already discovered.
1155 1155
    ///
1156 1156
    /// This function is called when an arc is examined but its target node is
1157 1157
    /// already discovered.
1158 1158
    void examine(const Arc& arc) {}
1159 1159
    /// \brief Called when the DFS steps back from a node.
1160 1160
    ///
1161 1161
    /// This function is called when the DFS steps back from a node.
1162 1162
    void leave(const Node& node) {}
1163 1163
    /// \brief Called when the DFS steps back on an arc.
1164 1164
    ///
1165 1165
    /// This function is called when the DFS steps back on an arc.
1166 1166
    void backtrack(const Arc& arc) {}
1167 1167
  };
1168 1168
#else
1169 1169
  template <typename _Digraph>
1170 1170
  struct DfsVisitor {
1171 1171
    typedef _Digraph Digraph;
1172 1172
    typedef typename Digraph::Arc Arc;
1173 1173
    typedef typename Digraph::Node Node;
1174 1174
    void start(const Node&) {}
1175 1175
    void stop(const Node&) {}
1176 1176
    void reach(const Node&) {}
1177 1177
    void discover(const Arc&) {}
1178 1178
    void examine(const Arc&) {}
1179 1179
    void leave(const Node&) {}
1180 1180
    void backtrack(const Arc&) {}
1181 1181

	
1182 1182
    template <typename _Visitor>
1183 1183
    struct Constraints {
1184 1184
      void constraints() {
1185 1185
        Arc arc;
1186 1186
        Node node;
1187 1187
        visitor.start(node);
1188 1188
        visitor.stop(arc);
1189 1189
        visitor.reach(node);
1190 1190
        visitor.discover(arc);
1191 1191
        visitor.examine(arc);
1192 1192
        visitor.leave(node);
1193 1193
        visitor.backtrack(arc);
1194 1194
      }
1195 1195
      _Visitor& visitor;
1196 1196
    };
1197 1197
  };
1198 1198
#endif
1199 1199

	
1200 1200
  /// \brief Default traits class of DfsVisit class.
1201 1201
  ///
1202 1202
  /// Default traits class of DfsVisit class.
1203 1203
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1204 1204
  template<class _Digraph>
1205 1205
  struct DfsVisitDefaultTraits {
1206 1206

	
1207 1207
    /// \brief The type of the digraph the algorithm runs on.
1208 1208
    typedef _Digraph Digraph;
1209 1209

	
1210 1210
    /// \brief The type of the map that indicates which nodes are reached.
1211 1211
    ///
1212 1212
    /// The type of the map that indicates which nodes are reached.
1213 1213
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1214 1214
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1215 1215

	
1216 1216
    /// \brief Instantiates a ReachedMap.
1217 1217
    ///
1218 1218
    /// This function instantiates a ReachedMap.
1219 1219
    /// \param digraph is the digraph, to which
1220 1220
    /// we would like to define the ReachedMap.
1221 1221
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1222 1222
      return new ReachedMap(digraph);
1223 1223
    }
1224 1224

	
1225 1225
  };
1226 1226

	
1227 1227
  /// \ingroup search
1228 1228
  ///
1229 1229
  /// \brief %DFS algorithm class with visitor interface.
1230 1230
  ///
1231 1231
  /// This class provides an efficient implementation of the %DFS algorithm
1232 1232
  /// with visitor interface.
1233 1233
  ///
1234 1234
  /// The %DfsVisit class provides an alternative interface to the Dfs
1235 1235
  /// class. It works with callback mechanism, the DfsVisit object calls
1236 1236
  /// the member functions of the \c Visitor class on every DFS event.
1237 1237
  ///
1238 1238
  /// This interface of the DFS algorithm should be used in special cases
1239 1239
  /// when extra actions have to be performed in connection with certain
1240 1240
  /// events of the DFS algorithm. Otherwise consider to use Dfs or dfs()
1241 1241
  /// instead.
1242 1242
  ///
1243 1243
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
1244 1244
  /// The default value is
1245 1245
  /// \ref ListDigraph. The value of _Digraph is not used directly by
1246 1246
  /// \ref DfsVisit, it is only passed to \ref DfsVisitDefaultTraits.
1247 1247
  /// \tparam _Visitor The Visitor type that is used by the algorithm.
1248 1248
  /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty visitor, which
1249 1249
  /// does not observe the DFS events. If you want to observe the DFS
1250 1250
  /// events, you should implement your own visitor class.
1251 1251
  /// \tparam _Traits Traits class to set various data types used by the
1252 1252
  /// algorithm. The default traits class is
1253 1253
  /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>".
1254 1254
  /// See \ref DfsVisitDefaultTraits for the documentation of
1255 1255
  /// a DFS visit traits class.
1256 1256
#ifdef DOXYGEN
1257 1257
  template <typename _Digraph, typename _Visitor, typename _Traits>
1258 1258
#else
1259 1259
  template <typename _Digraph = ListDigraph,
1260 1260
            typename _Visitor = DfsVisitor<_Digraph>,
1261 1261
            typename _Traits = DfsVisitDefaultTraits<_Digraph> >
1262 1262
#endif
1263 1263
  class DfsVisit {
1264 1264
  public:
1265 1265

	
1266 1266
    ///The traits class.
1267 1267
    typedef _Traits Traits;
1268 1268

	
1269 1269
    ///The type of the digraph the algorithm runs on.
1270 1270
    typedef typename Traits::Digraph Digraph;
1271 1271

	
1272 1272
    ///The visitor type used by the algorithm.
1273 1273
    typedef _Visitor Visitor;
1274 1274

	
1275 1275
    ///The type of the map that indicates which nodes are reached.
1276 1276
    typedef typename Traits::ReachedMap ReachedMap;
1277 1277

	
1278 1278
  private:
1279 1279

	
1280 1280
    typedef typename Digraph::Node Node;
1281 1281
    typedef typename Digraph::NodeIt NodeIt;
1282 1282
    typedef typename Digraph::Arc Arc;
1283 1283
    typedef typename Digraph::OutArcIt OutArcIt;
1284 1284

	
1285 1285
    //Pointer to the underlying digraph.
1286 1286
    const Digraph *_digraph;
1287 1287
    //Pointer to the visitor object.
1288 1288
    Visitor *_visitor;
1289 1289
    //Pointer to the map of reached status of the nodes.
1290 1290
    ReachedMap *_reached;
1291 1291
    //Indicates if _reached is locally allocated (true) or not.
1292 1292
    bool local_reached;
1293 1293

	
1294 1294
    std::vector<typename Digraph::Arc> _stack;
1295 1295
    int _stack_head;
1296 1296

	
1297 1297
    //Creates the maps if necessary.
1298 1298
    void create_maps() {
1299 1299
      if(!_reached) {
1300 1300
        local_reached = true;
1301 1301
        _reached = Traits::createReachedMap(*_digraph);
1302 1302
      }
1303 1303
    }
1304 1304

	
1305 1305
  protected:
1306 1306

	
1307 1307
    DfsVisit() {}
1308 1308

	
1309 1309
  public:
1310 1310

	
1311 1311
    typedef DfsVisit Create;
1312 1312

	
1313 1313
    /// \name Named template parameters
1314 1314

	
1315 1315
    ///@{
1316 1316
    template <class T>
1317 1317
    struct SetReachedMapTraits : public Traits {
1318 1318
      typedef T ReachedMap;
1319 1319
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1320 1320
        LEMON_ASSERT(false, "ReachedMap is not initialized");
1321 1321
        return 0; // ignore warnings
1322 1322
      }
1323 1323
    };
1324 1324
    /// \brief \ref named-templ-param "Named parameter" for setting
1325 1325
    /// ReachedMap type.
1326 1326
    ///
1327 1327
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1328 1328
    template <class T>
1329 1329
    struct SetReachedMap : public DfsVisit< Digraph, Visitor,
1330 1330
                                            SetReachedMapTraits<T> > {
1331 1331
      typedef DfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1332 1332
    };
1333 1333
    ///@}
1334 1334

	
1335 1335
  public:
1336 1336

	
1337 1337
    /// \brief Constructor.
1338 1338
    ///
1339 1339
    /// Constructor.
1340 1340
    ///
1341 1341
    /// \param digraph The digraph the algorithm runs on.
1342 1342
    /// \param visitor The visitor object of the algorithm.
1343 1343
    DfsVisit(const Digraph& digraph, Visitor& visitor)
1344 1344
      : _digraph(&digraph), _visitor(&visitor),
1345 1345
        _reached(0), local_reached(false) {}
1346 1346

	
1347 1347
    /// \brief Destructor.
1348 1348
    ~DfsVisit() {
1349 1349
      if(local_reached) delete _reached;
1350 1350
    }
1351 1351

	
1352 1352
    /// \brief Sets the map that indicates which nodes are reached.
1353 1353
    ///
1354 1354
    /// Sets the map that indicates which nodes are reached.
1355 1355
    /// If you don't use this function before calling \ref run(),
1356 1356
    /// it will allocate one. The destructor deallocates this
1357 1357
    /// automatically allocated map, of course.
1358 1358
    /// \return <tt> (*this) </tt>
1359 1359
    DfsVisit &reachedMap(ReachedMap &m) {
1360 1360
      if(local_reached) {
1361 1361
        delete _reached;
1362 1362
        local_reached=false;
1363 1363
      }
1364 1364
      _reached = &m;
1365 1365
      return *this;
1366 1366
    }
1367 1367

	
1368 1368
  public:
1369 1369

	
1370 1370
    /// \name Execution control
1371 1371
    /// The simplest way to execute the algorithm is to use
1372 1372
    /// one of the member functions called \ref lemon::DfsVisit::run()
1373 1373
    /// "run()".
1374 1374
    /// \n
1375 1375
    /// If you need more control on the execution, first you must call
1376 1376
    /// \ref lemon::DfsVisit::init() "init()", then you can add several
1377 1377
    /// source nodes with \ref lemon::DfsVisit::addSource() "addSource()".
1378 1378
    /// Finally \ref lemon::DfsVisit::start() "start()" will perform the
1379 1379
    /// actual path computation.
1380 1380

	
1381 1381
    /// @{
1382 1382

	
1383 1383
    /// \brief Initializes the internal data structures.
1384 1384
    ///
1385 1385
    /// Initializes the internal data structures.
1386 1386
    void init() {
1387 1387
      create_maps();
1388 1388
      _stack.resize(countNodes(*_digraph));
1389 1389
      _stack_head = -1;
1390 1390
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1391 1391
        _reached->set(u, false);
1392 1392
      }
1393 1393
    }
1394 1394

	
1395 1395
    ///Adds a new source node.
1396 1396

	
1397 1397
    ///Adds a new source node to the set of nodes to be processed.
1398 1398
    ///
1399 1399
    ///\pre The stack must be empty. (Otherwise the algorithm gives
1400 1400
    ///false results.)
1401 1401
    ///
1402 1402
    ///\warning Distances will be wrong (or at least strange) in case of
1403 1403
    ///multiple sources.
1404 1404
    void addSource(Node s)
1405 1405
    {
1406 1406
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
1407 1407
      if(!(*_reached)[s]) {
1408 1408
          _reached->set(s,true);
1409 1409
          _visitor->start(s);
1410 1410
          _visitor->reach(s);
1411 1411
          Arc e;
1412 1412
          _digraph->firstOut(e, s);
1413 1413
          if (e != INVALID) {
1414 1414
            _stack[++_stack_head] = e;
1415 1415
          } else {
1416 1416
            _visitor->leave(s);
1417 1417
          }
1418 1418
        }
1419 1419
    }
1420 1420

	
1421 1421
    /// \brief Processes the next arc.
1422 1422
    ///
1423 1423
    /// Processes the next arc.
1424 1424
    ///
1425 1425
    /// \return The processed arc.
1426 1426
    ///
1427 1427
    /// \pre The stack must not be empty.
1428 1428
    Arc processNextArc() {
1429 1429
      Arc e = _stack[_stack_head];
1430 1430
      Node m = _digraph->target(e);
1431 1431
      if(!(*_reached)[m]) {
1432 1432
        _visitor->discover(e);
1433 1433
        _visitor->reach(m);
1434 1434
        _reached->set(m, true);
1435 1435
        _digraph->firstOut(_stack[++_stack_head], m);
1436 1436
      } else {
1437 1437
        _visitor->examine(e);
1438 1438
        m = _digraph->source(e);
1439 1439
        _digraph->nextOut(_stack[_stack_head]);
1440 1440
      }
1441 1441
      while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1442 1442
        _visitor->leave(m);
1443 1443
        --_stack_head;
1444 1444
        if (_stack_head >= 0) {
1445 1445
          _visitor->backtrack(_stack[_stack_head]);
1446 1446
          m = _digraph->source(_stack[_stack_head]);
1447 1447
          _digraph->nextOut(_stack[_stack_head]);
1448 1448
        } else {
1449 1449
          _visitor->stop(m);
1450 1450
        }
1451 1451
      }
1452 1452
      return e;
1453 1453
    }
1454 1454

	
1455 1455
    /// \brief Next arc to be processed.
1456 1456
    ///
1457 1457
    /// Next arc to be processed.
1458 1458
    ///
1459 1459
    /// \return The next arc to be processed or INVALID if the stack is
1460 1460
    /// empty.
1461 1461
    Arc nextArc() const {
1462 1462
      return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1463 1463
    }
1464 1464

	
1465 1465
    /// \brief Returns \c false if there are nodes
1466 1466
    /// to be processed.
1467 1467
    ///
1468 1468
    /// Returns \c false if there are nodes
1469 1469
    /// to be processed in the queue (stack).
1470 1470
    bool emptyQueue() const { return _stack_head < 0; }
1471 1471

	
1472 1472
    /// \brief Returns the number of the nodes to be processed.
1473 1473
    ///
1474 1474
    /// Returns the number of the nodes to be processed in the queue (stack).
1475 1475
    int queueSize() const { return _stack_head + 1; }
1476 1476

	
1477 1477
    /// \brief Executes the algorithm.
1478 1478
    ///
1479 1479
    /// Executes the algorithm.
1480 1480
    ///
1481 1481
    /// This method runs the %DFS algorithm from the root node
1482 1482
    /// in order to compute the %DFS path to each node.
1483 1483
    ///
1484 1484
    /// The algorithm computes
1485 1485
    /// - the %DFS tree,
1486 1486
    /// - the distance of each node from the root in the %DFS tree.
1487 1487
    ///
1488 1488
    /// \pre init() must be called and a root node should be
1489 1489
    /// added with addSource() before using this function.
1490 1490
    ///
1491 1491
    /// \note <tt>d.start()</tt> is just a shortcut of the following code.
1492 1492
    /// \code
1493 1493
    ///   while ( !d.emptyQueue() ) {
1494 1494
    ///     d.processNextArc();
1495 1495
    ///   }
1496 1496
    /// \endcode
1497 1497
    void start() {
1498 1498
      while ( !emptyQueue() ) processNextArc();
1499 1499
    }
1500 1500

	
1501 1501
    /// \brief Executes the algorithm until the given target node is reached.
1502 1502
    ///
1503 1503
    /// Executes the algorithm until the given target node is reached.
1504 1504
    ///
1505 1505
    /// This method runs the %DFS algorithm from the root node
1506 1506
    /// in order to compute the DFS path to \c t.
1507 1507
    ///
1508 1508
    /// The algorithm computes
1509 1509
    /// - the %DFS path to \c t,
1510 1510
    /// - the distance of \c t from the root in the %DFS tree.
1511 1511
    ///
1512 1512
    /// \pre init() must be called and a root node should be added
1513 1513
    /// with addSource() before using this function.
1514 1514
    void start(Node t) {
1515 1515
      while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != t )
1516 1516
        processNextArc();
1517 1517
    }
1518 1518

	
1519 1519
    /// \brief Executes the algorithm until a condition is met.
1520 1520
    ///
1521 1521
    /// Executes the algorithm until a condition is met.
1522 1522
    ///
1523 1523
    /// This method runs the %DFS algorithm from the root node
1524 1524
    /// until an arc \c a with <tt>am[a]</tt> true is found.
1525 1525
    ///
1526 1526
    /// \param am A \c bool (or convertible) arc map. The algorithm
1527 1527
    /// will stop when it reaches an arc \c a with <tt>am[a]</tt> true.
1528 1528
    ///
1529 1529
    /// \return The reached arc \c a with <tt>am[a]</tt> true or
1530 1530
    /// \c INVALID if no such arc was found.
1531 1531
    ///
1532 1532
    /// \pre init() must be called and a root node should be added
1533 1533
    /// with addSource() before using this function.
1534 1534
    ///
1535 1535
    /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c am is an arc map,
1536 1536
    /// not a node map.
1537 1537
    template <typename AM>
1538 1538
    Arc start(const AM &am) {
1539 1539
      while ( !emptyQueue() && !am[_stack[_stack_head]] )
1540 1540
        processNextArc();
1541 1541
      return emptyQueue() ? INVALID : _stack[_stack_head];
1542 1542
    }
1543 1543

	
1544 1544
    /// \brief Runs the algorithm from the given source node.
1545 1545
    ///
1546 1546
    /// This method runs the %DFS algorithm from node \c s.
1547 1547
    /// in order to compute the DFS path to each node.
1548 1548
    ///
1549 1549
    /// The algorithm computes
1550 1550
    /// - the %DFS tree,
1551 1551
    /// - the distance of each node from the root in the %DFS tree.
1552 1552
    ///
1553 1553
    /// \note <tt>d.run(s)</tt> is just a shortcut of the following code.
1554 1554
    ///\code
1555 1555
    ///   d.init();
1556 1556
    ///   d.addSource(s);
1557 1557
    ///   d.start();
1558 1558
    ///\endcode
1559 1559
    void run(Node s) {
1560 1560
      init();
1561 1561
      addSource(s);
1562 1562
      start();
1563 1563
    }
1564 1564

	
1565 1565
    /// \brief Finds the %DFS path between \c s and \c t.
1566 1566

	
1567 1567
    /// This method runs the %DFS algorithm from node \c s
1568 1568
    /// in order to compute the DFS path to node \c t
1569 1569
    /// (it stops searching when \c t is processed).
1570 1570
    ///
1571 1571
    /// \return \c true if \c t is reachable form \c s.
1572 1572
    ///
1573 1573
    /// \note Apart from the return value, <tt>d.run(s,t)</tt> is
1574 1574
    /// just a shortcut of the following code.
1575 1575
    ///\code
1576 1576
    ///   d.init();
1577 1577
    ///   d.addSource(s);
1578 1578
    ///   d.start(t);
1579 1579
    ///\endcode
1580 1580
    bool run(Node s,Node t) {
1581 1581
      init();
1582 1582
      addSource(s);
1583 1583
      start(t);
1584 1584
      return reached(t);
1585 1585
    }
1586 1586

	
1587 1587
    /// \brief Runs the algorithm to visit all nodes in the digraph.
1588 1588

	
1589 1589
    /// This method runs the %DFS algorithm in order to
1590 1590
    /// compute the %DFS path to each node.
1591 1591
    ///
1592 1592
    /// The algorithm computes
1593 1593
    /// - the %DFS tree,
1594 1594
    /// - the distance of each node from the root in the %DFS tree.
1595 1595
    ///
1596 1596
    /// \note <tt>d.run()</tt> is just a shortcut of the following code.
1597 1597
    ///\code
1598 1598
    ///   d.init();
1599 1599
    ///   for (NodeIt n(digraph); n != INVALID; ++n) {
1600 1600
    ///     if (!d.reached(n)) {
1601 1601
    ///       d.addSource(n);
1602 1602
    ///       d.start();
1603 1603
    ///     }
1604 1604
    ///   }
1605 1605
    ///\endcode
1606 1606
    void run() {
1607 1607
      init();
1608 1608
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1609 1609
        if (!reached(it)) {
1610 1610
          addSource(it);
1611 1611
          start();
1612 1612
        }
1613 1613
      }
1614 1614
    }
1615 1615

	
1616 1616
    ///@}
1617 1617

	
1618 1618
    /// \name Query Functions
1619 1619
    /// The result of the %DFS algorithm can be obtained using these
1620 1620
    /// functions.\n
1621 1621
    /// Either \ref lemon::DfsVisit::run() "run()" or
1622 1622
    /// \ref lemon::DfsVisit::start() "start()" must be called before
1623 1623
    /// using them.
1624 1624
    ///@{
1625 1625

	
1626 1626
    /// \brief Checks if a node is reachable from the root(s).
1627 1627
    ///
1628 1628
    /// Returns \c true if \c v is reachable from the root(s).
1629 1629
    /// \pre Either \ref run() or \ref start()
1630 1630
    /// must be called before using this function.
1631 1631
    bool reached(Node v) { return (*_reached)[v]; }
1632 1632

	
1633 1633
    ///@}
1634 1634

	
1635 1635
  };
1636 1636

	
1637 1637
} //END OF NAMESPACE LEMON
1638 1638

	
1639 1639
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_DIJKSTRA_H
20 20
#define LEMON_DIJKSTRA_H
21 21

	
22 22
///\ingroup shortest_path
23 23
///\file
24 24
///\brief Dijkstra algorithm.
25 25

	
26 26
#include <limits>
27 27
#include <lemon/list_graph.h>
28 28
#include <lemon/bin_heap.h>
29 29
#include <lemon/bits/path_dump.h>
30 30
#include <lemon/core.h>
31 31
#include <lemon/error.h>
32 32
#include <lemon/maps.h>
33 33
#include <lemon/path.h>
34 34

	
35 35
namespace lemon {
36 36

	
37 37
  /// \brief Default operation traits for the Dijkstra algorithm class.
38 38
  ///
39 39
  /// This operation traits class defines all computational operations and
40 40
  /// constants which are used in the Dijkstra algorithm.
41 41
  template <typename Value>
42 42
  struct DijkstraDefaultOperationTraits {
43 43
    /// \brief Gives back the zero value of the type.
44 44
    static Value zero() {
45 45
      return static_cast<Value>(0);
46 46
    }
47 47
    /// \brief Gives back the sum of the given two elements.
48 48
    static Value plus(const Value& left, const Value& right) {
49 49
      return left + right;
50 50
    }
51 51
    /// \brief Gives back true only if the first value is less than the second.
52 52
    static bool less(const Value& left, const Value& right) {
53 53
      return left < right;
54 54
    }
55 55
  };
56 56

	
57 57
  /// \brief Widest path operation traits for the Dijkstra algorithm class.
58 58
  ///
59 59
  /// This operation traits class defines all computational operations and
60 60
  /// constants which are used in the Dijkstra algorithm for widest path
61 61
  /// computation.
62 62
  ///
63 63
  /// \see DijkstraDefaultOperationTraits
64 64
  template <typename Value>
65 65
  struct DijkstraWidestPathOperationTraits {
66 66
    /// \brief Gives back the maximum value of the type.
67 67
    static Value zero() {
68 68
      return std::numeric_limits<Value>::max();
69 69
    }
70 70
    /// \brief Gives back the minimum of the given two elements.
71 71
    static Value plus(const Value& left, const Value& right) {
72 72
      return std::min(left, right);
73 73
    }
74 74
    /// \brief Gives back true only if the first value is less than the second.
75 75
    static bool less(const Value& left, const Value& right) {
76 76
      return left < right;
77 77
    }
78 78
  };
79 79

	
80 80
  ///Default traits class of Dijkstra class.
81 81

	
82 82
  ///Default traits class of Dijkstra class.
83 83
  ///\tparam GR The type of the digraph.
84 84
  ///\tparam LM The type of the length map.
85 85
  template<class GR, class LM>
86 86
  struct DijkstraDefaultTraits
87 87
  {
88 88
    ///The type of the digraph the algorithm runs on.
89 89
    typedef GR Digraph;
90 90

	
91 91
    ///The type of the map that stores the arc lengths.
92 92

	
93 93
    ///The type of the map that stores the arc lengths.
94 94
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
95 95
    typedef LM LengthMap;
96 96
    ///The type of the length of the arcs.
97 97
    typedef typename LM::Value Value;
98 98

	
99 99
    /// Operation traits for Dijkstra algorithm.
100 100

	
101 101
    /// This class defines the operations that are used in the algorithm.
102 102
    /// \see DijkstraDefaultOperationTraits
103 103
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
104 104

	
105 105
    /// The cross reference type used by the heap.
106 106

	
107 107
    /// The cross reference type used by the heap.
108 108
    /// Usually it is \c Digraph::NodeMap<int>.
109 109
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
110 110
    ///Instantiates a \ref HeapCrossRef.
111 111

	
112 112
    ///This function instantiates a \ref HeapCrossRef.
113 113
    /// \param g is the digraph, to which we would like to define the
114 114
    /// \ref HeapCrossRef.
115 115
    static HeapCrossRef *createHeapCrossRef(const Digraph &g)
116 116
    {
117 117
      return new HeapCrossRef(g);
118 118
    }
119 119

	
120 120
    ///The heap type used by the Dijkstra algorithm.
121 121

	
122 122
    ///The heap type used by the Dijkstra algorithm.
123 123
    ///
124 124
    ///\sa BinHeap
125 125
    ///\sa Dijkstra
126 126
    typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap;
127 127
    ///Instantiates a \ref Heap.
128 128

	
129 129
    ///This function instantiates a \ref Heap.
130 130
    static Heap *createHeap(HeapCrossRef& r)
131 131
    {
132 132
      return new Heap(r);
133 133
    }
134 134

	
135 135
    ///\brief The type of the map that stores the predecessor
136 136
    ///arcs of the shortest paths.
137 137
    ///
138 138
    ///The type of the map that stores the predecessor
139 139
    ///arcs of the shortest paths.
140 140
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
141 141
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
142 142
    ///Instantiates a PredMap.
143 143

	
144 144
    ///This function instantiates a PredMap.
145 145
    ///\param g is the digraph, to which we would like to define the
146 146
    ///PredMap.
147 147
    static PredMap *createPredMap(const Digraph &g)
148 148
    {
149 149
      return new PredMap(g);
150 150
    }
151 151

	
152 152
    ///The type of the map that indicates which nodes are processed.
153 153

	
154 154
    ///The type of the map that indicates which nodes are processed.
155 155
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
156 156
    ///By default it is a NullMap.
157 157
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
158 158
    ///Instantiates a ProcessedMap.
159 159

	
160 160
    ///This function instantiates a ProcessedMap.
161 161
    ///\param g is the digraph, to which
162 162
    ///we would like to define the ProcessedMap
163 163
#ifdef DOXYGEN
164 164
    static ProcessedMap *createProcessedMap(const Digraph &g)
165 165
#else
166 166
    static ProcessedMap *createProcessedMap(const Digraph &)
167 167
#endif
168 168
    {
169 169
      return new ProcessedMap();
170 170
    }
171 171

	
172 172
    ///The type of the map that stores the distances of the nodes.
173 173

	
174 174
    ///The type of the map that stores the distances of the nodes.
175 175
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
176 176
    typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
177 177
    ///Instantiates a DistMap.
178 178

	
179 179
    ///This function instantiates a DistMap.
180 180
    ///\param g is the digraph, to which we would like to define
181 181
    ///the DistMap
182 182
    static DistMap *createDistMap(const Digraph &g)
183 183
    {
184 184
      return new DistMap(g);
185 185
    }
186 186
  };
187 187

	
188 188
  ///%Dijkstra algorithm class.
189 189

	
190 190
  /// \ingroup shortest_path
191 191
  ///This class provides an efficient implementation of the %Dijkstra algorithm.
192 192
  ///
193 193
  ///The arc lengths are passed to the algorithm using a
194 194
  ///\ref concepts::ReadMap "ReadMap",
195 195
  ///so it is easy to change it to any kind of length.
196 196
  ///The type of the length is determined by the
197 197
  ///\ref concepts::ReadMap::Value "Value" of the length map.
198 198
  ///It is also possible to change the underlying priority heap.
199 199
  ///
200 200
  ///There is also a \ref dijkstra() "function-type interface" for the
201 201
  ///%Dijkstra algorithm, which is convenient in the simplier cases and
202 202
  ///it can be used easier.
203 203
  ///
204 204
  ///\tparam GR The type of the digraph the algorithm runs on.
205 205
  ///The default value is \ref ListDigraph.
206 206
  ///The value of GR is not used directly by \ref Dijkstra, it is only
207 207
  ///passed to \ref DijkstraDefaultTraits.
208 208
  ///\tparam LM A readable arc map that determines the lengths of the
209 209
  ///arcs. It is read once for each arc, so the map may involve in
210 210
  ///relatively time consuming process to compute the arc lengths if
211 211
  ///it is necessary. The default map type is \ref
212 212
  ///concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
213 213
  ///The value of LM is not used directly by \ref Dijkstra, it is only
214 214
  ///passed to \ref DijkstraDefaultTraits.
215 215
  ///\tparam TR Traits class to set various data types used by the algorithm.
216 216
  ///The default traits class is \ref DijkstraDefaultTraits
217 217
  ///"DijkstraDefaultTraits<GR,LM>". See \ref DijkstraDefaultTraits
218 218
  ///for the documentation of a Dijkstra traits class.
219 219
#ifdef DOXYGEN
220 220
  template <typename GR, typename LM, typename TR>
221 221
#else
222 222
  template <typename GR=ListDigraph,
223 223
            typename LM=typename GR::template ArcMap<int>,
224 224
            typename TR=DijkstraDefaultTraits<GR,LM> >
225 225
#endif
226 226
  class Dijkstra {
227 227
  public:
228 228

	
229 229
    ///The type of the digraph the algorithm runs on.
230 230
    typedef typename TR::Digraph Digraph;
231 231

	
232 232
    ///The type of the length of the arcs.
233 233
    typedef typename TR::LengthMap::Value Value;
234 234
    ///The type of the map that stores the arc lengths.
235 235
    typedef typename TR::LengthMap LengthMap;
236 236
    ///\brief The type of the map that stores the predecessor arcs of the
237 237
    ///shortest paths.
238 238
    typedef typename TR::PredMap PredMap;
239 239
    ///The type of the map that stores the distances of the nodes.
240 240
    typedef typename TR::DistMap DistMap;
241 241
    ///The type of the map that indicates which nodes are processed.
242 242
    typedef typename TR::ProcessedMap ProcessedMap;
243 243
    ///The type of the paths.
244 244
    typedef PredMapPath<Digraph, PredMap> Path;
245 245
    ///The cross reference type used for the current heap.
246 246
    typedef typename TR::HeapCrossRef HeapCrossRef;
247 247
    ///The heap type used by the algorithm.
248 248
    typedef typename TR::Heap Heap;
249 249
    ///The operation traits class.
250 250
    typedef typename TR::OperationTraits OperationTraits;
251 251

	
252 252
    ///The traits class.
253 253
    typedef TR Traits;
254 254

	
255 255
  private:
256 256

	
257 257
    typedef typename Digraph::Node Node;
258 258
    typedef typename Digraph::NodeIt NodeIt;
259 259
    typedef typename Digraph::Arc Arc;
260 260
    typedef typename Digraph::OutArcIt OutArcIt;
261 261

	
262 262
    //Pointer to the underlying digraph.
263 263
    const Digraph *G;
264 264
    //Pointer to the length map.
265 265
    const LengthMap *length;
266 266
    //Pointer to the map of predecessors arcs.
267 267
    PredMap *_pred;
268 268
    //Indicates if _pred is locally allocated (true) or not.
269 269
    bool local_pred;
270 270
    //Pointer to the map of distances.
271 271
    DistMap *_dist;
272 272
    //Indicates if _dist is locally allocated (true) or not.
273 273
    bool local_dist;
274 274
    //Pointer to the map of processed status of the nodes.
275 275
    ProcessedMap *_processed;
276 276
    //Indicates if _processed is locally allocated (true) or not.
277 277
    bool local_processed;
278 278
    //Pointer to the heap cross references.
279 279
    HeapCrossRef *_heap_cross_ref;
280 280
    //Indicates if _heap_cross_ref is locally allocated (true) or not.
281 281
    bool local_heap_cross_ref;
282 282
    //Pointer to the heap.
283 283
    Heap *_heap;
284 284
    //Indicates if _heap is locally allocated (true) or not.
285 285
    bool local_heap;
286 286

	
287 287
    //Creates the maps if necessary.
288 288
    void create_maps()
289 289
    {
290 290
      if(!_pred) {
291 291
        local_pred = true;
292 292
        _pred = Traits::createPredMap(*G);
293 293
      }
294 294
      if(!_dist) {
295 295
        local_dist = true;
296 296
        _dist = Traits::createDistMap(*G);
297 297
      }
298 298
      if(!_processed) {
299 299
        local_processed = true;
300 300
        _processed = Traits::createProcessedMap(*G);
301 301
      }
302 302
      if (!_heap_cross_ref) {
303 303
        local_heap_cross_ref = true;
304 304
        _heap_cross_ref = Traits::createHeapCrossRef(*G);
305 305
      }
306 306
      if (!_heap) {
307 307
        local_heap = true;
308 308
        _heap = Traits::createHeap(*_heap_cross_ref);
309 309
      }
310 310
    }
311 311

	
312 312
  public:
313 313

	
314 314
    typedef Dijkstra Create;
315 315

	
316 316
    ///\name Named template parameters
317 317

	
318 318
    ///@{
319 319

	
320 320
    template <class T>
321 321
    struct SetPredMapTraits : public Traits {
322 322
      typedef T PredMap;
323 323
      static PredMap *createPredMap(const Digraph &)
324 324
      {
325 325
        LEMON_ASSERT(false, "PredMap is not initialized");
326 326
        return 0; // ignore warnings
327 327
      }
328 328
    };
329 329
    ///\brief \ref named-templ-param "Named parameter" for setting
330 330
    ///PredMap type.
331 331
    ///
332 332
    ///\ref named-templ-param "Named parameter" for setting
333 333
    ///PredMap type.
334 334
    template <class T>
335 335
    struct SetPredMap
336 336
      : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
337 337
      typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
338 338
    };
339 339

	
340 340
    template <class T>
341 341
    struct SetDistMapTraits : public Traits {
342 342
      typedef T DistMap;
343 343
      static DistMap *createDistMap(const Digraph &)
344 344
      {
345 345
        LEMON_ASSERT(false, "DistMap is not initialized");
346 346
        return 0; // ignore warnings
347 347
      }
348 348
    };
349 349
    ///\brief \ref named-templ-param "Named parameter" for setting
350 350
    ///DistMap type.
351 351
    ///
352 352
    ///\ref named-templ-param "Named parameter" for setting
353 353
    ///DistMap type.
354 354
    template <class T>
355 355
    struct SetDistMap
356 356
      : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
357 357
      typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
358 358
    };
359 359

	
360 360
    template <class T>
361 361
    struct SetProcessedMapTraits : public Traits {
362 362
      typedef T ProcessedMap;
363 363
      static ProcessedMap *createProcessedMap(const Digraph &)
364 364
      {
365 365
        LEMON_ASSERT(false, "ProcessedMap is not initialized");
366 366
        return 0; // ignore warnings
367 367
      }
368 368
    };
369 369
    ///\brief \ref named-templ-param "Named parameter" for setting
370 370
    ///ProcessedMap type.
371 371
    ///
372 372
    ///\ref named-templ-param "Named parameter" for setting
373 373
    ///ProcessedMap type.
374 374
    template <class T>
375 375
    struct SetProcessedMap
376 376
      : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
377 377
      typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
378 378
    };
379 379

	
380 380
    struct SetStandardProcessedMapTraits : public Traits {
381 381
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
382 382
      static ProcessedMap *createProcessedMap(const Digraph &g)
383 383
      {
384 384
        return new ProcessedMap(g);
385 385
      }
386 386
    };
387 387
    ///\brief \ref named-templ-param "Named parameter" for setting
388 388
    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
389 389
    ///
390 390
    ///\ref named-templ-param "Named parameter" for setting
391 391
    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
392 392
    ///If you don't set it explicitly, it will be automatically allocated.
393 393
    struct SetStandardProcessedMap
394 394
      : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
395 395
      typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
396 396
      Create;
397 397
    };
398 398

	
399 399
    template <class H, class CR>
400 400
    struct SetHeapTraits : public Traits {
401 401
      typedef CR HeapCrossRef;
402 402
      typedef H Heap;
403 403
      static HeapCrossRef *createHeapCrossRef(const Digraph &) {
404 404
        LEMON_ASSERT(false, "HeapCrossRef is not initialized");
405 405
        return 0; // ignore warnings
406 406
      }
407 407
      static Heap *createHeap(HeapCrossRef &)
408 408
      {
409 409
        LEMON_ASSERT(false, "Heap is not initialized");
410 410
        return 0; // ignore warnings
411 411
      }
412 412
    };
413 413
    ///\brief \ref named-templ-param "Named parameter" for setting
414 414
    ///heap and cross reference type
415 415
    ///
416 416
    ///\ref named-templ-param "Named parameter" for setting heap and cross
417 417
    ///reference type.
418 418
    template <class H, class CR = typename Digraph::template NodeMap<int> >
419 419
    struct SetHeap
420 420
      : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
421 421
      typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
422 422
    };
423 423

	
424 424
    template <class H, class CR>
425 425
    struct SetStandardHeapTraits : public Traits {
426 426
      typedef CR HeapCrossRef;
427 427
      typedef H Heap;
428 428
      static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
429 429
        return new HeapCrossRef(G);
430 430
      }
431 431
      static Heap *createHeap(HeapCrossRef &R)
432 432
      {
433 433
        return new Heap(R);
434 434
      }
435 435
    };
436 436
    ///\brief \ref named-templ-param "Named parameter" for setting
437 437
    ///heap and cross reference type with automatic allocation
438 438
    ///
439 439
    ///\ref named-templ-param "Named parameter" for setting heap and cross
440 440
    ///reference type. It can allocate the heap and the cross reference
441 441
    ///object if the cross reference's constructor waits for the digraph as
442 442
    ///parameter and the heap's constructor waits for the cross reference.
443 443
    template <class H, class CR = typename Digraph::template NodeMap<int> >
444 444
    struct SetStandardHeap
445 445
      : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
446 446
      typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
447 447
      Create;
448 448
    };
449 449

	
450 450
    template <class T>
451 451
    struct SetOperationTraitsTraits : public Traits {
452 452
      typedef T OperationTraits;
453 453
    };
454 454

	
455 455
    /// \brief \ref named-templ-param "Named parameter" for setting
456
    ///\ref OperationTraits type
456
    ///\c OperationTraits type
457 457
    ///
458 458
    ///\ref named-templ-param "Named parameter" for setting
459 459
    ///\ref OperationTraits type.
460 460
    template <class T>
461 461
    struct SetOperationTraits
462 462
      : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
463 463
      typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
464 464
      Create;
465 465
    };
466 466

	
467 467
    ///@}
468 468

	
469 469
  protected:
470 470

	
471 471
    Dijkstra() {}
472 472

	
473 473
  public:
474 474

	
475 475
    ///Constructor.
476 476

	
477 477
    ///Constructor.
478 478
    ///\param _g The digraph the algorithm runs on.
479 479
    ///\param _length The length map used by the algorithm.
480 480
    Dijkstra(const Digraph& _g, const LengthMap& _length) :
481 481
      G(&_g), length(&_length),
482 482
      _pred(NULL), local_pred(false),
483 483
      _dist(NULL), local_dist(false),
484 484
      _processed(NULL), local_processed(false),
485 485
      _heap_cross_ref(NULL), local_heap_cross_ref(false),
486 486
      _heap(NULL), local_heap(false)
487 487
    { }
488 488

	
489 489
    ///Destructor.
490 490
    ~Dijkstra()
491 491
    {
492 492
      if(local_pred) delete _pred;
493 493
      if(local_dist) delete _dist;
494 494
      if(local_processed) delete _processed;
495 495
      if(local_heap_cross_ref) delete _heap_cross_ref;
496 496
      if(local_heap) delete _heap;
497 497
    }
498 498

	
499 499
    ///Sets the length map.
500 500

	
501 501
    ///Sets the length map.
502 502
    ///\return <tt> (*this) </tt>
503 503
    Dijkstra &lengthMap(const LengthMap &m)
504 504
    {
505 505
      length = &m;
506 506
      return *this;
507 507
    }
508 508

	
509 509
    ///Sets the map that stores the predecessor arcs.
510 510

	
511 511
    ///Sets the map that stores the predecessor arcs.
512 512
    ///If you don't use this function before calling \ref run(),
513 513
    ///it will allocate one. The destructor deallocates this
514 514
    ///automatically allocated map, of course.
515 515
    ///\return <tt> (*this) </tt>
516 516
    Dijkstra &predMap(PredMap &m)
517 517
    {
518 518
      if(local_pred) {
519 519
        delete _pred;
520 520
        local_pred=false;
521 521
      }
522 522
      _pred = &m;
523 523
      return *this;
524 524
    }
525 525

	
526 526
    ///Sets the map that indicates which nodes are processed.
527 527

	
528 528
    ///Sets the map that indicates which nodes are processed.
529 529
    ///If you don't use this function before calling \ref run(),
530 530
    ///it will allocate one. The destructor deallocates this
531 531
    ///automatically allocated map, of course.
532 532
    ///\return <tt> (*this) </tt>
533 533
    Dijkstra &processedMap(ProcessedMap &m)
534 534
    {
535 535
      if(local_processed) {
536 536
        delete _processed;
537 537
        local_processed=false;
538 538
      }
539 539
      _processed = &m;
540 540
      return *this;
541 541
    }
542 542

	
543 543
    ///Sets the map that stores the distances of the nodes.
544 544

	
545 545
    ///Sets the map that stores the distances of the nodes calculated by the
546 546
    ///algorithm.
547 547
    ///If you don't use this function before calling \ref run(),
548 548
    ///it will allocate one. The destructor deallocates this
549 549
    ///automatically allocated map, of course.
550 550
    ///\return <tt> (*this) </tt>
551 551
    Dijkstra &distMap(DistMap &m)
552 552
    {
553 553
      if(local_dist) {
554 554
        delete _dist;
555 555
        local_dist=false;
556 556
      }
557 557
      _dist = &m;
558 558
      return *this;
559 559
    }
560 560

	
561 561
    ///Sets the heap and the cross reference used by algorithm.
562 562

	
563 563
    ///Sets the heap and the cross reference used by algorithm.
564 564
    ///If you don't use this function before calling \ref run(),
565 565
    ///it will allocate one. The destructor deallocates this
566 566
    ///automatically allocated heap and cross reference, of course.
567 567
    ///\return <tt> (*this) </tt>
568 568
    Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
569 569
    {
570 570
      if(local_heap_cross_ref) {
571 571
        delete _heap_cross_ref;
572 572
        local_heap_cross_ref=false;
573 573
      }
574 574
      _heap_cross_ref = &cr;
575 575
      if(local_heap) {
576 576
        delete _heap;
577 577
        local_heap=false;
578 578
      }
579 579
      _heap = &hp;
580 580
      return *this;
581 581
    }
582 582

	
583 583
  private:
584 584

	
585 585
    void finalizeNodeData(Node v,Value dst)
586 586
    {
587 587
      _processed->set(v,true);
588 588
      _dist->set(v, dst);
589 589
    }
590 590

	
591 591
  public:
592 592

	
593 593
    ///\name Execution control
594 594
    ///The simplest way to execute the algorithm is to use one of the
595 595
    ///member functions called \ref lemon::Dijkstra::run() "run()".
596 596
    ///\n
597 597
    ///If you need more control on the execution, first you must call
598 598
    ///\ref lemon::Dijkstra::init() "init()", then you can add several
599 599
    ///source nodes with \ref lemon::Dijkstra::addSource() "addSource()".
600 600
    ///Finally \ref lemon::Dijkstra::start() "start()" will perform the
601 601
    ///actual path computation.
602 602

	
603 603
    ///@{
604 604

	
605 605
    ///Initializes the internal data structures.
606 606

	
607 607
    ///Initializes the internal data structures.
608 608
    ///
609 609
    void init()
610 610
    {
611 611
      create_maps();
612 612
      _heap->clear();
613 613
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
614 614
        _pred->set(u,INVALID);
615 615
        _processed->set(u,false);
616 616
        _heap_cross_ref->set(u,Heap::PRE_HEAP);
617 617
      }
618 618
    }
619 619

	
620 620
    ///Adds a new source node.
621 621

	
622 622
    ///Adds a new source node to the priority heap.
623 623
    ///The optional second parameter is the initial distance of the node.
624 624
    ///
625 625
    ///The function checks if the node has already been added to the heap and
626 626
    ///it is pushed to the heap only if either it was not in the heap
627 627
    ///or the shortest path found till then is shorter than \c dst.
628 628
    void addSource(Node s,Value dst=OperationTraits::zero())
629 629
    {
630 630
      if(_heap->state(s) != Heap::IN_HEAP) {
631 631
        _heap->push(s,dst);
632 632
      } else if(OperationTraits::less((*_heap)[s], dst)) {
633 633
        _heap->set(s,dst);
634 634
        _pred->set(s,INVALID);
635 635
      }
636 636
    }
637 637

	
638 638
    ///Processes the next node in the priority heap
639 639

	
640 640
    ///Processes the next node in the priority heap.
641 641
    ///
642 642
    ///\return The processed node.
643 643
    ///
644 644
    ///\warning The priority heap must not be empty.
645 645
    Node processNextNode()
646 646
    {
647 647
      Node v=_heap->top();
648 648
      Value oldvalue=_heap->prio();
649 649
      _heap->pop();
650 650
      finalizeNodeData(v,oldvalue);
651 651

	
652 652
      for(OutArcIt e(*G,v); e!=INVALID; ++e) {
653 653
        Node w=G->target(e);
654 654
        switch(_heap->state(w)) {
655 655
        case Heap::PRE_HEAP:
656 656
          _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e]));
657 657
          _pred->set(w,e);
658 658
          break;
659 659
        case Heap::IN_HEAP:
660 660
          {
661 661
            Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]);
662 662
            if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
663 663
              _heap->decrease(w, newvalue);
664 664
              _pred->set(w,e);
665 665
            }
666 666
          }
667 667
          break;
668 668
        case Heap::POST_HEAP:
669 669
          break;
670 670
        }
671 671
      }
672 672
      return v;
673 673
    }
674 674

	
675 675
    ///The next node to be processed.
676 676

	
677 677
    ///Returns the next node to be processed or \c INVALID if the
678 678
    ///priority heap is empty.
679 679
    Node nextNode() const
680 680
    {
681 681
      return !_heap->empty()?_heap->top():INVALID;
682 682
    }
683 683

	
684 684
    ///\brief Returns \c false if there are nodes
685 685
    ///to be processed.
686 686
    ///
687 687
    ///Returns \c false if there are nodes
688 688
    ///to be processed in the priority heap.
689 689
    bool emptyQueue() const { return _heap->empty(); }
690 690

	
691 691
    ///Returns the number of the nodes to be processed in the priority heap
692 692

	
693 693
    ///Returns the number of the nodes to be processed in the priority heap.
694 694
    ///
695 695
    int queueSize() const { return _heap->size(); }
696 696

	
697 697
    ///Executes the algorithm.
698 698

	
699 699
    ///Executes the algorithm.
700 700
    ///
701 701
    ///This method runs the %Dijkstra algorithm from the root node(s)
702 702
    ///in order to compute the shortest path to each node.
703 703
    ///
704 704
    ///The algorithm computes
705 705
    ///- the shortest path tree (forest),
706 706
    ///- the distance of each node from the root(s).
707 707
    ///
708 708
    ///\pre init() must be called and at least one root node should be
709 709
    ///added with addSource() before using this function.
710 710
    ///
711 711
    ///\note <tt>d.start()</tt> is just a shortcut of the following code.
712 712
    ///\code
713 713
    ///  while ( !d.emptyQueue() ) {
714 714
    ///    d.processNextNode();
715 715
    ///  }
716 716
    ///\endcode
717 717
    void start()
718 718
    {
719 719
      while ( !emptyQueue() ) processNextNode();
720 720
    }
721 721

	
722 722
    ///Executes the algorithm until the given target node is processed.
723 723

	
724 724
    ///Executes the algorithm until the given target node is processed.
725 725
    ///
726 726
    ///This method runs the %Dijkstra algorithm from the root node(s)
727 727
    ///in order to compute the shortest path to \c t.
728 728
    ///
729 729
    ///The algorithm computes
730 730
    ///- the shortest path to \c t,
731 731
    ///- the distance of \c t from the root(s).
732 732
    ///
733 733
    ///\pre init() must be called and at least one root node should be
734 734
    ///added with addSource() before using this function.
735 735
    void start(Node t)
736 736
    {
737 737
      while ( !_heap->empty() && _heap->top()!=t ) processNextNode();
738 738
      if ( !_heap->empty() ) {
739 739
        finalizeNodeData(_heap->top(),_heap->prio());
740 740
        _heap->pop();
741 741
      }
742 742
    }
743 743

	
744 744
    ///Executes the algorithm until a condition is met.
745 745

	
746 746
    ///Executes the algorithm until a condition is met.
747 747
    ///
748 748
    ///This method runs the %Dijkstra algorithm from the root node(s) in
749 749
    ///order to compute the shortest path to a node \c v with
750 750
    /// <tt>nm[v]</tt> true, if such a node can be found.
751 751
    ///
752 752
    ///\param nm A \c bool (or convertible) node map. The algorithm
753 753
    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
754 754
    ///
755 755
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
756 756
    ///\c INVALID if no such node was found.
757 757
    ///
758 758
    ///\pre init() must be called and at least one root node should be
759 759
    ///added with addSource() before using this function.
760 760
    template<class NodeBoolMap>
761 761
    Node start(const NodeBoolMap &nm)
762 762
    {
763 763
      while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
764 764
      if ( _heap->empty() ) return INVALID;
765 765
      finalizeNodeData(_heap->top(),_heap->prio());
766 766
      return _heap->top();
767 767
    }
768 768

	
769 769
    ///Runs the algorithm from the given source node.
770 770

	
771 771
    ///This method runs the %Dijkstra algorithm from node \c s
772 772
    ///in order to compute the shortest path to each node.
773 773
    ///
774 774
    ///The algorithm computes
775 775
    ///- the shortest path tree,
776 776
    ///- the distance of each node from the root.
777 777
    ///
778 778
    ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
779 779
    ///\code
780 780
    ///  d.init();
781 781
    ///  d.addSource(s);
782 782
    ///  d.start();
783 783
    ///\endcode
784 784
    void run(Node s) {
785 785
      init();
786 786
      addSource(s);
787 787
      start();
788 788
    }
789 789

	
790 790
    ///Finds the shortest path between \c s and \c t.
791 791

	
792 792
    ///This method runs the %Dijkstra algorithm from node \c s
793 793
    ///in order to compute the shortest path to node \c t
794 794
    ///(it stops searching when \c t is processed).
795 795
    ///
796 796
    ///\return \c true if \c t is reachable form \c s.
797 797
    ///
798 798
    ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
799 799
    ///shortcut of the following code.
800 800
    ///\code
801 801
    ///  d.init();
802 802
    ///  d.addSource(s);
803 803
    ///  d.start(t);
804 804
    ///\endcode
805 805
    bool run(Node s,Node t) {
806 806
      init();
807 807
      addSource(s);
808 808
      start(t);
809 809
      return (*_heap_cross_ref)[t] == Heap::POST_HEAP;
810 810
    }
811 811

	
812 812
    ///@}
813 813

	
814 814
    ///\name Query Functions
815 815
    ///The result of the %Dijkstra algorithm can be obtained using these
816 816
    ///functions.\n
817 817
    ///Either \ref lemon::Dijkstra::run() "run()" or
818 818
    ///\ref lemon::Dijkstra::start() "start()" must be called before
819 819
    ///using them.
820 820

	
821 821
    ///@{
822 822

	
823 823
    ///The shortest path to a node.
824 824

	
825 825
    ///Returns the shortest path to a node.
826 826
    ///
827 827
    ///\warning \c t should be reachable from the root(s).
828 828
    ///
829 829
    ///\pre Either \ref run() or \ref start() must be called before
830 830
    ///using this function.
831 831
    Path path(Node t) const { return Path(*G, *_pred, t); }
832 832

	
833 833
    ///The distance of a node from the root(s).
834 834

	
835 835
    ///Returns the distance of a node from the root(s).
836 836
    ///
837 837
    ///\warning If node \c v is not reachable from the root(s), then
838 838
    ///the return value of this function is undefined.
839 839
    ///
840 840
    ///\pre Either \ref run() or \ref start() must be called before
841 841
    ///using this function.
842 842
    Value dist(Node v) const { return (*_dist)[v]; }
843 843

	
844 844
    ///Returns the 'previous arc' of the shortest path tree for a node.
845 845

	
846 846
    ///This function returns the 'previous arc' of the shortest path
847 847
    ///tree for the node \c v, i.e. it returns the last arc of a
848 848
    ///shortest path from the root(s) to \c v. It is \c INVALID if \c v
849 849
    ///is not reachable from the root(s) or if \c v is a root.
850 850
    ///
851 851
    ///The shortest path tree used here is equal to the shortest path
852 852
    ///tree used in \ref predNode().
853 853
    ///
854 854
    ///\pre Either \ref run() or \ref start() must be called before
855 855
    ///using this function.
856 856
    Arc predArc(Node v) const { return (*_pred)[v]; }
857 857

	
858 858
    ///Returns the 'previous node' of the shortest path tree for a node.
859 859

	
860 860
    ///This function returns the 'previous node' of the shortest path
861 861
    ///tree for the node \c v, i.e. it returns the last but one node
862 862
    ///from a shortest path from the root(s) to \c v. It is \c INVALID
863 863
    ///if \c v is not reachable from the root(s) or if \c v is a root.
864 864
    ///
865 865
    ///The shortest path tree used here is equal to the shortest path
866 866
    ///tree used in \ref predArc().
867 867
    ///
868 868
    ///\pre Either \ref run() or \ref start() must be called before
869 869
    ///using this function.
870 870
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
871 871
                                  G->source((*_pred)[v]); }
872 872

	
873 873
    ///\brief Returns a const reference to the node map that stores the
874 874
    ///distances of the nodes.
875 875
    ///
876 876
    ///Returns a const reference to the node map that stores the distances
877 877
    ///of the nodes calculated by the algorithm.
878 878
    ///
879 879
    ///\pre Either \ref run() or \ref init()
880 880
    ///must be called before using this function.
881 881
    const DistMap &distMap() const { return *_dist;}
882 882

	
883 883
    ///\brief Returns a const reference to the node map that stores the
884 884
    ///predecessor arcs.
885 885
    ///
886 886
    ///Returns a const reference to the node map that stores the predecessor
887 887
    ///arcs, which form the shortest path tree.
888 888
    ///
889 889
    ///\pre Either \ref run() or \ref init()
890 890
    ///must be called before using this function.
891 891
    const PredMap &predMap() const { return *_pred;}
892 892

	
893 893
    ///Checks if a node is reachable from the root(s).
894 894

	
895 895
    ///Returns \c true if \c v is reachable from the root(s).
896 896
    ///\pre Either \ref run() or \ref start()
897 897
    ///must be called before using this function.
898 898
    bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
899 899
                                        Heap::PRE_HEAP; }
900 900

	
901 901
    ///Checks if a node is processed.
902 902

	
903 903
    ///Returns \c true if \c v is processed, i.e. the shortest
904 904
    ///path to \c v has already found.
905 905
    ///\pre Either \ref run() or \ref init()
906 906
    ///must be called before using this function.
907 907
    bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
908 908
                                          Heap::POST_HEAP; }
909 909

	
910 910
    ///The current distance of a node from the root(s).
911 911

	
912 912
    ///Returns the current distance of a node from the root(s).
913 913
    ///It may be decreased in the following processes.
914 914
    ///\pre Either \ref run() or \ref init()
915 915
    ///must be called before using this function and
916 916
    ///node \c v must be reached but not necessarily processed.
917 917
    Value currentDist(Node v) const {
918 918
      return processed(v) ? (*_dist)[v] : (*_heap)[v];
919 919
    }
920 920

	
921 921
    ///@}
922 922
  };
923 923

	
924 924

	
925 925
  ///Default traits class of dijkstra() function.
926 926

	
927 927
  ///Default traits class of dijkstra() function.
928 928
  ///\tparam GR The type of the digraph.
929 929
  ///\tparam LM The type of the length map.
930 930
  template<class GR, class LM>
931 931
  struct DijkstraWizardDefaultTraits
932 932
  {
933 933
    ///The type of the digraph the algorithm runs on.
934 934
    typedef GR Digraph;
935 935
    ///The type of the map that stores the arc lengths.
936 936

	
937 937
    ///The type of the map that stores the arc lengths.
938 938
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
939 939
    typedef LM LengthMap;
940 940
    ///The type of the length of the arcs.
941 941
    typedef typename LM::Value Value;
942 942

	
943 943
    /// Operation traits for Dijkstra algorithm.
944 944

	
945 945
    /// This class defines the operations that are used in the algorithm.
946 946
    /// \see DijkstraDefaultOperationTraits
947 947
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
948 948

	
949 949
    /// The cross reference type used by the heap.
950 950

	
951 951
    /// The cross reference type used by the heap.
952 952
    /// Usually it is \c Digraph::NodeMap<int>.
953 953
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
954 954
    ///Instantiates a \ref HeapCrossRef.
955 955

	
956 956
    ///This function instantiates a \ref HeapCrossRef.
957 957
    /// \param g is the digraph, to which we would like to define the
958 958
    /// HeapCrossRef.
959 959
    static HeapCrossRef *createHeapCrossRef(const Digraph &g)
960 960
    {
961 961
      return new HeapCrossRef(g);
962 962
    }
963 963

	
964 964
    ///The heap type used by the Dijkstra algorithm.
965 965

	
966 966
    ///The heap type used by the Dijkstra algorithm.
967 967
    ///
968 968
    ///\sa BinHeap
969 969
    ///\sa Dijkstra
970 970
    typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
971 971
                    std::less<Value> > Heap;
972 972

	
973 973
    ///Instantiates a \ref Heap.
974 974

	
975 975
    ///This function instantiates a \ref Heap.
976 976
    /// \param r is the HeapCrossRef which is used.
977 977
    static Heap *createHeap(HeapCrossRef& r)
978 978
    {
979 979
      return new Heap(r);
980 980
    }
981 981

	
982 982
    ///\brief The type of the map that stores the predecessor
983 983
    ///arcs of the shortest paths.
984 984
    ///
985 985
    ///The type of the map that stores the predecessor
986 986
    ///arcs of the shortest paths.
987 987
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
988 988
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
989 989
    ///Instantiates a PredMap.
990 990

	
991 991
    ///This function instantiates a PredMap.
992 992
    ///\param g is the digraph, to which we would like to define the
993 993
    ///PredMap.
994 994
    static PredMap *createPredMap(const Digraph &g)
995 995
    {
996 996
      return new PredMap(g);
997 997
    }
998 998

	
999 999
    ///The type of the map that indicates which nodes are processed.
1000 1000

	
1001 1001
    ///The type of the map that indicates which nodes are processed.
1002 1002
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1003 1003
    ///By default it is a NullMap.
1004 1004
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
1005 1005
    ///Instantiates a ProcessedMap.
1006 1006

	
1007 1007
    ///This function instantiates a ProcessedMap.
1008 1008
    ///\param g is the digraph, to which
1009 1009
    ///we would like to define the ProcessedMap.
1010 1010
#ifdef DOXYGEN
1011 1011
    static ProcessedMap *createProcessedMap(const Digraph &g)
1012 1012
#else
1013 1013
    static ProcessedMap *createProcessedMap(const Digraph &)
1014 1014
#endif
1015 1015
    {
1016 1016
      return new ProcessedMap();
1017 1017
    }
1018 1018

	
1019 1019
    ///The type of the map that stores the distances of the nodes.
1020 1020

	
1021 1021
    ///The type of the map that stores the distances of the nodes.
1022 1022
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1023 1023
    typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
1024 1024
    ///Instantiates a DistMap.
1025 1025

	
1026 1026
    ///This function instantiates a DistMap.
1027 1027
    ///\param g is the digraph, to which we would like to define
1028 1028
    ///the DistMap
1029 1029
    static DistMap *createDistMap(const Digraph &g)
1030 1030
    {
1031 1031
      return new DistMap(g);
1032 1032
    }
1033 1033

	
1034 1034
    ///The type of the shortest paths.
1035 1035

	
1036 1036
    ///The type of the shortest paths.
1037 1037
    ///It must meet the \ref concepts::Path "Path" concept.
1038 1038
    typedef lemon::Path<Digraph> Path;
1039 1039
  };
1040 1040

	
1041
  /// Default traits class used by \ref DijkstraWizard
1041
  /// Default traits class used by DijkstraWizard
1042 1042

	
1043 1043
  /// To make it easier to use Dijkstra algorithm
1044 1044
  /// we have created a wizard class.
1045 1045
  /// This \ref DijkstraWizard class needs default traits,
1046 1046
  /// as well as the \ref Dijkstra class.
1047 1047
  /// The \ref DijkstraWizardBase is a class to be the default traits of the
1048 1048
  /// \ref DijkstraWizard class.
1049 1049
  template<class GR,class LM>
1050 1050
  class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
1051 1051
  {
1052 1052
    typedef DijkstraWizardDefaultTraits<GR,LM> Base;
1053 1053
  protected:
1054 1054
    //The type of the nodes in the digraph.
1055 1055
    typedef typename Base::Digraph::Node Node;
1056 1056

	
1057 1057
    //Pointer to the digraph the algorithm runs on.
1058 1058
    void *_g;
1059 1059
    //Pointer to the length map.
1060 1060
    void *_length;
1061 1061
    //Pointer to the map of processed nodes.
1062 1062
    void *_processed;
1063 1063
    //Pointer to the map of predecessors arcs.
1064 1064
    void *_pred;
1065 1065
    //Pointer to the map of distances.
1066 1066
    void *_dist;
1067 1067
    //Pointer to the shortest path to the target node.
1068 1068
    void *_path;
1069 1069
    //Pointer to the distance of the target node.
1070 1070
    void *_di;
1071 1071

	
1072 1072
  public:
1073 1073
    /// Constructor.
1074 1074

	
1075 1075
    /// This constructor does not require parameters, therefore it initiates
1076 1076
    /// all of the attributes to \c 0.
1077 1077
    DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0),
1078 1078
                           _dist(0), _path(0), _di(0) {}
1079 1079

	
1080 1080
    /// Constructor.
1081 1081

	
1082 1082
    /// This constructor requires two parameters,
1083 1083
    /// others are initiated to \c 0.
1084 1084
    /// \param g The digraph the algorithm runs on.
1085 1085
    /// \param l The length map.
1086 1086
    DijkstraWizardBase(const GR &g,const LM &l) :
1087 1087
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1088 1088
      _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1089 1089
      _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
1090 1090

	
1091 1091
  };
1092 1092

	
1093 1093
  /// Auxiliary class for the function-type interface of Dijkstra algorithm.
1094 1094

	
1095 1095
  /// This auxiliary class is created to implement the
1096 1096
  /// \ref dijkstra() "function-type interface" of \ref Dijkstra algorithm.
1097 1097
  /// It does not have own \ref run() method, it uses the functions
1098 1098
  /// and features of the plain \ref Dijkstra.
1099 1099
  ///
1100 1100
  /// This class should only be used through the \ref dijkstra() function,
1101 1101
  /// which makes it easier to use the algorithm.
1102 1102
  template<class TR>
1103 1103
  class DijkstraWizard : public TR
1104 1104
  {
1105 1105
    typedef TR Base;
1106 1106

	
1107 1107
    ///The type of the digraph the algorithm runs on.
1108 1108
    typedef typename TR::Digraph Digraph;
1109 1109

	
1110 1110
    typedef typename Digraph::Node Node;
1111 1111
    typedef typename Digraph::NodeIt NodeIt;
1112 1112
    typedef typename Digraph::Arc Arc;
1113 1113
    typedef typename Digraph::OutArcIt OutArcIt;
1114 1114

	
1115 1115
    ///The type of the map that stores the arc lengths.
1116 1116
    typedef typename TR::LengthMap LengthMap;
1117 1117
    ///The type of the length of the arcs.
1118 1118
    typedef typename LengthMap::Value Value;
1119 1119
    ///\brief The type of the map that stores the predecessor
1120 1120
    ///arcs of the shortest paths.
1121 1121
    typedef typename TR::PredMap PredMap;
1122 1122
    ///The type of the map that stores the distances of the nodes.
1123 1123
    typedef typename TR::DistMap DistMap;
1124 1124
    ///The type of the map that indicates which nodes are processed.
1125 1125
    typedef typename TR::ProcessedMap ProcessedMap;
1126 1126
    ///The type of the shortest paths
1127 1127
    typedef typename TR::Path Path;
1128 1128
    ///The heap type used by the dijkstra algorithm.
1129 1129
    typedef typename TR::Heap Heap;
1130 1130

	
1131 1131
  public:
1132 1132

	
1133 1133
    /// Constructor.
1134 1134
    DijkstraWizard() : TR() {}
1135 1135

	
1136 1136
    /// Constructor that requires parameters.
1137 1137

	
1138 1138
    /// Constructor that requires parameters.
1139 1139
    /// These parameters will be the default values for the traits class.
1140 1140
    /// \param g The digraph the algorithm runs on.
1141 1141
    /// \param l The length map.
1142 1142
    DijkstraWizard(const Digraph &g, const LengthMap &l) :
1143 1143
      TR(g,l) {}
1144 1144

	
1145 1145
    ///Copy constructor
1146 1146
    DijkstraWizard(const TR &b) : TR(b) {}
1147 1147

	
1148 1148
    ~DijkstraWizard() {}
1149 1149

	
1150 1150
    ///Runs Dijkstra algorithm from the given source node.
1151 1151

	
1152 1152
    ///This method runs %Dijkstra algorithm from the given source node
1153 1153
    ///in order to compute the shortest path to each node.
1154 1154
    void run(Node s)
1155 1155
    {
1156 1156
      Dijkstra<Digraph,LengthMap,TR>
1157 1157
        dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1158 1158
             *reinterpret_cast<const LengthMap*>(Base::_length));
1159 1159
      if (Base::_pred)
1160 1160
        dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1161 1161
      if (Base::_dist)
1162 1162
        dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1163 1163
      if (Base::_processed)
1164 1164
        dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1165 1165
      dijk.run(s);
1166 1166
    }
1167 1167

	
1168 1168
    ///Finds the shortest path between \c s and \c t.
1169 1169

	
1170 1170
    ///This method runs the %Dijkstra algorithm from node \c s
1171 1171
    ///in order to compute the shortest path to node \c t
1172 1172
    ///(it stops searching when \c t is processed).
1173 1173
    ///
1174 1174
    ///\return \c true if \c t is reachable form \c s.
1175 1175
    bool run(Node s, Node t)
1176 1176
    {
1177 1177
      Dijkstra<Digraph,LengthMap,TR>
1178 1178
        dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1179 1179
             *reinterpret_cast<const LengthMap*>(Base::_length));
1180 1180
      if (Base::_pred)
1181 1181
        dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1182 1182
      if (Base::_dist)
1183 1183
        dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1184 1184
      if (Base::_processed)
1185 1185
        dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1186 1186
      dijk.run(s,t);
1187 1187
      if (Base::_path)
1188 1188
        *reinterpret_cast<Path*>(Base::_path) = dijk.path(t);
1189 1189
      if (Base::_di)
1190 1190
        *reinterpret_cast<Value*>(Base::_di) = dijk.dist(t);
1191 1191
      return dijk.reached(t);
1192 1192
    }
1193 1193

	
1194 1194
    template<class T>
1195 1195
    struct SetPredMapBase : public Base {
1196 1196
      typedef T PredMap;
1197 1197
      static PredMap *createPredMap(const Digraph &) { return 0; };
1198 1198
      SetPredMapBase(const TR &b) : TR(b) {}
1199 1199
    };
1200 1200
    ///\brief \ref named-func-param "Named parameter"
1201 1201
    ///for setting PredMap object.
1202 1202
    ///
1203 1203
    ///\ref named-func-param "Named parameter"
1204 1204
    ///for setting PredMap object.
1205 1205
    template<class T>
1206 1206
    DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1207 1207
    {
1208 1208
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1209 1209
      return DijkstraWizard<SetPredMapBase<T> >(*this);
1210 1210
    }
1211 1211

	
1212 1212
    template<class T>
1213 1213
    struct SetDistMapBase : public Base {
1214 1214
      typedef T DistMap;
1215 1215
      static DistMap *createDistMap(const Digraph &) { return 0; };
1216 1216
      SetDistMapBase(const TR &b) : TR(b) {}
1217 1217
    };
1218 1218
    ///\brief \ref named-func-param "Named parameter"
1219 1219
    ///for setting DistMap object.
1220 1220
    ///
1221 1221
    ///\ref named-func-param "Named parameter"
1222 1222
    ///for setting DistMap object.
1223 1223
    template<class T>
1224 1224
    DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1225 1225
    {
1226 1226
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1227 1227
      return DijkstraWizard<SetDistMapBase<T> >(*this);
1228 1228
    }
1229 1229

	
1230 1230
    template<class T>
1231 1231
    struct SetProcessedMapBase : public Base {
1232 1232
      typedef T ProcessedMap;
1233 1233
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1234 1234
      SetProcessedMapBase(const TR &b) : TR(b) {}
1235 1235
    };
1236 1236
    ///\brief \ref named-func-param "Named parameter"
1237 1237
    ///for setting ProcessedMap object.
1238 1238
    ///
1239 1239
    /// \ref named-func-param "Named parameter"
1240 1240
    ///for setting ProcessedMap object.
1241 1241
    template<class T>
1242 1242
    DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1243 1243
    {
1244 1244
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1245 1245
      return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1246 1246
    }
1247 1247

	
1248 1248
    template<class T>
1249 1249
    struct SetPathBase : public Base {
1250 1250
      typedef T Path;
1251 1251
      SetPathBase(const TR &b) : TR(b) {}
1252 1252
    };
1253 1253
    ///\brief \ref named-func-param "Named parameter"
1254 1254
    ///for getting the shortest path to the target node.
1255 1255
    ///
1256 1256
    ///\ref named-func-param "Named parameter"
1257 1257
    ///for getting the shortest path to the target node.
1258 1258
    template<class T>
1259 1259
    DijkstraWizard<SetPathBase<T> > path(const T &t)
1260 1260
    {
1261 1261
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1262 1262
      return DijkstraWizard<SetPathBase<T> >(*this);
1263 1263
    }
1264 1264

	
1265 1265
    ///\brief \ref named-func-param "Named parameter"
1266 1266
    ///for getting the distance of the target node.
1267 1267
    ///
1268 1268
    ///\ref named-func-param "Named parameter"
1269 1269
    ///for getting the distance of the target node.
1270 1270
    DijkstraWizard dist(const Value &d)
1271 1271
    {
1272 1272
      Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1273 1273
      return *this;
1274 1274
    }
1275 1275

	
1276 1276
  };
1277 1277

	
1278 1278
  ///Function-type interface for Dijkstra algorithm.
1279 1279

	
1280 1280
  /// \ingroup shortest_path
1281 1281
  ///Function-type interface for Dijkstra algorithm.
1282 1282
  ///
1283 1283
  ///This function also has several \ref named-func-param "named parameters",
1284 1284
  ///they are declared as the members of class \ref DijkstraWizard.
1285 1285
  ///The following examples show how to use these parameters.
1286 1286
  ///\code
1287 1287
  ///  // Compute shortest path from node s to each node
1288 1288
  ///  dijkstra(g,length).predMap(preds).distMap(dists).run(s);
1289 1289
  ///
1290 1290
  ///  // Compute shortest path from s to t
1291 1291
  ///  bool reached = dijkstra(g,length).path(p).dist(d).run(s,t);
1292 1292
  ///\endcode
1293 1293
  ///\warning Don't forget to put the \ref DijkstraWizard::run() "run()"
1294 1294
  ///to the end of the parameter list.
1295 1295
  ///\sa DijkstraWizard
1296 1296
  ///\sa Dijkstra
1297 1297
  template<class GR, class LM>
1298 1298
  DijkstraWizard<DijkstraWizardBase<GR,LM> >
1299 1299
  dijkstra(const GR &digraph, const LM &length)
1300 1300
  {
1301 1301
    return DijkstraWizard<DijkstraWizardBase<GR,LM> >(digraph,length);
1302 1302
  }
1303 1303

	
1304 1304
} //END OF NAMESPACE LEMON
1305 1305

	
1306 1306
#endif

Changeset was too big and was cut off... Show full diff

0 comments (0 inline)