↑ 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
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_CORE_H
20 20
#define LEMON_CORE_H
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 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_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
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_DIM2_H
20 20
#define LEMON_DIM2_H
21 21

	
22 22
#include <iostream>
23 23

	
24 24
///\ingroup misc
25 25
///\file
26 26
///\brief A simple two dimensional vector and a bounding box implementation
27 27
///
28 28
/// The class \ref lemon::dim2::Point "dim2::Point" implements
29 29
/// a two dimensional vector with the usual operations.
30 30
///
31 31
/// The class \ref lemon::dim2::Box "dim2::Box" can be used to determine
32 32
/// the rectangular bounding box of a set of
33 33
/// \ref lemon::dim2::Point "dim2::Point"'s.
34 34

	
35 35
namespace lemon {
36 36

	
37 37
  ///Tools for handling two dimensional coordinates
38 38

	
39 39
  ///This namespace is a storage of several
40 40
  ///tools for handling two dimensional coordinates
41 41
  namespace dim2 {
42 42

	
43 43
  /// \addtogroup misc
44 44
  /// @{
45 45

	
46 46
  /// Two dimensional vector (plain vector)
47 47

	
48 48
  /// A simple two dimensional vector (plain vector) implementation
49 49
  /// with the usual vector operations.
50 50
  template<typename T>
51 51
    class Point {
52 52

	
53 53
    public:
54 54

	
55 55
      typedef T Value;
56 56

	
57 57
      ///First coordinate
58 58
      T x;
59 59
      ///Second coordinate
60 60
      T y;
61 61

	
62 62
      ///Default constructor
63 63
      Point() {}
64 64

	
65 65
      ///Construct an instance from coordinates
66 66
      Point(T a, T b) : x(a), y(b) { }
67 67

	
68 68
      ///Returns the dimension of the vector (i.e. returns 2).
69 69

	
70 70
      ///The dimension of the vector.
71 71
      ///This function always returns 2.
72 72
      int size() const { return 2; }
73 73

	
74 74
      ///Subscripting operator
75 75

	
76 76
      ///\c p[0] is \c p.x and \c p[1] is \c p.y
77 77
      ///
78 78
      T& operator[](int idx) { return idx == 0 ? x : y; }
79 79

	
80 80
      ///Const subscripting operator
81 81

	
82 82
      ///\c p[0] is \c p.x and \c p[1] is \c p.y
83 83
      ///
84 84
      const T& operator[](int idx) const { return idx == 0 ? x : y; }
85 85

	
86 86
      ///Conversion constructor
87 87
      template<class TT> Point(const Point<TT> &p) : x(p.x), y(p.y) {}
88 88

	
89 89
      ///Give back the square of the norm of the vector
90 90
      T normSquare() const {
91 91
        return x*x+y*y;
92 92
      }
93 93

	
94 94
      ///Increment the left hand side by \c u
95 95
      Point<T>& operator +=(const Point<T>& u) {
96 96
        x += u.x;
97 97
        y += u.y;
98 98
        return *this;
99 99
      }
100 100

	
101 101
      ///Decrement the left hand side by \c u
102 102
      Point<T>& operator -=(const Point<T>& u) {
103 103
        x -= u.x;
104 104
        y -= u.y;
105 105
        return *this;
106 106
      }
107 107

	
108 108
      ///Multiply the left hand side with a scalar
109 109
      Point<T>& operator *=(const T &u) {
110 110
        x *= u;
111 111
        y *= u;
112 112
        return *this;
113 113
      }
114 114

	
115 115
      ///Divide the left hand side by a scalar
116 116
      Point<T>& operator /=(const T &u) {
117 117
        x /= u;
118 118
        y /= u;
119 119
        return *this;
120 120
      }
121 121

	
122 122
      ///Return the scalar product of two vectors
123 123
      T operator *(const Point<T>& u) const {
124 124
        return x*u.x+y*u.y;
125 125
      }
126 126

	
127 127
      ///Return the sum of two vectors
128 128
      Point<T> operator+(const Point<T> &u) const {
129 129
        Point<T> b=*this;
130 130
        return b+=u;
131 131
      }
132 132

	
133 133
      ///Return the negative of the vector
134 134
      Point<T> operator-() const {
135 135
        Point<T> b=*this;
136 136
        b.x=-b.x; b.y=-b.y;
137 137
        return b;
138 138
      }
139 139

	
140 140
      ///Return the difference of two vectors
141 141
      Point<T> operator-(const Point<T> &u) const {
142 142
        Point<T> b=*this;
143 143
        return b-=u;
144 144
      }
145 145

	
146 146
      ///Return a vector multiplied by a scalar
147 147
      Point<T> operator*(const T &u) const {
148 148
        Point<T> b=*this;
149 149
        return b*=u;
150 150
      }
151 151

	
152 152
      ///Return a vector divided by a scalar
153 153
      Point<T> operator/(const T &u) const {
154 154
        Point<T> b=*this;
155 155
        return b/=u;
156 156
      }
157 157

	
158 158
      ///Test equality
159 159
      bool operator==(const Point<T> &u) const {
160 160
        return (x==u.x) && (y==u.y);
161 161
      }
162 162

	
163 163
      ///Test inequality
164 164
      bool operator!=(Point u) const {
165 165
        return  (x!=u.x) || (y!=u.y);
166 166
      }
167 167

	
168 168
    };
169 169

	
170 170
  ///Return a Point
171 171

	
172 172
  ///Return a Point.
173 173
  ///\relates Point
174 174
  template <typename T>
175 175
  inline Point<T> makePoint(const T& x, const T& y) {
176 176
    return Point<T>(x, y);
177 177
  }
178 178

	
179 179
  ///Return a vector multiplied by a scalar
180 180

	
181 181
  ///Return a vector multiplied by a scalar.
182 182
  ///\relates Point
183 183
  template<typename T> Point<T> operator*(const T &u,const Point<T> &x) {
184 184
    return x*u;
185 185
  }
186 186

	
187 187
  ///Read a plain vector from a stream
188 188

	
189 189
  ///Read a plain vector from a stream.
190 190
  ///\relates Point
191 191
  ///
192 192
  template<typename T>
193 193
  inline std::istream& operator>>(std::istream &is, Point<T> &z) {
194 194
    char c;
195 195
    if (is >> c) {
196 196
      if (c != '(') is.putback(c);
197 197
    } else {
198 198
      is.clear();
199 199
    }
200 200
    if (!(is >> z.x)) return is;
201 201
    if (is >> c) {
202 202
      if (c != ',') is.putback(c);
203 203
    } else {
204 204
      is.clear();
205 205
    }
206 206
    if (!(is >> z.y)) return is;
207 207
    if (is >> c) {
208 208
      if (c != ')') is.putback(c);
209 209
    } else {
210 210
      is.clear();
211 211
    }
212 212
    return is;
213 213
  }
214 214

	
215 215
  ///Write a plain vector to a stream
216 216

	
217 217
  ///Write a plain vector to a stream.
218 218
  ///\relates Point
219 219
  ///
220 220
  template<typename T>
221 221
  inline std::ostream& operator<<(std::ostream &os, const Point<T>& z)
222 222
  {
223 223
    os << "(" << z.x << "," << z.y << ")";
224 224
    return os;
225 225
  }
226 226

	
227 227
  ///Rotate by 90 degrees
228 228

	
229 229
  ///Returns the parameter rotated by 90 degrees in positive direction.
230 230
  ///\relates Point
231 231
  ///
232 232
  template<typename T>
233 233
  inline Point<T> rot90(const Point<T> &z)
234 234
  {
235 235
    return Point<T>(-z.y,z.x);
236 236
  }
237 237

	
238 238
  ///Rotate by 180 degrees
239 239

	
240 240
  ///Returns the parameter rotated by 180 degrees.
241 241
  ///\relates Point
242 242
  ///
243 243
  template<typename T>
244 244
  inline Point<T> rot180(const Point<T> &z)
245 245
  {
246 246
    return Point<T>(-z.x,-z.y);
247 247
  }
248 248

	
249 249
  ///Rotate by 270 degrees
250 250

	
251 251
  ///Returns the parameter rotated by 90 degrees in negative direction.
252 252
  ///\relates Point
253 253
  ///
254 254
  template<typename T>
255 255
  inline Point<T> rot270(const Point<T> &z)
256 256
  {
257 257
    return Point<T>(z.y,-z.x);
258 258
  }
259 259

	
260 260

	
261 261

	
262
  /// Bounding box of plain vectors (\ref Point points).
262
  /// Bounding box of plain vectors (points).
263 263

	
264 264
  /// A class to calculate or store the bounding box of plain vectors
265
  /// (\ref Point points).
265
  /// (\ref Point "points").
266 266
  template<typename T>
267 267
  class Box {
268 268
      Point<T> _bottom_left, _top_right;
269 269
      bool _empty;
270 270
    public:
271 271

	
272 272
      ///Default constructor: creates an empty box
273 273
      Box() { _empty = true; }
274 274

	
275 275
      ///Construct a box from one point
276 276
      Box(Point<T> a) {
277 277
        _bottom_left = _top_right = a;
278 278
        _empty = false;
279 279
      }
280 280

	
281 281
      ///Construct a box from two points
282 282

	
283 283
      ///Construct a box from two points.
284 284
      ///\param a The bottom left corner.
285 285
      ///\param b The top right corner.
286 286
      ///\warning The coordinates of the bottom left corner must be no more
287 287
      ///than those of the top right one.
288 288
      Box(Point<T> a,Point<T> b)
289 289
      {
290 290
        _bottom_left = a;
291 291
        _top_right = b;
292 292
        _empty = false;
293 293
      }
294 294

	
295 295
      ///Construct a box from four numbers
296 296

	
297 297
      ///Construct a box from four numbers.
298 298
      ///\param l The left side of the box.
299 299
      ///\param b The bottom of the box.
300 300
      ///\param r The right side of the box.
301 301
      ///\param t The top of the box.
302 302
      ///\warning The left side must be no more than the right side and
303 303
      ///bottom must be no more than the top.
304 304
      Box(T l,T b,T r,T t)
305 305
      {
306 306
        _bottom_left=Point<T>(l,b);
307 307
        _top_right=Point<T>(r,t);
308 308
        _empty = false;
309 309
      }
310 310

	
311 311
      ///Return \c true if the box is empty.
312 312

	
313 313
      ///Return \c true if the box is empty (i.e. return \c false
314 314
      ///if at least one point was added to the box or the coordinates of
315 315
      ///the box were set).
316 316
      ///
317 317
      ///The coordinates of an empty box are not defined.
318 318
      bool empty() const {
319 319
        return _empty;
320 320
      }
321 321

	
322 322
      ///Make the box empty
323 323
      void clear() {
324 324
        _empty = true;
325 325
      }
326 326

	
327 327
      ///Give back the bottom left corner of the box
328 328

	
329 329
      ///Give back the bottom left corner of the box.
330 330
      ///If the box is empty, then the return value is not defined.
331 331
      Point<T> bottomLeft() const {
332 332
        return _bottom_left;
333 333
      }
334 334

	
335 335
      ///Set the bottom left corner of the box
336 336

	
337 337
      ///Set the bottom left corner of the box.
338 338
      ///\pre The box must not be empty.
339 339
      void bottomLeft(Point<T> p) {
340 340
        _bottom_left = p;
341 341
      }
342 342

	
343 343
      ///Give back the top right corner of the box
344 344

	
345 345
      ///Give back the top right corner of the box.
346 346
      ///If the box is empty, then the return value is not defined.
347 347
      Point<T> topRight() const {
348 348
        return _top_right;
349 349
      }
350 350

	
351 351
      ///Set the top right corner of the box
352 352

	
353 353
      ///Set the top right corner of the box.
354 354
      ///\pre The box must not be empty.
355 355
      void topRight(Point<T> p) {
356 356
        _top_right = p;
357 357
      }
358 358

	
359 359
      ///Give back the bottom right corner of the box
360 360

	
361 361
      ///Give back the bottom right corner of the box.
362 362
      ///If the box is empty, then the return value is not defined.
363 363
      Point<T> bottomRight() const {
364 364
        return Point<T>(_top_right.x,_bottom_left.y);
365 365
      }
366 366

	
367 367
      ///Set the bottom right corner of the box
368 368

	
369 369
      ///Set the bottom right corner of the box.
370 370
      ///\pre The box must not be empty.
371 371
      void bottomRight(Point<T> p) {
372 372
        _top_right.x = p.x;
373 373
        _bottom_left.y = p.y;
374 374
      }
375 375

	
376 376
      ///Give back the top left corner of the box
377 377

	
378 378
      ///Give back the top left corner of the box.
379 379
      ///If the box is empty, then the return value is not defined.
380 380
      Point<T> topLeft() const {
381 381
        return Point<T>(_bottom_left.x,_top_right.y);
382 382
      }
383 383

	
384 384
      ///Set the top left corner of the box
385 385

	
386 386
      ///Set the top left corner of the box.
387 387
      ///\pre The box must not be empty.
388 388
      void topLeft(Point<T> p) {
389 389
        _top_right.y = p.y;
390 390
        _bottom_left.x = p.x;
391 391
      }
392 392

	
393 393
      ///Give back the bottom of the box
394 394

	
395 395
      ///Give back the bottom of the box.
396 396
      ///If the box is empty, then the return value is not defined.
397 397
      T bottom() const {
398 398
        return _bottom_left.y;
399 399
      }
400 400

	
401 401
      ///Set the bottom of the box
402 402

	
403 403
      ///Set the bottom of the box.
404 404
      ///\pre The box must not be empty.
405 405
      void bottom(T t) {
406 406
        _bottom_left.y = t;
407 407
      }
408 408

	
409 409
      ///Give back the top of the box
410 410

	
411 411
      ///Give back the top of the box.
412 412
      ///If the box is empty, then the return value is not defined.
413 413
      T top() const {
414 414
        return _top_right.y;
415 415
      }
416 416

	
417 417
      ///Set the top of the box
418 418

	
419 419
      ///Set the top of the box.
420 420
      ///\pre The box must not be empty.
421 421
      void top(T t) {
422 422
        _top_right.y = t;
423 423
      }
424 424

	
425 425
      ///Give back the left side of the box
426 426

	
427 427
      ///Give back the left side of the box.
428 428
      ///If the box is empty, then the return value is not defined.
429 429
      T left() const {
430 430
        return _bottom_left.x;
431 431
      }
432 432

	
433 433
      ///Set the left side of the box
434 434

	
435 435
      ///Set the left side of the box.
436 436
      ///\pre The box must not be empty.
437 437
      void left(T t) {
438 438
        _bottom_left.x = t;
439 439
      }
440 440

	
441 441
      /// Give back the right side of the box
442 442

	
443 443
      /// Give back the right side of the box.
444 444
      ///If the box is empty, then the return value is not defined.
445 445
      T right() const {
446 446
        return _top_right.x;
447 447
      }
448 448

	
449 449
      ///Set the right side of the box
450 450

	
451 451
      ///Set the right side of the box.
452 452
      ///\pre The box must not be empty.
453 453
      void right(T t) {
454 454
        _top_right.x = t;
455 455
      }
456 456

	
457 457
      ///Give back the height of the box
458 458

	
459 459
      ///Give back the height of the box.
460 460
      ///If the box is empty, then the return value is not defined.
461 461
      T height() const {
462 462
        return _top_right.y-_bottom_left.y;
463 463
      }
464 464

	
465 465
      ///Give back the width of the box
466 466

	
467 467
      ///Give back the width of the box.
468 468
      ///If the box is empty, then the return value is not defined.
469 469
      T width() const {
470 470
        return _top_right.x-_bottom_left.x;
471 471
      }
472 472

	
473 473
      ///Checks whether a point is inside the box
474 474
      bool inside(const Point<T>& u) const {
475 475
        if (_empty)
476 476
          return false;
477 477
        else {
478 478
          return ( (u.x-_bottom_left.x)*(_top_right.x-u.x) >= 0 &&
479 479
                   (u.y-_bottom_left.y)*(_top_right.y-u.y) >= 0 );
480 480
        }
481 481
      }
482 482

	
483 483
      ///Increments the box with a point
484 484

	
485 485
      ///Increments the box with a point.
486 486
      ///
487 487
      Box& add(const Point<T>& u){
488 488
        if (_empty) {
489 489
          _bottom_left = _top_right = u;
490 490
          _empty = false;
491 491
        }
492 492
        else {
493 493
          if (_bottom_left.x > u.x) _bottom_left.x = u.x;
494 494
          if (_bottom_left.y > u.y) _bottom_left.y = u.y;
495 495
          if (_top_right.x < u.x) _top_right.x = u.x;
496 496
          if (_top_right.y < u.y) _top_right.y = u.y;
497 497
        }
498 498
        return *this;
499 499
      }
500 500

	
501 501
      ///Increments the box to contain another box
502 502

	
503 503
      ///Increments the box to contain another box.
504 504
      ///
505 505
      Box& add(const Box &u){
506 506
        if ( !u.empty() ){
507 507
          add(u._bottom_left);
508 508
          add(u._top_right);
509 509
        }
510 510
        return *this;
511 511
      }
512 512

	
513 513
      ///Intersection of two boxes
514 514

	
515 515
      ///Intersection of two boxes.
516 516
      ///
517 517
      Box operator&(const Box& u) const {
518 518
        Box b;
519 519
        if (_empty || u._empty) {
520 520
          b._empty = true;
521 521
        } else {
522 522
          b._bottom_left.x = std::max(_bottom_left.x, u._bottom_left.x);
523 523
          b._bottom_left.y = std::max(_bottom_left.y, u._bottom_left.y);
524 524
          b._top_right.x = std::min(_top_right.x, u._top_right.x);
525 525
          b._top_right.y = std::min(_top_right.y, u._top_right.y);
526 526
          b._empty = b._bottom_left.x > b._top_right.x ||
527 527
                     b._bottom_left.y > b._top_right.y;
528 528
        }
529 529
        return b;
530 530
      }
531 531

	
532 532
  };//class Box
533 533

	
534 534

	
535 535
  ///Read a box from a stream
536 536

	
537 537
  ///Read a box from a stream.
538 538
  ///\relates Box
539 539
  template<typename T>
540 540
  inline std::istream& operator>>(std::istream &is, Box<T>& b) {
541 541
    char c;
542 542
    Point<T> p;
543 543
    if (is >> c) {
544 544
      if (c != '(') is.putback(c);
545 545
    } else {
546 546
      is.clear();
547 547
    }
548 548
    if (!(is >> p)) return is;
549 549
    b.bottomLeft(p);
550 550
    if (is >> c) {
551 551
      if (c != ',') is.putback(c);
552 552
    } else {
553 553
      is.clear();
554 554
    }
555 555
    if (!(is >> p)) return is;
556 556
    b.topRight(p);
557 557
    if (is >> c) {
558 558
      if (c != ')') is.putback(c);
559 559
    } else {
560 560
      is.clear();
561 561
    }
562 562
    return is;
563 563
  }
564 564

	
565 565
  ///Write a box to a stream
566 566

	
567 567
  ///Write a box to a stream.
568 568
  ///\relates Box
569 569
  template<typename T>
570 570
  inline std::ostream& operator<<(std::ostream &os, const Box<T>& b)
571 571
  {
572 572
    os << "(" << b.bottomLeft() << "," << b.topRight() << ")";
573 573
    return os;
574 574
  }
575 575

	
576
  ///Map of x-coordinates of a \ref Point "Point"-map
576
  ///Map of x-coordinates of a <tt>Point</tt>-map
577 577

	
578
  ///Map of x-coordinates of a \ref Point "Point"-map.
578 579
  ///\ingroup maps
579
  ///Map of x-coordinates of a \ref Point "Point"-map.
580
  ///
581 580
  template<class M>
582 581
  class XMap
583 582
  {
584 583
    M& _map;
585 584
  public:
586 585

	
587 586
    typedef typename M::Value::Value Value;
588 587
    typedef typename M::Key Key;
589 588
    ///\e
590 589
    XMap(M& map) : _map(map) {}
591 590
    Value operator[](Key k) const {return _map[k].x;}
592 591
    void set(Key k,Value v) {_map.set(k,typename M::Value(v,_map[k].y));}
593 592
  };
594 593

	
595
  ///Returns an \ref XMap class
594
  ///Returns an XMap class
596 595

	
597
  ///This function just returns an \ref XMap class.
596
  ///This function just returns an XMap class.
598 597
  ///
599 598
  ///\ingroup maps
600 599
  ///\relates XMap
601 600
  template<class M>
602 601
  inline XMap<M> xMap(M &m)
603 602
  {
604 603
    return XMap<M>(m);
605 604
  }
606 605

	
607 606
  template<class M>
608 607
  inline XMap<M> xMap(const M &m)
609 608
  {
610 609
    return XMap<M>(m);
611 610
  }
612 611

	
613
  ///Constant (read only) version of \ref XMap
612
  ///Constant (read only) version of XMap
614 613

	
614
  ///Constant (read only) version of XMap.
615 615
  ///\ingroup maps
616
  ///Constant (read only) version of \ref XMap
617
  ///
618 616
  template<class M>
619 617
  class ConstXMap
620 618
  {
621 619
    const M& _map;
622 620
  public:
623 621

	
624 622
    typedef typename M::Value::Value Value;
625 623
    typedef typename M::Key Key;
626 624
    ///\e
627 625
    ConstXMap(const M &map) : _map(map) {}
628 626
    Value operator[](Key k) const {return _map[k].x;}
629 627
  };
630 628

	
631
  ///Returns a \ref ConstXMap class
629
  ///Returns a ConstXMap class
632 630

	
633
  ///This function just returns a \ref ConstXMap class.
631
  ///This function just returns a ConstXMap class.
634 632
  ///
635 633
  ///\ingroup maps
636 634
  ///\relates ConstXMap
637 635
  template<class M>
638 636
  inline ConstXMap<M> xMap(const M &m)
639 637
  {
640 638
    return ConstXMap<M>(m);
641 639
  }
642 640

	
643
  ///Map of y-coordinates of a \ref Point "Point"-map
641
  ///Map of y-coordinates of a <tt>Point</tt>-map
644 642

	
643
  ///Map of y-coordinates of a \ref Point "Point"-map.
645 644
  ///\ingroup maps
646
  ///Map of y-coordinates of a \ref Point "Point"-map.
647
  ///
648 645
  template<class M>
649 646
  class YMap
650 647
  {
651 648
    M& _map;
652 649
  public:
653 650

	
654 651
    typedef typename M::Value::Value Value;
655 652
    typedef typename M::Key Key;
656 653
    ///\e
657 654
    YMap(M& map) : _map(map) {}
658 655
    Value operator[](Key k) const {return _map[k].y;}
659 656
    void set(Key k,Value v) {_map.set(k,typename M::Value(_map[k].x,v));}
660 657
  };
661 658

	
662
  ///Returns a \ref YMap class
659
  ///Returns a YMap class
663 660

	
664
  ///This function just returns a \ref YMap class.
661
  ///This function just returns a YMap class.
665 662
  ///
666 663
  ///\ingroup maps
667 664
  ///\relates YMap
668 665
  template<class M>
669 666
  inline YMap<M> yMap(M &m)
670 667
  {
671 668
    return YMap<M>(m);
672 669
  }
673 670

	
674 671
  template<class M>
675 672
  inline YMap<M> yMap(const M &m)
676 673
  {
677 674
    return YMap<M>(m);
678 675
  }
679 676

	
680
  ///Constant (read only) version of \ref YMap
677
  ///Constant (read only) version of YMap
681 678

	
679
  ///Constant (read only) version of YMap.
682 680
  ///\ingroup maps
683
  ///Constant (read only) version of \ref YMap
684
  ///
685 681
  template<class M>
686 682
  class ConstYMap
687 683
  {
688 684
    const M& _map;
689 685
  public:
690 686

	
691 687
    typedef typename M::Value::Value Value;
692 688
    typedef typename M::Key Key;
693 689
    ///\e
694 690
    ConstYMap(const M &map) : _map(map) {}
695 691
    Value operator[](Key k) const {return _map[k].y;}
696 692
  };
697 693

	
698
  ///Returns a \ref ConstYMap class
694
  ///Returns a ConstYMap class
699 695

	
700
  ///This function just returns a \ref ConstYMap class.
696
  ///This function just returns a ConstYMap class.
701 697
  ///
702 698
  ///\ingroup maps
703 699
  ///\relates ConstYMap
704 700
  template<class M>
705 701
  inline ConstYMap<M> yMap(const M &m)
706 702
  {
707 703
    return ConstYMap<M>(m);
708 704
  }
709 705

	
710 706

	
711
  ///\brief Map of the \ref Point::normSquare() "normSquare()"
712
  ///of a \ref Point "Point"-map
707
  ///\brief Map of the normSquare() of a <tt>Point</tt>-map
713 708
  ///
714 709
  ///Map of the \ref Point::normSquare() "normSquare()"
715 710
  ///of a \ref Point "Point"-map.
716 711
  ///\ingroup maps
717 712
  template<class M>
718 713
  class NormSquareMap
719 714
  {
720 715
    const M& _map;
721 716
  public:
722 717

	
723 718
    typedef typename M::Value::Value Value;
724 719
    typedef typename M::Key Key;
725 720
    ///\e
726 721
    NormSquareMap(const M &map) : _map(map) {}
727 722
    Value operator[](Key k) const {return _map[k].normSquare();}
728 723
  };
729 724

	
730
  ///Returns a \ref NormSquareMap class
725
  ///Returns a NormSquareMap class
731 726

	
732
  ///This function just returns a \ref NormSquareMap class.
727
  ///This function just returns a NormSquareMap class.
733 728
  ///
734 729
  ///\ingroup maps
735 730
  ///\relates NormSquareMap
736 731
  template<class M>
737 732
  inline NormSquareMap<M> normSquareMap(const M &m)
738 733
  {
739 734
    return NormSquareMap<M>(m);
740 735
  }
741 736

	
742 737
  /// @}
743 738

	
744 739
  } //namespce dim2
745 740

	
746 741
} //namespace lemon
747 742

	
748 743
#endif //LEMON_DIM2_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
#ifndef LEMON_GRAPH_TO_EPS_H
20 20
#define LEMON_GRAPH_TO_EPS_H
21 21

	
22 22
#include<iostream>
23 23
#include<fstream>
24 24
#include<sstream>
25 25
#include<algorithm>
26 26
#include<vector>
27 27

	
28 28
#ifndef WIN32
29 29
#include<sys/time.h>
30 30
#include<ctime>
31 31
#else
32 32
#define WIN32_LEAN_AND_MEAN
33 33
#define NOMINMAX
34 34
#include<windows.h>
35 35
#endif
36 36

	
37 37
#include<lemon/math.h>
38 38
#include<lemon/core.h>
39 39
#include<lemon/dim2.h>
40 40
#include<lemon/maps.h>
41 41
#include<lemon/color.h>
42 42
#include<lemon/bits/bezier.h>
43 43
#include<lemon/error.h>
44 44

	
45 45

	
46 46
///\ingroup eps_io
47 47
///\file
48 48
///\brief A well configurable tool for visualizing graphs
49 49

	
50 50
namespace lemon {
51 51

	
52 52
  namespace _graph_to_eps_bits {
53 53
    template<class MT>
54 54
    class _NegY {
55 55
    public:
56 56
      typedef typename MT::Key Key;
57 57
      typedef typename MT::Value Value;
58 58
      const MT &map;
59 59
      int yscale;
60 60
      _NegY(const MT &m,bool b) : map(m), yscale(1-b*2) {}
61 61
      Value operator[](Key n) { return Value(map[n].x,map[n].y*yscale);}
62 62
    };
63 63
  }
64 64

	
65
///Default traits class of \ref GraphToEps
65
///Default traits class of GraphToEps
66 66

	
67 67
///Default traits class of \ref GraphToEps.
68 68
///
69 69
///\c G is the type of the underlying graph.
70 70
template<class G>
71 71
struct DefaultGraphToEpsTraits
72 72
{
73 73
  typedef G Graph;
74 74
  typedef typename Graph::Node Node;
75 75
  typedef typename Graph::NodeIt NodeIt;
76 76
  typedef typename Graph::Arc Arc;
77 77
  typedef typename Graph::ArcIt ArcIt;
78 78
  typedef typename Graph::InArcIt InArcIt;
79 79
  typedef typename Graph::OutArcIt OutArcIt;
80 80

	
81 81

	
82 82
  const Graph &g;
83 83

	
84 84
  std::ostream& os;
85 85

	
86 86
  typedef ConstMap<typename Graph::Node,dim2::Point<double> > CoordsMapType;
87 87
  CoordsMapType _coords;
88 88
  ConstMap<typename Graph::Node,double > _nodeSizes;
89 89
  ConstMap<typename Graph::Node,int > _nodeShapes;
90 90

	
91 91
  ConstMap<typename Graph::Node,Color > _nodeColors;
92 92
  ConstMap<typename Graph::Arc,Color > _arcColors;
93 93

	
94 94
  ConstMap<typename Graph::Arc,double > _arcWidths;
95 95

	
96 96
  double _arcWidthScale;
97 97

	
98 98
  double _nodeScale;
99 99
  double _xBorder, _yBorder;
100 100
  double _scale;
101 101
  double _nodeBorderQuotient;
102 102

	
103 103
  bool _drawArrows;
104 104
  double _arrowLength, _arrowWidth;
105 105

	
106 106
  bool _showNodes, _showArcs;
107 107

	
108 108
  bool _enableParallel;
109 109
  double _parArcDist;
110 110

	
111 111
  bool _showNodeText;
112 112
  ConstMap<typename Graph::Node,bool > _nodeTexts;
113 113
  double _nodeTextSize;
114 114

	
115 115
  bool _showNodePsText;
116 116
  ConstMap<typename Graph::Node,bool > _nodePsTexts;
117 117
  char *_nodePsTextsPreamble;
118 118

	
119 119
  bool _undirected;
120 120

	
121 121
  bool _pleaseRemoveOsStream;
122 122

	
123 123
  bool _scaleToA4;
124 124

	
125 125
  std::string _title;
126 126
  std::string _copyright;
127 127

	
128 128
  enum NodeTextColorType
129 129
    { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType;
130 130
  ConstMap<typename Graph::Node,Color > _nodeTextColors;
131 131

	
132 132
  bool _autoNodeScale;
133 133
  bool _autoArcWidthScale;
134 134

	
135 135
  bool _absoluteNodeSizes;
136 136
  bool _absoluteArcWidths;
137 137

	
138 138
  bool _negY;
139 139

	
140 140
  bool _preScale;
141 141
  ///Constructor
142 142

	
143 143
  ///Constructor
144 144
  ///\param _g  Reference to the graph to be printed.
145 145
  ///\param _os Reference to the output stream.
146 146
  ///\param _os Reference to the output stream.
147 147
  ///By default it is <tt>std::cout</tt>.
148 148
  ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
149 149
  ///will be explicitly deallocated by the destructor.
150 150
  DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
151 151
                          bool _pros=false) :
152 152
    g(_g), os(_os),
153 153
    _coords(dim2::Point<double>(1,1)), _nodeSizes(1), _nodeShapes(0),
154 154
    _nodeColors(WHITE), _arcColors(BLACK),
155 155
    _arcWidths(1.0), _arcWidthScale(0.003),
156 156
    _nodeScale(.01), _xBorder(10), _yBorder(10), _scale(1.0),
157 157
    _nodeBorderQuotient(.1),
158 158
    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
159 159
    _showNodes(true), _showArcs(true),
160 160
    _enableParallel(false), _parArcDist(1),
161 161
    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
162 162
    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
163 163
    _undirected(lemon::UndirectedTagIndicator<G>::value),
164 164
    _pleaseRemoveOsStream(_pros), _scaleToA4(false),
165 165
    _nodeTextColorType(SAME_COL), _nodeTextColors(BLACK),
166 166
    _autoNodeScale(false),
167 167
    _autoArcWidthScale(false),
168 168
    _absoluteNodeSizes(false),
169 169
    _absoluteArcWidths(false),
170 170
    _negY(false),
171 171
    _preScale(true)
172 172
  {}
173 173
};
174 174

	
175 175
///Auxiliary class to implement the named parameters of \ref graphToEps()
176 176

	
177 177
///Auxiliary class to implement the named parameters of \ref graphToEps().
178 178
///
179 179
///For detailed examples see the \ref graph_to_eps_demo.cc demo file.
180 180
template<class T> class GraphToEps : public T
181 181
{
182 182
  // Can't believe it is required by the C++ standard
183 183
  using T::g;
184 184
  using T::os;
185 185

	
186 186
  using T::_coords;
187 187
  using T::_nodeSizes;
188 188
  using T::_nodeShapes;
189 189
  using T::_nodeColors;
190 190
  using T::_arcColors;
191 191
  using T::_arcWidths;
192 192

	
193 193
  using T::_arcWidthScale;
194 194
  using T::_nodeScale;
195 195
  using T::_xBorder;
196 196
  using T::_yBorder;
197 197
  using T::_scale;
198 198
  using T::_nodeBorderQuotient;
199 199

	
200 200
  using T::_drawArrows;
201 201
  using T::_arrowLength;
202 202
  using T::_arrowWidth;
203 203

	
204 204
  using T::_showNodes;
205 205
  using T::_showArcs;
206 206

	
207 207
  using T::_enableParallel;
208 208
  using T::_parArcDist;
209 209

	
210 210
  using T::_showNodeText;
211 211
  using T::_nodeTexts;
212 212
  using T::_nodeTextSize;
213 213

	
214 214
  using T::_showNodePsText;
215 215
  using T::_nodePsTexts;
216 216
  using T::_nodePsTextsPreamble;
217 217

	
218 218
  using T::_undirected;
219 219

	
220 220
  using T::_pleaseRemoveOsStream;
221 221

	
222 222
  using T::_scaleToA4;
223 223

	
224 224
  using T::_title;
225 225
  using T::_copyright;
226 226

	
227 227
  using T::NodeTextColorType;
228 228
  using T::CUST_COL;
229 229
  using T::DIST_COL;
230 230
  using T::DIST_BW;
231 231
  using T::_nodeTextColorType;
232 232
  using T::_nodeTextColors;
233 233

	
234 234
  using T::_autoNodeScale;
235 235
  using T::_autoArcWidthScale;
236 236

	
237 237
  using T::_absoluteNodeSizes;
238 238
  using T::_absoluteArcWidths;
239 239

	
240 240

	
241 241
  using T::_negY;
242 242
  using T::_preScale;
243 243

	
244 244
  // dradnats ++C eht yb deriuqer si ti eveileb t'naC
245 245

	
246 246
  typedef typename T::Graph Graph;
247 247
  typedef typename Graph::Node Node;
248 248
  typedef typename Graph::NodeIt NodeIt;
249 249
  typedef typename Graph::Arc Arc;
250 250
  typedef typename Graph::ArcIt ArcIt;
251 251
  typedef typename Graph::InArcIt InArcIt;
252 252
  typedef typename Graph::OutArcIt OutArcIt;
253 253

	
254 254
  static const int INTERPOL_PREC;
255 255
  static const double A4HEIGHT;
256 256
  static const double A4WIDTH;
257 257
  static const double A4BORDER;
258 258

	
259 259
  bool dontPrint;
260 260

	
261 261
public:
262 262
  ///Node shapes
263 263

	
264 264
  ///Node shapes.
265 265
  ///
266 266
  enum NodeShapes {
267 267
    /// = 0
268 268
    ///\image html nodeshape_0.png
269 269
    ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm
270 270
    CIRCLE=0,
271 271
    /// = 1
272 272
    ///\image html nodeshape_1.png
273 273
    ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm
274 274
    ///
275 275
    SQUARE=1,
276 276
    /// = 2
277 277
    ///\image html nodeshape_2.png
278 278
    ///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm
279 279
    ///
280 280
    DIAMOND=2,
281 281
    /// = 3
282 282
    ///\image html nodeshape_3.png
283 283
    ///\image latex nodeshape_2.eps "MALE shape (4)" width=2cm
284 284
    ///
285 285
    MALE=3,
286 286
    /// = 4
287 287
    ///\image html nodeshape_4.png
288 288
    ///\image latex nodeshape_2.eps "FEMALE shape (4)" width=2cm
289 289
    ///
290 290
    FEMALE=4
291 291
  };
292 292

	
293 293
private:
294 294
  class arcLess {
295 295
    const Graph &g;
296 296
  public:
297 297
    arcLess(const Graph &_g) : g(_g) {}
298 298
    bool operator()(Arc a,Arc b) const
299 299
    {
300 300
      Node ai=std::min(g.source(a),g.target(a));
301 301
      Node aa=std::max(g.source(a),g.target(a));
302 302
      Node bi=std::min(g.source(b),g.target(b));
303 303
      Node ba=std::max(g.source(b),g.target(b));
304 304
      return ai<bi ||
305 305
        (ai==bi && (aa < ba ||
306 306
                    (aa==ba && ai==g.source(a) && bi==g.target(b))));
307 307
    }
308 308
  };
309 309
  bool isParallel(Arc e,Arc f) const
310 310
  {
311 311
    return (g.source(e)==g.source(f)&&
312 312
            g.target(e)==g.target(f)) ||
313 313
      (g.source(e)==g.target(f)&&
314 314
       g.target(e)==g.source(f));
315 315
  }
316 316
  template<class TT>
317 317
  static std::string psOut(const dim2::Point<TT> &p)
318 318
    {
319 319
      std::ostringstream os;
320 320
      os << p.x << ' ' << p.y;
321 321
      return os.str();
322 322
    }
323 323
  static std::string psOut(const Color &c)
324 324
    {
325 325
      std::ostringstream os;
326 326
      os << c.red() << ' ' << c.green() << ' ' << c.blue();
327 327
      return os.str();
328 328
    }
329 329

	
330 330
public:
331 331
  GraphToEps(const T &t) : T(t), dontPrint(false) {};
332 332

	
333 333
  template<class X> struct CoordsTraits : public T {
334 334
  typedef X CoordsMapType;
335 335
    const X &_coords;
336 336
    CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
337 337
  };
338 338
  ///Sets the map of the node coordinates
339 339

	
340 340
  ///Sets the map of the node coordinates.
341 341
  ///\param x must be a node map with \ref dim2::Point "dim2::Point<double>" or
342 342
  ///\ref dim2::Point "dim2::Point<int>" values.
343 343
  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
344 344
    dontPrint=true;
345 345
    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
346 346
  }
347 347
  template<class X> struct NodeSizesTraits : public T {
348 348
    const X &_nodeSizes;
349 349
    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
350 350
  };
351 351
  ///Sets the map of the node sizes
352 352

	
353 353
  ///Sets the map of the node sizes.
354 354
  ///\param x must be a node map with \c double (or convertible) values.
355 355
  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
356 356
  {
357 357
    dontPrint=true;
358 358
    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
359 359
  }
360 360
  template<class X> struct NodeShapesTraits : public T {
361 361
    const X &_nodeShapes;
362 362
    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
363 363
  };
364 364
  ///Sets the map of the node shapes
365 365

	
366 366
  ///Sets the map of the node shapes.
367 367
  ///The available shape values
368 368
  ///can be found in \ref NodeShapes "enum NodeShapes".
369 369
  ///\param x must be a node map with \c int (or convertible) values.
370 370
  ///\sa NodeShapes
371 371
  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
372 372
  {
373 373
    dontPrint=true;
374 374
    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
375 375
  }
376 376
  template<class X> struct NodeTextsTraits : public T {
377 377
    const X &_nodeTexts;
378 378
    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
379 379
  };
380 380
  ///Sets the text printed on the nodes
381 381

	
382 382
  ///Sets the text printed on the nodes.
383 383
  ///\param x must be a node map with type that can be pushed to a standard
384 384
  ///\c ostream.
385 385
  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
386 386
  {
387 387
    dontPrint=true;
388 388
    _showNodeText=true;
389 389
    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
390 390
  }
391 391
  template<class X> struct NodePsTextsTraits : public T {
392 392
    const X &_nodePsTexts;
393 393
    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
394 394
  };
395 395
  ///Inserts a PostScript block to the nodes
396 396

	
397 397
  ///With this command it is possible to insert a verbatim PostScript
398 398
  ///block to the nodes.
399 399
  ///The PS current point will be moved to the center of the node before
400 400
  ///the PostScript block inserted.
401 401
  ///
402 402
  ///Before and after the block a newline character is inserted so you
403 403
  ///don't have to bother with the separators.
404 404
  ///
405 405
  ///\param x must be a node map with type that can be pushed to a standard
406 406
  ///\c ostream.
407 407
  ///
408 408
  ///\sa nodePsTextsPreamble()
409 409
  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
410 410
  {
411 411
    dontPrint=true;
412 412
    _showNodePsText=true;
413 413
    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
414 414
  }
415 415
  template<class X> struct ArcWidthsTraits : public T {
416 416
    const X &_arcWidths;
417 417
    ArcWidthsTraits(const T &t,const X &x) : T(t), _arcWidths(x) {}
418 418
  };
419 419
  ///Sets the map of the arc widths
420 420

	
421 421
  ///Sets the map of the arc widths.
422 422
  ///\param x must be an arc map with \c double (or convertible) values.
423 423
  template<class X> GraphToEps<ArcWidthsTraits<X> > arcWidths(const X &x)
424 424
  {
425 425
    dontPrint=true;
426 426
    return GraphToEps<ArcWidthsTraits<X> >(ArcWidthsTraits<X>(*this,x));
427 427
  }
428 428

	
429 429
  template<class X> struct NodeColorsTraits : public T {
430 430
    const X &_nodeColors;
431 431
    NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
432 432
  };
433 433
  ///Sets the map of the node colors
434 434

	
435 435
  ///Sets the map of the node colors.
436 436
  ///\param x must be a node map with \ref Color values.
437 437
  ///
438 438
  ///\sa Palette
439 439
  template<class X> GraphToEps<NodeColorsTraits<X> >
440 440
  nodeColors(const X &x)
441 441
  {
442 442
    dontPrint=true;
443 443
    return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
444 444
  }
445 445
  template<class X> struct NodeTextColorsTraits : public T {
446 446
    const X &_nodeTextColors;
447 447
    NodeTextColorsTraits(const T &t,const X &x) : T(t), _nodeTextColors(x) {}
448 448
  };
449 449
  ///Sets the map of the node text colors
450 450

	
451 451
  ///Sets the map of the node text colors.
452 452
  ///\param x must be a node map with \ref Color values.
453 453
  ///
454 454
  ///\sa Palette
455 455
  template<class X> GraphToEps<NodeTextColorsTraits<X> >
456 456
  nodeTextColors(const X &x)
457 457
  {
458 458
    dontPrint=true;
459 459
    _nodeTextColorType=CUST_COL;
460 460
    return GraphToEps<NodeTextColorsTraits<X> >
461 461
      (NodeTextColorsTraits<X>(*this,x));
462 462
  }
463 463
  template<class X> struct ArcColorsTraits : public T {
464 464
    const X &_arcColors;
465 465
    ArcColorsTraits(const T &t,const X &x) : T(t), _arcColors(x) {}
466 466
  };
467 467
  ///Sets the map of the arc colors
468 468

	
469 469
  ///Sets the map of the arc colors.
470 470
  ///\param x must be an arc map with \ref Color values.
471 471
  ///
472 472
  ///\sa Palette
473 473
  template<class X> GraphToEps<ArcColorsTraits<X> >
474 474
  arcColors(const X &x)
475 475
  {
476 476
    dontPrint=true;
477 477
    return GraphToEps<ArcColorsTraits<X> >(ArcColorsTraits<X>(*this,x));
478 478
  }
479 479
  ///Sets a global scale factor for node sizes
480 480

	
481 481
  ///Sets a global scale factor for node sizes.
482 482
  ///
483 483
  /// If nodeSizes() is not given, this function simply sets the node
484 484
  /// sizes to \c d.  If nodeSizes() is given, but
485 485
  /// autoNodeScale() is not, then the node size given by
486 486
  /// nodeSizes() will be multiplied by the value \c d.
487 487
  /// If both nodeSizes() and autoNodeScale() are used, then the
488 488
  /// node sizes will be scaled in such a way that the greatest size will be
489 489
  /// equal to \c d.
490 490
  /// \sa nodeSizes()
491 491
  /// \sa autoNodeScale()
492 492
  GraphToEps<T> &nodeScale(double d=.01) {_nodeScale=d;return *this;}
493 493
  ///Turns on/off the automatic node size scaling.
494 494

	
495 495
  ///Turns on/off the automatic node size scaling.
496 496
  ///
497 497
  ///\sa nodeScale()
498 498
  ///
499 499
  GraphToEps<T> &autoNodeScale(bool b=true) {
500 500
    _autoNodeScale=b;return *this;
501 501
  }
502 502

	
503 503
  ///Turns on/off the absolutematic node size scaling.
504 504

	
505 505
  ///Turns on/off the absolutematic node size scaling.
506 506
  ///
507 507
  ///\sa nodeScale()
508 508
  ///
509 509
  GraphToEps<T> &absoluteNodeSizes(bool b=true) {
510 510
    _absoluteNodeSizes=b;return *this;
511 511
  }
512 512

	
513 513
  ///Negates the Y coordinates.
514 514
  GraphToEps<T> &negateY(bool b=true) {
515 515
    _negY=b;return *this;
516 516
  }
517 517

	
518 518
  ///Turn on/off pre-scaling
519 519

	
520 520
  ///By default graphToEps() rescales the whole image in order to avoid
521 521
  ///very big or very small bounding boxes.
522 522
  ///
523 523
  ///This (p)rescaling can be turned off with this function.
524 524
  ///
525 525
  GraphToEps<T> &preScale(bool b=true) {
526 526
    _preScale=b;return *this;
527 527
  }
528 528

	
529 529
  ///Sets a global scale factor for arc widths
530 530

	
531 531
  /// Sets a global scale factor for arc widths.
532 532
  ///
533 533
  /// If arcWidths() is not given, this function simply sets the arc
534 534
  /// widths to \c d.  If arcWidths() is given, but
535 535
  /// autoArcWidthScale() is not, then the arc withs given by
536 536
  /// arcWidths() will be multiplied by the value \c d.
537 537
  /// If both arcWidths() and autoArcWidthScale() are used, then the
538 538
  /// arc withs will be scaled in such a way that the greatest width will be
539 539
  /// equal to \c d.
540 540
  GraphToEps<T> &arcWidthScale(double d=.003) {_arcWidthScale=d;return *this;}
541 541
  ///Turns on/off the automatic arc width scaling.
542 542

	
543 543
  ///Turns on/off the automatic arc width scaling.
544 544
  ///
545 545
  ///\sa arcWidthScale()
546 546
  ///
547 547
  GraphToEps<T> &autoArcWidthScale(bool b=true) {
548 548
    _autoArcWidthScale=b;return *this;
549 549
  }
550 550
  ///Turns on/off the absolutematic arc width scaling.
551 551

	
552 552
  ///Turns on/off the absolutematic arc width scaling.
553 553
  ///
554 554
  ///\sa arcWidthScale()
555 555
  ///
556 556
  GraphToEps<T> &absoluteArcWidths(bool b=true) {
557 557
    _absoluteArcWidths=b;return *this;
558 558
  }
559 559
  ///Sets a global scale factor for the whole picture
560 560
  GraphToEps<T> &scale(double d) {_scale=d;return *this;}
561 561
  ///Sets the width of the border around the picture
562 562
  GraphToEps<T> &border(double b=10) {_xBorder=_yBorder=b;return *this;}
563 563
  ///Sets the width of the border around the picture
564 564
  GraphToEps<T> &border(double x, double y) {
565 565
    _xBorder=x;_yBorder=y;return *this;
566 566
  }
567 567
  ///Sets whether to draw arrows
568 568
  GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
569 569
  ///Sets the length of the arrowheads
570 570
  GraphToEps<T> &arrowLength(double d=1.0) {_arrowLength*=d;return *this;}
571 571
  ///Sets the width of the arrowheads
572 572
  GraphToEps<T> &arrowWidth(double d=.3) {_arrowWidth*=d;return *this;}
573 573

	
574 574
  ///Scales the drawing to fit to A4 page
575 575
  GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;}
576 576

	
577 577
  ///Enables parallel arcs
578 578
  GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
579 579

	
580 580
  ///Sets the distance between parallel arcs
581 581
  GraphToEps<T> &parArcDist(double d) {_parArcDist*=d;return *this;}
582 582

	
583 583
  ///Hides the arcs
584 584
  GraphToEps<T> &hideArcs(bool b=true) {_showArcs=!b;return *this;}
585 585
  ///Hides the nodes
586 586
  GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
587 587

	
588 588
  ///Sets the size of the node texts
589 589
  GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
590 590

	
591 591
  ///Sets the color of the node texts to be different from the node color
592 592

	
593 593
  ///Sets the color of the node texts to be as different from the node color
594 594
  ///as it is possible.
595 595
  GraphToEps<T> &distantColorNodeTexts()
596 596
  {_nodeTextColorType=DIST_COL;return *this;}
597 597
  ///Sets the color of the node texts to be black or white and always visible.
598 598

	
599 599
  ///Sets the color of the node texts to be black or white according to
600 600
  ///which is more different from the node color.
601 601
  GraphToEps<T> &distantBWNodeTexts()
602 602
  {_nodeTextColorType=DIST_BW;return *this;}
603 603

	
604 604
  ///Gives a preamble block for node Postscript block.
605 605

	
606 606
  ///Gives a preamble block for node Postscript block.
607 607
  ///
608 608
  ///\sa nodePsTexts()
609 609
  GraphToEps<T> & nodePsTextsPreamble(const char *str) {
610 610
    _nodePsTextsPreamble=str ;return *this;
611 611
  }
612 612
  ///Sets whether the graph is undirected
613 613

	
614 614
  ///Sets whether the graph is undirected.
615 615
  ///
616 616
  ///This setting is the default for undirected graphs.
617 617
  ///
618 618
  ///\sa directed()
619 619
   GraphToEps<T> &undirected(bool b=true) {_undirected=b;return *this;}
620 620

	
621 621
  ///Sets whether the graph is directed
622 622

	
623 623
  ///Sets whether the graph is directed.
624 624
  ///Use it to show the edges as a pair of directed ones.
625 625
  ///
626 626
  ///This setting is the default for digraphs.
627 627
  ///
628 628
  ///\sa undirected()
629 629
  GraphToEps<T> &directed(bool b=true) {_undirected=!b;return *this;}
630 630

	
631 631
  ///Sets the title.
632 632

	
633 633
  ///Sets the title of the generated image,
634 634
  ///namely it inserts a <tt>%%Title:</tt> DSC field to the header of
635 635
  ///the EPS file.
636 636
  GraphToEps<T> &title(const std::string &t) {_title=t;return *this;}
637 637
  ///Sets the copyright statement.
638 638

	
639 639
  ///Sets the copyright statement of the generated image,
640 640
  ///namely it inserts a <tt>%%Copyright:</tt> DSC field to the header of
641 641
  ///the EPS file.
642 642
  GraphToEps<T> &copyright(const std::string &t) {_copyright=t;return *this;}
643 643

	
644 644
protected:
645 645
  bool isInsideNode(dim2::Point<double> p, double r,int t)
646 646
  {
647 647
    switch(t) {
648 648
    case CIRCLE:
649 649
    case MALE:
650 650
    case FEMALE:
651 651
      return p.normSquare()<=r*r;
652 652
    case SQUARE:
653 653
      return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r;
654 654
    case DIAMOND:
655 655
      return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r;
656 656
    }
657 657
    return false;
658 658
  }
659 659

	
660 660
public:
661 661
  ~GraphToEps() { }
662 662

	
663 663
  ///Draws the graph.
664 664

	
665 665
  ///Like other functions using
666 666
  ///\ref named-templ-func-param "named template parameters",
667 667
  ///this function calls the algorithm itself, i.e. in this case
668 668
  ///it draws the graph.
669 669
  void run() {
670 670
    const double EPSILON=1e-9;
671 671
    if(dontPrint) return;
672 672

	
673 673
    _graph_to_eps_bits::_NegY<typename T::CoordsMapType>
674 674
      mycoords(_coords,_negY);
675 675

	
676 676
    os << "%!PS-Adobe-2.0 EPSF-2.0\n";
677 677
    if(_title.size()>0) os << "%%Title: " << _title << '\n';
678 678
     if(_copyright.size()>0) os << "%%Copyright: " << _copyright << '\n';
679 679
    os << "%%Creator: LEMON, graphToEps()\n";
680 680

	
681 681
    {
682 682
#ifndef WIN32
683 683
      timeval tv;
684 684
      gettimeofday(&tv, 0);
685 685

	
686 686
      char cbuf[26];
687 687
      ctime_r(&tv.tv_sec,cbuf);
688 688
      os << "%%CreationDate: " << cbuf;
689 689
#else
690 690
      SYSTEMTIME time;
691 691
      char buf1[11], buf2[9], buf3[5];
692 692

	
693 693
      GetSystemTime(&time);
694 694
      if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &time,
695 695
                        "ddd MMM dd", buf1, 11) &&
696 696
          GetTimeFormat(LOCALE_USER_DEFAULT, 0, &time,
697 697
                        "HH':'mm':'ss", buf2, 9) &&
698 698
          GetDateFormat(LOCALE_USER_DEFAULT, 0, &time,
699 699
                                "yyyy", buf3, 5)) {
700 700
        os << "%%CreationDate: " << buf1 << ' '
701 701
           << buf2 << ' ' << buf3 << std::endl;
702 702
      }
703 703
#endif
704 704
    }
705 705

	
706 706
    if (_autoArcWidthScale) {
707 707
      double max_w=0;
708 708
      for(ArcIt e(g);e!=INVALID;++e)
709 709
        max_w=std::max(double(_arcWidths[e]),max_w);
710 710
      if(max_w>EPSILON) {
711 711
        _arcWidthScale/=max_w;
712 712
      }
713 713
    }
714 714

	
715 715
    if (_autoNodeScale) {
716 716
      double max_s=0;
717 717
      for(NodeIt n(g);n!=INVALID;++n)
718 718
        max_s=std::max(double(_nodeSizes[n]),max_s);
719 719
      if(max_s>EPSILON) {
720 720
        _nodeScale/=max_s;
721 721
      }
722 722
    }
723 723

	
724 724
    double diag_len = 1;
725 725
    if(!(_absoluteNodeSizes&&_absoluteArcWidths)) {
726 726
      dim2::Box<double> bb;
727 727
      for(NodeIt n(g);n!=INVALID;++n) bb.add(mycoords[n]);
728 728
      if (bb.empty()) {
729 729
        bb = dim2::Box<double>(dim2::Point<double>(0,0));
730 730
      }
731 731
      diag_len = std::sqrt((bb.bottomLeft()-bb.topRight()).normSquare());
732 732
      if(diag_len<EPSILON) diag_len = 1;
733 733
      if(!_absoluteNodeSizes) _nodeScale*=diag_len;
734 734
      if(!_absoluteArcWidths) _arcWidthScale*=diag_len;
735 735
    }
736 736

	
737 737
    dim2::Box<double> bb;
738 738
    for(NodeIt n(g);n!=INVALID;++n) {
739 739
      double ns=_nodeSizes[n]*_nodeScale;
740 740
      dim2::Point<double> p(ns,ns);
741 741
      switch(_nodeShapes[n]) {
742 742
      case CIRCLE:
743 743
      case SQUARE:
744 744
      case DIAMOND:
745 745
        bb.add(p+mycoords[n]);
746 746
        bb.add(-p+mycoords[n]);
747 747
        break;
748 748
      case MALE:
749 749
        bb.add(-p+mycoords[n]);
750 750
        bb.add(dim2::Point<double>(1.5*ns,1.5*std::sqrt(3.0)*ns)+mycoords[n]);
751 751
        break;
752 752
      case FEMALE:
753 753
        bb.add(p+mycoords[n]);
754 754
        bb.add(dim2::Point<double>(-ns,-3.01*ns)+mycoords[n]);
755 755
        break;
756 756
      }
757 757
    }
758 758
    if (bb.empty()) {
759 759
      bb = dim2::Box<double>(dim2::Point<double>(0,0));
760 760
    }
761 761

	
762 762
    if(_scaleToA4)
763 763
      os <<"%%BoundingBox: 0 0 596 842\n%%DocumentPaperSizes: a4\n";
764 764
    else {
765 765
      if(_preScale) {
766 766
        //Rescale so that BoundingBox won't be neither to big nor too small.
767 767
        while(bb.height()*_scale>1000||bb.width()*_scale>1000) _scale/=10;
768 768
        while(bb.height()*_scale<100||bb.width()*_scale<100) _scale*=10;
769 769
      }
770 770

	
771 771
      os << "%%BoundingBox: "
772 772
         << int(floor(bb.left()   * _scale - _xBorder)) << ' '
773 773
         << int(floor(bb.bottom() * _scale - _yBorder)) << ' '
774 774
         << int(ceil(bb.right()  * _scale + _xBorder)) << ' '
775 775
         << int(ceil(bb.top()    * _scale + _yBorder)) << '\n';
776 776
    }
777 777

	
778 778
    os << "%%EndComments\n";
779 779

	
780 780
    //x1 y1 x2 y2 x3 y3 cr cg cb w
781 781
    os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
782 782
       << "      4 2 roll 1 index 1 index curveto stroke } bind def\n";
783 783
    os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke }"
784 784
       << " bind def\n";
785 785
    //x y r
786 786
    os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath }"
787 787
       << " bind def\n";
788 788
    //x y r
789 789
    os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n"
790 790
       << "      2 index 1 index sub 2 index 2 index add lineto\n"
791 791
       << "      2 index 1 index sub 2 index 2 index sub lineto\n"
792 792
       << "      2 index 1 index add 2 index 2 index sub lineto\n"
793 793
       << "      closepath pop pop pop} bind def\n";
794 794
    //x y r
795 795
    os << "/di { newpath 2 index 1 index add 2 index moveto\n"
796 796
       << "      2 index             2 index 2 index add lineto\n"
797 797
       << "      2 index 1 index sub 2 index             lineto\n"
798 798
       << "      2 index             2 index 2 index sub lineto\n"
799 799
       << "      closepath pop pop pop} bind def\n";
800 800
    // x y r cr cg cb
801 801
    os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n"
802 802
       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
803 803
       << "   } bind def\n";
804 804
    os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n"
805 805
       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n"
806 806
       << "   } bind def\n";
807 807
    os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n"
808 808
       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n"
809 809
       << "   } bind def\n";
810 810
    os << "/nfemale { 0 0 0 setrgbcolor 3 index "
811 811
       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
812 812
       << " 1.5 mul mul setlinewidth\n"
813 813
       << "  newpath 5 index 5 index moveto "
814 814
       << "5 index 5 index 5 index 3.01 mul sub\n"
815 815
       << "  lineto 5 index 4 index .7 mul sub 5 index 5 index 2.2 mul sub"
816 816
       << " moveto\n"
817 817
       << "  5 index 4 index .7 mul add 5 index 5 index 2.2 mul sub lineto "
818 818
       << "stroke\n"
819 819
       << "  5 index 5 index 5 index c fill\n"
820 820
       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
821 821
       << "  } bind def\n";
822 822
    os << "/nmale {\n"
823 823
       << "  0 0 0 setrgbcolor 3 index "
824 824
       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
825 825
       <<" 1.5 mul mul setlinewidth\n"
826 826
       << "  newpath 5 index 5 index moveto\n"
827 827
       << "  5 index 4 index 1 mul 1.5 mul add\n"
828 828
       << "  5 index 5 index 3 sqrt 1.5 mul mul add\n"
829 829
       << "  1 index 1 index lineto\n"
830 830
       << "  1 index 1 index 7 index sub moveto\n"
831 831
       << "  1 index 1 index lineto\n"
832 832
       << "  exch 5 index 3 sqrt .5 mul mul sub exch 5 index .5 mul sub"
833 833
       << " lineto\n"
834 834
       << "  stroke\n"
835 835
       << "  5 index 5 index 5 index c fill\n"
836 836
       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
837 837
       << "  } bind def\n";
838 838

	
839 839

	
840 840
    os << "/arrl " << _arrowLength << " def\n";
841 841
    os << "/arrw " << _arrowWidth << " def\n";
842 842
    // l dx_norm dy_norm
843 843
    os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
844 844
    //len w dx_norm dy_norm x1 y1 cr cg cb
845 845
    os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx "
846 846
       << "exch def\n"
847 847
       << "       /w exch def /len exch def\n"
848 848
      //<< "0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
849 849
       << "       newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
850 850
       << "       len w sub arrl sub dx dy lrl\n"
851 851
       << "       arrw dy dx neg lrl\n"
852 852
       << "       dx arrl w add mul dy w 2 div arrw add mul sub\n"
853 853
       << "       dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
854 854
       << "       dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
855 855
       << "       dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
856 856
       << "       arrw dy dx neg lrl\n"
857 857
       << "       len w sub arrl sub neg dx dy lrl\n"
858 858
       << "       closepath fill } bind def\n";
859 859
    os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
860 860
       << "         neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
861 861

	
862 862
    os << "\ngsave\n";
863 863
    if(_scaleToA4)
864 864
      if(bb.height()>bb.width()) {
865 865
        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.height(),
866 866
                  (A4WIDTH-2*A4BORDER)/bb.width());
867 867
        os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' '
868 868
           << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER
869 869
           << " translate\n"
870 870
           << sc << " dup scale\n"
871 871
           << -bb.left() << ' ' << -bb.bottom() << " translate\n";
872 872
      }
873 873
      else {
874 874
        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.width(),
875 875
                  (A4WIDTH-2*A4BORDER)/bb.height());
876 876
        os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' '
877 877
           << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER
878 878
           << " translate\n"
879 879
           << sc << " dup scale\n90 rotate\n"
880 880
           << -bb.left() << ' ' << -bb.top() << " translate\n";
881 881
        }
882 882
    else if(_scale!=1.0) os << _scale << " dup scale\n";
883 883

	
884 884
    if(_showArcs) {
885 885
      os << "%Arcs:\ngsave\n";
886 886
      if(_enableParallel) {
887 887
        std::vector<Arc> el;
888 888
        for(ArcIt e(g);e!=INVALID;++e)
889 889
          if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0
890 890
             &&g.source(e)!=g.target(e))
891 891
            el.push_back(e);
892 892
        std::sort(el.begin(),el.end(),arcLess(g));
893 893

	
894 894
        typename std::vector<Arc>::iterator j;
895 895
        for(typename std::vector<Arc>::iterator i=el.begin();i!=el.end();i=j) {
896 896
          for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
897 897

	
898 898
          double sw=0;
899 899
          for(typename std::vector<Arc>::iterator e=i;e!=j;++e)
900 900
            sw+=_arcWidths[*e]*_arcWidthScale+_parArcDist;
901 901
          sw-=_parArcDist;
902 902
          sw/=-2.0;
903 903
          dim2::Point<double>
904 904
            dvec(mycoords[g.target(*i)]-mycoords[g.source(*i)]);
905 905
          double l=std::sqrt(dvec.normSquare());
906 906
          dim2::Point<double> d(dvec/std::max(l,EPSILON));
907 907
          dim2::Point<double> m;
908 908
//           m=dim2::Point<double>(mycoords[g.target(*i)]+
909 909
//                                 mycoords[g.source(*i)])/2.0;
910 910

	
911 911
//            m=dim2::Point<double>(mycoords[g.source(*i)])+
912 912
//             dvec*(double(_nodeSizes[g.source(*i)])/
913 913
//                (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
914 914

	
915 915
          m=dim2::Point<double>(mycoords[g.source(*i)])+
916 916
            d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
917 917

	
918 918
          for(typename std::vector<Arc>::iterator e=i;e!=j;++e) {
919 919
            sw+=_arcWidths[*e]*_arcWidthScale/2.0;
920 920
            dim2::Point<double> mm=m+rot90(d)*sw/.75;
921 921
            if(_drawArrows) {
922 922
              int node_shape;
923 923
              dim2::Point<double> s=mycoords[g.source(*e)];
924 924
              dim2::Point<double> t=mycoords[g.target(*e)];
925 925
              double rn=_nodeSizes[g.target(*e)]*_nodeScale;
926 926
              node_shape=_nodeShapes[g.target(*e)];
927 927
              dim2::Bezier3 bez(s,mm,mm,t);
928 928
              double t1=0,t2=1;
929 929
              for(int ii=0;ii<INTERPOL_PREC;++ii)
930 930
                if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2;
931 931
                else t1=(t1+t2)/2;
932 932
              dim2::Point<double> apoint=bez((t1+t2)/2);
933 933
              rn = _arrowLength+_arcWidths[*e]*_arcWidthScale;
934 934
              rn*=rn;
935 935
              t2=(t1+t2)/2;t1=0;
936 936
              for(int ii=0;ii<INTERPOL_PREC;++ii)
937 937
                if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2;
938 938
                else t2=(t1+t2)/2;
939 939
              dim2::Point<double> linend=bez((t1+t2)/2);
940 940
              bez=bez.before((t1+t2)/2);
941 941
//               rn=_nodeSizes[g.source(*e)]*_nodeScale;
942 942
//               node_shape=_nodeShapes[g.source(*e)];
943 943
//               t1=0;t2=1;
944 944
//               for(int i=0;i<INTERPOL_PREC;++i)
945 945
//                 if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape))
946 946
//                   t1=(t1+t2)/2;
947 947
//                 else t2=(t1+t2)/2;
948 948
//               bez=bez.after((t1+t2)/2);
949 949
              os << _arcWidths[*e]*_arcWidthScale << " setlinewidth "
950 950
                 << _arcColors[*e].red() << ' '
951 951
                 << _arcColors[*e].green() << ' '
952 952
                 << _arcColors[*e].blue() << " setrgbcolor newpath\n"
953 953
                 << bez.p1.x << ' ' <<  bez.p1.y << " moveto\n"
954 954
                 << bez.p2.x << ' ' << bez.p2.y << ' '
955 955
                 << bez.p3.x << ' ' << bez.p3.y << ' '
956 956
                 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
957 957
              dim2::Point<double> dd(rot90(linend-apoint));
958 958
              dd*=(.5*_arcWidths[*e]*_arcWidthScale+_arrowWidth)/
959 959
                std::sqrt(dd.normSquare());
960 960
              os << "newpath " << psOut(apoint) << " moveto "
961 961
                 << psOut(linend+dd) << " lineto "
962 962
                 << psOut(linend-dd) << " lineto closepath fill\n";
963 963
            }
964 964
            else {
965 965
              os << mycoords[g.source(*e)].x << ' '
966 966
                 << mycoords[g.source(*e)].y << ' '
967 967
                 << mm.x << ' ' << mm.y << ' '
968 968
                 << mycoords[g.target(*e)].x << ' '
969 969
                 << mycoords[g.target(*e)].y << ' '
970 970
                 << _arcColors[*e].red() << ' '
971 971
                 << _arcColors[*e].green() << ' '
972 972
                 << _arcColors[*e].blue() << ' '
973 973
                 << _arcWidths[*e]*_arcWidthScale << " lb\n";
974 974
            }
975 975
            sw+=_arcWidths[*e]*_arcWidthScale/2.0+_parArcDist;
976 976
          }
977 977
        }
978 978
      }
979 979
      else for(ArcIt e(g);e!=INVALID;++e)
980 980
        if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0
981 981
           &&g.source(e)!=g.target(e)) {
982 982
          if(_drawArrows) {
983 983
            dim2::Point<double> d(mycoords[g.target(e)]-mycoords[g.source(e)]);
984 984
            double rn=_nodeSizes[g.target(e)]*_nodeScale;
985 985
            int node_shape=_nodeShapes[g.target(e)];
986 986
            double t1=0,t2=1;
987 987
            for(int i=0;i<INTERPOL_PREC;++i)
988 988
              if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2;
989 989
              else t2=(t1+t2)/2;
990 990
            double l=std::sqrt(d.normSquare());
991 991
            d/=l;
992 992

	
993 993
            os << l*(1-(t1+t2)/2) << ' '
994 994
               << _arcWidths[e]*_arcWidthScale << ' '
995 995
               << d.x << ' ' << d.y << ' '
996 996
               << mycoords[g.source(e)].x << ' '
997 997
               << mycoords[g.source(e)].y << ' '
998 998
               << _arcColors[e].red() << ' '
999 999
               << _arcColors[e].green() << ' '
1000 1000
               << _arcColors[e].blue() << " arr\n";
1001 1001
          }
1002 1002
          else os << mycoords[g.source(e)].x << ' '
1003 1003
                  << mycoords[g.source(e)].y << ' '
1004 1004
                  << mycoords[g.target(e)].x << ' '
1005 1005
                  << mycoords[g.target(e)].y << ' '
1006 1006
                  << _arcColors[e].red() << ' '
1007 1007
                  << _arcColors[e].green() << ' '
1008 1008
                  << _arcColors[e].blue() << ' '
1009 1009
                  << _arcWidths[e]*_arcWidthScale << " l\n";
1010 1010
        }
1011 1011
      os << "grestore\n";
1012 1012
    }
1013 1013
    if(_showNodes) {
1014 1014
      os << "%Nodes:\ngsave\n";
1015 1015
      for(NodeIt n(g);n!=INVALID;++n) {
1016 1016
        os << mycoords[n].x << ' ' << mycoords[n].y << ' '
1017 1017
           << _nodeSizes[n]*_nodeScale << ' '
1018 1018
           << _nodeColors[n].red() << ' '
1019 1019
           << _nodeColors[n].green() << ' '
1020 1020
           << _nodeColors[n].blue() << ' ';
1021 1021
        switch(_nodeShapes[n]) {
1022 1022
        case CIRCLE:
1023 1023
          os<< "nc";break;
1024 1024
        case SQUARE:
1025 1025
          os<< "nsq";break;
1026 1026
        case DIAMOND:
1027 1027
          os<< "ndi";break;
1028 1028
        case MALE:
1029 1029
          os<< "nmale";break;
1030 1030
        case FEMALE:
1031 1031
          os<< "nfemale";break;
1032 1032
        }
1033 1033
        os<<'\n';
1034 1034
      }
1035 1035
      os << "grestore\n";
1036 1036
    }
1037 1037
    if(_showNodeText) {
1038 1038
      os << "%Node texts:\ngsave\n";
1039 1039
      os << "/fosi " << _nodeTextSize << " def\n";
1040 1040
      os << "(Helvetica) findfont fosi scalefont setfont\n";
1041 1041
      for(NodeIt n(g);n!=INVALID;++n) {
1042 1042
        switch(_nodeTextColorType) {
1043 1043
        case DIST_COL:
1044 1044
          os << psOut(distantColor(_nodeColors[n])) << " setrgbcolor\n";
1045 1045
          break;
1046 1046
        case DIST_BW:
1047 1047
          os << psOut(distantBW(_nodeColors[n])) << " setrgbcolor\n";
1048 1048
          break;
1049 1049
        case CUST_COL:
1050 1050
          os << psOut(distantColor(_nodeTextColors[n])) << " setrgbcolor\n";
1051 1051
          break;
1052 1052
        default:
1053 1053
          os << "0 0 0 setrgbcolor\n";
1054 1054
        }
1055 1055
        os << mycoords[n].x << ' ' << mycoords[n].y
1056 1056
           << " (" << _nodeTexts[n] << ") cshow\n";
1057 1057
      }
1058 1058
      os << "grestore\n";
1059 1059
    }
1060 1060
    if(_showNodePsText) {
1061 1061
      os << "%Node PS blocks:\ngsave\n";
1062 1062
      for(NodeIt n(g);n!=INVALID;++n)
1063 1063
        os << mycoords[n].x << ' ' << mycoords[n].y
1064 1064
           << " moveto\n" << _nodePsTexts[n] << "\n";
1065 1065
      os << "grestore\n";
1066 1066
    }
1067 1067

	
1068 1068
    os << "grestore\nshowpage\n";
1069 1069

	
1070 1070
    //CleanUp:
1071 1071
    if(_pleaseRemoveOsStream) {delete &os;}
1072 1072
  }
1073 1073

	
1074 1074
  ///\name Aliases
1075 1075
  ///These are just some aliases to other parameter setting functions.
1076 1076

	
1077 1077
  ///@{
1078 1078

	
1079 1079
  ///An alias for arcWidths()
1080 1080
  template<class X> GraphToEps<ArcWidthsTraits<X> > edgeWidths(const X &x)
1081 1081
  {
1082 1082
    return arcWidths(x);
1083 1083
  }
1084 1084

	
1085 1085
  ///An alias for arcColors()
1086 1086
  template<class X> GraphToEps<ArcColorsTraits<X> >
1087 1087
  edgeColors(const X &x)
1088 1088
  {
1089 1089
    return arcColors(x);
1090 1090
  }
1091 1091

	
1092 1092
  ///An alias for arcWidthScale()
1093 1093
  GraphToEps<T> &edgeWidthScale(double d) {return arcWidthScale(d);}
1094 1094

	
1095 1095
  ///An alias for autoArcWidthScale()
1096 1096
  GraphToEps<T> &autoEdgeWidthScale(bool b=true)
1097 1097
  {
1098 1098
    return autoArcWidthScale(b);
1099 1099
  }
1100 1100

	
1101 1101
  ///An alias for absoluteArcWidths()
1102 1102
  GraphToEps<T> &absoluteEdgeWidths(bool b=true)
1103 1103
  {
1104 1104
    return absoluteArcWidths(b);
1105 1105
  }
1106 1106

	
1107 1107
  ///An alias for parArcDist()
1108 1108
  GraphToEps<T> &parEdgeDist(double d) {return parArcDist(d);}
1109 1109

	
1110 1110
  ///An alias for hideArcs()
1111 1111
  GraphToEps<T> &hideEdges(bool b=true) {return hideArcs(b);}
1112 1112

	
1113 1113
  ///@}
1114 1114
};
1115 1115

	
1116 1116
template<class T>
1117 1117
const int GraphToEps<T>::INTERPOL_PREC = 20;
1118 1118
template<class T>
1119 1119
const double GraphToEps<T>::A4HEIGHT = 841.8897637795276;
1120 1120
template<class T>
1121 1121
const double GraphToEps<T>::A4WIDTH  = 595.275590551181;
1122 1122
template<class T>
1123 1123
const double GraphToEps<T>::A4BORDER = 15;
1124 1124

	
1125 1125

	
1126 1126
///Generates an EPS file from a graph
1127 1127

	
1128 1128
///\ingroup eps_io
1129 1129
///Generates an EPS file from a graph.
1130 1130
///\param g Reference to the graph to be printed.
1131 1131
///\param os Reference to the output stream.
1132 1132
///By default it is <tt>std::cout</tt>.
1133 1133
///
1134 1134
///This function also has a lot of
1135 1135
///\ref named-templ-func-param "named parameters",
1136 1136
///they are declared as the members of class \ref GraphToEps. The following
1137 1137
///example shows how to use these parameters.
1138 1138
///\code
1139 1139
/// graphToEps(g,os).scale(10).coords(coords)
1140 1140
///              .nodeScale(2).nodeSizes(sizes)
1141 1141
///              .arcWidthScale(.4).run();
1142 1142
///\endcode
1143 1143
///
1144 1144
///For more detailed examples see the \ref graph_to_eps_demo.cc demo file.
1145 1145
///
1146 1146
///\warning Don't forget to put the \ref GraphToEps::run() "run()"
1147 1147
///to the end of the parameter list.
1148 1148
///\sa GraphToEps
1149 1149
///\sa graphToEps(G &g, const char *file_name)
1150 1150
template<class G>
1151 1151
GraphToEps<DefaultGraphToEpsTraits<G> >
1152 1152
graphToEps(G &g, std::ostream& os=std::cout)
1153 1153
{
1154 1154
  return
1155 1155
    GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
1156 1156
}
1157 1157

	
1158 1158
///Generates an EPS file from a graph
1159 1159

	
1160 1160
///\ingroup eps_io
1161 1161
///This function does the same as
1162 1162
///\ref graphToEps(G &g,std::ostream& os)
1163 1163
///but it writes its output into the file \c file_name
1164 1164
///instead of a stream.
1165 1165
///\sa graphToEps(G &g, std::ostream& os)
1166 1166
template<class G>
1167 1167
GraphToEps<DefaultGraphToEpsTraits<G> >
1168 1168
graphToEps(G &g,const char *file_name)
1169 1169
{
1170 1170
  std::ostream* os = new std::ofstream(file_name);
1171 1171
  if (!(*os)) {
1172 1172
    delete os;
1173 1173
    throw IoError("Cannot write file", file_name);
1174 1174
  }
1175 1175
  return GraphToEps<DefaultGraphToEpsTraits<G> >
1176 1176
    (DefaultGraphToEpsTraits<G>(g,*os,true));
1177 1177
}
1178 1178

	
1179 1179
///Generates an EPS file from a graph
1180 1180

	
1181 1181
///\ingroup eps_io
1182 1182
///This function does the same as
1183 1183
///\ref graphToEps(G &g,std::ostream& os)
1184 1184
///but it writes its output into the file \c file_name
1185 1185
///instead of a stream.
1186 1186
///\sa graphToEps(G &g, std::ostream& os)
1187 1187
template<class G>
1188 1188
GraphToEps<DefaultGraphToEpsTraits<G> >
1189 1189
graphToEps(G &g,const std::string& file_name)
1190 1190
{
1191 1191
  std::ostream* os = new std::ofstream(file_name.c_str());
1192 1192
  if (!(*os)) {
1193 1193
    delete os;
1194 1194
    throw IoError("Cannot write file", file_name);
1195 1195
  }
1196 1196
  return GraphToEps<DefaultGraphToEpsTraits<G> >
1197 1197
    (DefaultGraphToEpsTraits<G>(g,*os,true));
1198 1198
}
1199 1199

	
1200 1200
} //END OF NAMESPACE LEMON
1201 1201

	
1202 1202
#endif // LEMON_GRAPH_TO_EPS_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
#ifndef LEMON_LIST_GRAPH_H
20 20
#define LEMON_LIST_GRAPH_H
21 21

	
22 22
///\ingroup graphs
23 23
///\file
24 24
///\brief ListDigraph, ListGraph classes.
25 25

	
26 26
#include <lemon/core.h>
27 27
#include <lemon/error.h>
28 28
#include <lemon/bits/graph_extender.h>
29 29

	
30 30
#include <vector>
31 31
#include <list>
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  class ListDigraphBase {
36 36

	
37 37
  protected:
38 38
    struct NodeT {
39 39
      int first_in, first_out;
40 40
      int prev, next;
41 41
    };
42 42

	
43 43
    struct ArcT {
44 44
      int target, source;
45 45
      int prev_in, prev_out;
46 46
      int next_in, next_out;
47 47
    };
48 48

	
49 49
    std::vector<NodeT> nodes;
50 50

	
51 51
    int first_node;
52 52

	
53 53
    int first_free_node;
54 54

	
55 55
    std::vector<ArcT> arcs;
56 56

	
57 57
    int first_free_arc;
58 58

	
59 59
  public:
60 60

	
61 61
    typedef ListDigraphBase Digraph;
62 62

	
63 63
    class Node {
64 64
      friend class ListDigraphBase;
65 65
    protected:
66 66

	
67 67
      int id;
68 68
      explicit Node(int pid) { id = pid;}
69 69

	
70 70
    public:
71 71
      Node() {}
72 72
      Node (Invalid) { id = -1; }
73 73
      bool operator==(const Node& node) const {return id == node.id;}
74 74
      bool operator!=(const Node& node) const {return id != node.id;}
75 75
      bool operator<(const Node& node) const {return id < node.id;}
76 76
    };
77 77

	
78 78
    class Arc {
79 79
      friend class ListDigraphBase;
80 80
    protected:
81 81

	
82 82
      int id;
83 83
      explicit Arc(int pid) { id = pid;}
84 84

	
85 85
    public:
86 86
      Arc() {}
87 87
      Arc (Invalid) { id = -1; }
88 88
      bool operator==(const Arc& arc) const {return id == arc.id;}
89 89
      bool operator!=(const Arc& arc) const {return id != arc.id;}
90 90
      bool operator<(const Arc& arc) const {return id < arc.id;}
91 91
    };
92 92

	
93 93

	
94 94

	
95 95
    ListDigraphBase()
96 96
      : nodes(), first_node(-1),
97 97
        first_free_node(-1), arcs(), first_free_arc(-1) {}
98 98

	
99 99

	
100 100
    int maxNodeId() const { return nodes.size()-1; }
101 101
    int maxArcId() const { return arcs.size()-1; }
102 102

	
103 103
    Node source(Arc e) const { return Node(arcs[e.id].source); }
104 104
    Node target(Arc e) const { return Node(arcs[e.id].target); }
105 105

	
106 106

	
107 107
    void first(Node& node) const {
108 108
      node.id = first_node;
109 109
    }
110 110

	
111 111
    void next(Node& node) const {
112 112
      node.id = nodes[node.id].next;
113 113
    }
114 114

	
115 115

	
116 116
    void first(Arc& arc) const {
117 117
      int n;
118 118
      for(n = first_node;
119 119
          n!=-1 && nodes[n].first_in == -1;
120 120
          n = nodes[n].next) {}
121 121
      arc.id = (n == -1) ? -1 : nodes[n].first_in;
122 122
    }
123 123

	
124 124
    void next(Arc& arc) const {
125 125
      if (arcs[arc.id].next_in != -1) {
126 126
        arc.id = arcs[arc.id].next_in;
127 127
      } else {
128 128
        int n;
129 129
        for(n = nodes[arcs[arc.id].target].next;
130 130
            n!=-1 && nodes[n].first_in == -1;
131 131
            n = nodes[n].next) {}
132 132
        arc.id = (n == -1) ? -1 : nodes[n].first_in;
133 133
      }
134 134
    }
135 135

	
136 136
    void firstOut(Arc &e, const Node& v) const {
137 137
      e.id = nodes[v.id].first_out;
138 138
    }
139 139
    void nextOut(Arc &e) const {
140 140
      e.id=arcs[e.id].next_out;
141 141
    }
142 142

	
143 143
    void firstIn(Arc &e, const Node& v) const {
144 144
      e.id = nodes[v.id].first_in;
145 145
    }
146 146
    void nextIn(Arc &e) const {
147 147
      e.id=arcs[e.id].next_in;
148 148
    }
149 149

	
150 150

	
151 151
    static int id(Node v) { return v.id; }
152 152
    static int id(Arc e) { return e.id; }
153 153

	
154 154
    static Node nodeFromId(int id) { return Node(id);}
155 155
    static Arc arcFromId(int id) { return Arc(id);}
156 156

	
157 157
    bool valid(Node n) const {
158 158
      return n.id >= 0 && n.id < static_cast<int>(nodes.size()) &&
159 159
        nodes[n.id].prev != -2;
160 160
    }
161 161

	
162 162
    bool valid(Arc a) const {
163 163
      return a.id >= 0 && a.id < static_cast<int>(arcs.size()) &&
164 164
        arcs[a.id].prev_in != -2;
165 165
    }
166 166

	
167 167
    Node addNode() {
168 168
      int n;
169 169

	
170 170
      if(first_free_node==-1) {
171 171
        n = nodes.size();
172 172
        nodes.push_back(NodeT());
173 173
      } else {
174 174
        n = first_free_node;
175 175
        first_free_node = nodes[n].next;
176 176
      }
177 177

	
178 178
      nodes[n].next = first_node;
179 179
      if(first_node != -1) nodes[first_node].prev = n;
180 180
      first_node = n;
181 181
      nodes[n].prev = -1;
182 182

	
183 183
      nodes[n].first_in = nodes[n].first_out = -1;
184 184

	
185 185
      return Node(n);
186 186
    }
187 187

	
188 188
    Arc addArc(Node u, Node v) {
189 189
      int n;
190 190

	
191 191
      if (first_free_arc == -1) {
192 192
        n = arcs.size();
193 193
        arcs.push_back(ArcT());
194 194
      } else {
195 195
        n = first_free_arc;
196 196
        first_free_arc = arcs[n].next_in;
197 197
      }
198 198

	
199 199
      arcs[n].source = u.id;
200 200
      arcs[n].target = v.id;
201 201

	
202 202
      arcs[n].next_out = nodes[u.id].first_out;
203 203
      if(nodes[u.id].first_out != -1) {
204 204
        arcs[nodes[u.id].first_out].prev_out = n;
205 205
      }
206 206

	
207 207
      arcs[n].next_in = nodes[v.id].first_in;
208 208
      if(nodes[v.id].first_in != -1) {
209 209
        arcs[nodes[v.id].first_in].prev_in = n;
210 210
      }
211 211

	
212 212
      arcs[n].prev_in = arcs[n].prev_out = -1;
213 213

	
214 214
      nodes[u.id].first_out = nodes[v.id].first_in = n;
215 215

	
216 216
      return Arc(n);
217 217
    }
218 218

	
219 219
    void erase(const Node& node) {
220 220
      int n = node.id;
221 221

	
222 222
      if(nodes[n].next != -1) {
223 223
        nodes[nodes[n].next].prev = nodes[n].prev;
224 224
      }
225 225

	
226 226
      if(nodes[n].prev != -1) {
227 227
        nodes[nodes[n].prev].next = nodes[n].next;
228 228
      } else {
229 229
        first_node = nodes[n].next;
230 230
      }
231 231

	
232 232
      nodes[n].next = first_free_node;
233 233
      first_free_node = n;
234 234
      nodes[n].prev = -2;
235 235

	
236 236
    }
237 237

	
238 238
    void erase(const Arc& arc) {
239 239
      int n = arc.id;
240 240

	
241 241
      if(arcs[n].next_in!=-1) {
242 242
        arcs[arcs[n].next_in].prev_in = arcs[n].prev_in;
243 243
      }
244 244

	
245 245
      if(arcs[n].prev_in!=-1) {
246 246
        arcs[arcs[n].prev_in].next_in = arcs[n].next_in;
247 247
      } else {
248 248
        nodes[arcs[n].target].first_in = arcs[n].next_in;
249 249
      }
250 250

	
251 251

	
252 252
      if(arcs[n].next_out!=-1) {
253 253
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
254 254
      }
255 255

	
256 256
      if(arcs[n].prev_out!=-1) {
257 257
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
258 258
      } else {
259 259
        nodes[arcs[n].source].first_out = arcs[n].next_out;
260 260
      }
261 261

	
262 262
      arcs[n].next_in = first_free_arc;
263 263
      first_free_arc = n;
264 264
      arcs[n].prev_in = -2;
265 265
    }
266 266

	
267 267
    void clear() {
268 268
      arcs.clear();
269 269
      nodes.clear();
270 270
      first_node = first_free_node = first_free_arc = -1;
271 271
    }
272 272

	
273 273
  protected:
274 274
    void changeTarget(Arc e, Node n)
275 275
    {
276 276
      if(arcs[e.id].next_in != -1)
277 277
        arcs[arcs[e.id].next_in].prev_in = arcs[e.id].prev_in;
278 278
      if(arcs[e.id].prev_in != -1)
279 279
        arcs[arcs[e.id].prev_in].next_in = arcs[e.id].next_in;
280 280
      else nodes[arcs[e.id].target].first_in = arcs[e.id].next_in;
281 281
      if (nodes[n.id].first_in != -1) {
282 282
        arcs[nodes[n.id].first_in].prev_in = e.id;
283 283
      }
284 284
      arcs[e.id].target = n.id;
285 285
      arcs[e.id].prev_in = -1;
286 286
      arcs[e.id].next_in = nodes[n.id].first_in;
287 287
      nodes[n.id].first_in = e.id;
288 288
    }
289 289
    void changeSource(Arc e, Node n)
290 290
    {
291 291
      if(arcs[e.id].next_out != -1)
292 292
        arcs[arcs[e.id].next_out].prev_out = arcs[e.id].prev_out;
293 293
      if(arcs[e.id].prev_out != -1)
294 294
        arcs[arcs[e.id].prev_out].next_out = arcs[e.id].next_out;
295 295
      else nodes[arcs[e.id].source].first_out = arcs[e.id].next_out;
296 296
      if (nodes[n.id].first_out != -1) {
297 297
        arcs[nodes[n.id].first_out].prev_out = e.id;
298 298
      }
299 299
      arcs[e.id].source = n.id;
300 300
      arcs[e.id].prev_out = -1;
301 301
      arcs[e.id].next_out = nodes[n.id].first_out;
302 302
      nodes[n.id].first_out = e.id;
303 303
    }
304 304

	
305 305
  };
306 306

	
307 307
  typedef DigraphExtender<ListDigraphBase> ExtendedListDigraphBase;
308 308

	
309 309
  /// \addtogroup graphs
310 310
  /// @{
311 311

	
312 312
  ///A general directed graph structure.
313 313

	
314 314
  ///\ref ListDigraph is a simple and fast <em>directed graph</em>
315 315
  ///implementation based on static linked lists that are stored in
316 316
  ///\c std::vector structures.
317 317
  ///
318 318
  ///It conforms to the \ref concepts::Digraph "Digraph concept" and it
319 319
  ///also provides several useful additional functionalities.
320 320
  ///Most of the member functions and nested classes are documented
321 321
  ///only in the concept class.
322 322
  ///
323 323
  ///An important extra feature of this digraph implementation is that
324 324
  ///its maps are real \ref concepts::ReferenceMap "reference map"s.
325 325
  ///
326 326
  ///\sa concepts::Digraph
327 327

	
328 328
  class ListDigraph : public ExtendedListDigraphBase {
329 329
  private:
330 330
    ///ListDigraph is \e not copy constructible. Use copyDigraph() instead.
331 331

	
332 332
    ///ListDigraph is \e not copy constructible. Use copyDigraph() instead.
333 333
    ///
334 334
    ListDigraph(const ListDigraph &) :ExtendedListDigraphBase() {};
335 335
    ///\brief Assignment of ListDigraph to another one is \e not allowed.
336 336
    ///Use copyDigraph() instead.
337 337

	
338 338
    ///Assignment of ListDigraph to another one is \e not allowed.
339 339
    ///Use copyDigraph() instead.
340 340
    void operator=(const ListDigraph &) {}
341 341
  public:
342 342

	
343 343
    typedef ExtendedListDigraphBase Parent;
344 344

	
345 345
    /// Constructor
346 346

	
347 347
    /// Constructor.
348 348
    ///
349 349
    ListDigraph() {}
350 350

	
351 351
    ///Add a new node to the digraph.
352 352

	
353 353
    ///Add a new node to the digraph.
354 354
    ///\return the new node.
355 355
    Node addNode() { return Parent::addNode(); }
356 356

	
357 357
    ///Add a new arc to the digraph.
358 358

	
359 359
    ///Add a new arc to the digraph with source node \c s
360 360
    ///and target node \c t.
361 361
    ///\return the new arc.
362 362
    Arc addArc(const Node& s, const Node& t) {
363 363
      return Parent::addArc(s, t);
364 364
    }
365 365

	
366 366
    ///\brief Erase a node from the digraph.
367 367
    ///
368 368
    ///Erase a node from the digraph.
369 369
    ///
370 370
    void erase(const Node& n) { Parent::erase(n); }
371 371

	
372 372
    ///\brief Erase an arc from the digraph.
373 373
    ///
374 374
    ///Erase an arc from the digraph.
375 375
    ///
376 376
    void erase(const Arc& a) { Parent::erase(a); }
377 377

	
378 378
    /// Node validity check
379 379

	
380 380
    /// This function gives back true if the given node is valid,
381 381
    /// ie. it is a real node of the graph.
382 382
    ///
383 383
    /// \warning A Node pointing to a removed item
384 384
    /// could become valid again later if new nodes are
385 385
    /// added to the graph.
386 386
    bool valid(Node n) const { return Parent::valid(n); }
387 387

	
388 388
    /// Arc validity check
389 389

	
390 390
    /// This function gives back true if the given arc is valid,
391 391
    /// ie. it is a real arc of the graph.
392 392
    ///
393 393
    /// \warning An Arc pointing to a removed item
394 394
    /// could become valid again later if new nodes are
395 395
    /// added to the graph.
396 396
    bool valid(Arc a) const { return Parent::valid(a); }
397 397

	
398 398
    /// Change the target of \c a to \c n
399 399

	
400 400
    /// Change the target of \c a to \c n
401 401
    ///
402 402
    ///\note The <tt>ArcIt</tt>s and <tt>OutArcIt</tt>s referencing
403 403
    ///the changed arc remain valid. However <tt>InArcIt</tt>s are
404 404
    ///invalidated.
405 405
    ///
406 406
    ///\warning This functionality cannot be used together with the Snapshot
407 407
    ///feature.
408 408
    void changeTarget(Arc a, Node n) {
409 409
      Parent::changeTarget(a,n);
410 410
    }
411 411
    /// Change the source of \c a to \c n
412 412

	
413 413
    /// Change the source of \c a to \c n
414 414
    ///
415 415
    ///\note The <tt>InArcIt</tt>s referencing the changed arc remain
416
    ///valid. However the <tt>ArcIt<tt>s and <tt>OutArcIt</tt>s are
416
    ///valid. However the <tt>ArcIt</tt>s and <tt>OutArcIt</tt>s are
417 417
    ///invalidated.
418 418
    ///
419 419
    ///\warning This functionality cannot be used together with the Snapshot
420 420
    ///feature.
421 421
    void changeSource(Arc a, Node n) {
422 422
      Parent::changeSource(a,n);
423 423
    }
424 424

	
425 425
    /// Invert the direction of an arc.
426 426

	
427 427
    ///\note The <tt>ArcIt</tt>s referencing the changed arc remain
428 428
    ///valid. However <tt>OutArcIt</tt>s and <tt>InArcIt</tt>s are
429 429
    ///invalidated.
430 430
    ///
431 431
    ///\warning This functionality cannot be used together with the Snapshot
432 432
    ///feature.
433 433
    void reverseArc(Arc e) {
434 434
      Node t=target(e);
435 435
      changeTarget(e,source(e));
436 436
      changeSource(e,t);
437 437
    }
438 438

	
439 439
    /// Reserve memory for nodes.
440 440

	
441 441
    /// Using this function it is possible to avoid the superfluous memory
442 442
    /// allocation: if you know that the digraph you want to build will
443 443
    /// be very large (e.g. it will contain millions of nodes and/or arcs)
444 444
    /// then it is worth reserving space for this amount before starting
445 445
    /// to build the digraph.
446 446
    /// \sa reserveArc
447 447
    void reserveNode(int n) { nodes.reserve(n); };
448 448

	
449 449
    /// Reserve memory for arcs.
450 450

	
451 451
    /// Using this function it is possible to avoid the superfluous memory
452 452
    /// allocation: if you know that the digraph you want to build will
453 453
    /// be very large (e.g. it will contain millions of nodes and/or arcs)
454 454
    /// then it is worth reserving space for this amount before starting
455 455
    /// to build the digraph.
456 456
    /// \sa reserveNode
457 457
    void reserveArc(int m) { arcs.reserve(m); };
458 458

	
459 459
    ///Contract two nodes.
460 460

	
461 461
    ///This function contracts two nodes.
462 462
    ///Node \p b will be removed but instead of deleting
463 463
    ///incident arcs, they will be joined to \p a.
464 464
    ///The last parameter \p r controls whether to remove loops. \c true
465 465
    ///means that loops will be removed.
466 466
    ///
467 467
    ///\note The <tt>ArcIt</tt>s referencing a moved arc remain
468 468
    ///valid. However <tt>InArcIt</tt>s and <tt>OutArcIt</tt>s
469 469
    ///may be invalidated.
470 470
    ///
471 471
    ///\warning This functionality cannot be used together with the Snapshot
472 472
    ///feature.
473 473
    void contract(Node a, Node b, bool r = true)
474 474
    {
475 475
      for(OutArcIt e(*this,b);e!=INVALID;) {
476 476
        OutArcIt f=e;
477 477
        ++f;
478 478
        if(r && target(e)==a) erase(e);
479 479
        else changeSource(e,a);
480 480
        e=f;
481 481
      }
482 482
      for(InArcIt e(*this,b);e!=INVALID;) {
483 483
        InArcIt f=e;
484 484
        ++f;
485 485
        if(r && source(e)==a) erase(e);
486 486
        else changeTarget(e,a);
487 487
        e=f;
488 488
      }
489 489
      erase(b);
490 490
    }
491 491

	
492 492
    ///Split a node.
493 493

	
494 494
    ///This function splits a node. First a new node is added to the digraph,
495 495
    ///then the source of each outgoing arc of \c n is moved to this new node.
496 496
    ///If \c connect is \c true (this is the default value), then a new arc
497 497
    ///from \c n to the newly created node is also added.
498 498
    ///\return The newly created node.
499 499
    ///
500 500
    ///\note The <tt>ArcIt</tt>s referencing a moved arc remain
501 501
    ///valid. However <tt>InArcIt</tt>s and <tt>OutArcIt</tt>s may
502 502
    ///be invalidated.
503 503
    ///
504 504
    ///\warning This functionality cannot be used in conjunction with the
505 505
    ///Snapshot feature.
506 506
    Node split(Node n, bool connect = true) {
507 507
      Node b = addNode();
508 508
      for(OutArcIt e(*this,n);e!=INVALID;) {
509 509
        OutArcIt f=e;
510 510
        ++f;
511 511
        changeSource(e,b);
512 512
        e=f;
513 513
      }
514 514
      if (connect) addArc(n,b);
515 515
      return b;
516 516
    }
517 517

	
518 518
    ///Split an arc.
519 519

	
520 520
    ///This function splits an arc. First a new node \c b is added to
521 521
    ///the digraph, then the original arc is re-targeted to \c
522 522
    ///b. Finally an arc from \c b to the original target is added.
523 523
    ///
524 524
    ///\return The newly created node.
525 525
    ///
526 526
    ///\warning This functionality cannot be used together with the
527 527
    ///Snapshot feature.
528 528
    Node split(Arc e) {
529 529
      Node b = addNode();
530 530
      addArc(b,target(e));
531 531
      changeTarget(e,b);
532 532
      return b;
533 533
    }
534 534

	
535 535
    /// \brief Class to make a snapshot of the digraph and restore
536 536
    /// it later.
537 537
    ///
538 538
    /// Class to make a snapshot of the digraph and restore it later.
539 539
    ///
540 540
    /// The newly added nodes and arcs can be removed using the
541 541
    /// restore() function.
542 542
    ///
543 543
    /// \warning Arc and node deletions and other modifications (e.g.
544 544
    /// contracting, splitting, reversing arcs or nodes) cannot be
545 545
    /// restored. These events invalidate the snapshot.
546 546
    class Snapshot {
547 547
    protected:
548 548

	
549 549
      typedef Parent::NodeNotifier NodeNotifier;
550 550

	
551 551
      class NodeObserverProxy : public NodeNotifier::ObserverBase {
552 552
      public:
553 553

	
554 554
        NodeObserverProxy(Snapshot& _snapshot)
555 555
          : snapshot(_snapshot) {}
556 556

	
557 557
        using NodeNotifier::ObserverBase::attach;
558 558
        using NodeNotifier::ObserverBase::detach;
559 559
        using NodeNotifier::ObserverBase::attached;
560 560

	
561 561
      protected:
562 562

	
563 563
        virtual void add(const Node& node) {
564 564
          snapshot.addNode(node);
565 565
        }
566 566
        virtual void add(const std::vector<Node>& nodes) {
567 567
          for (int i = nodes.size() - 1; i >= 0; ++i) {
568 568
            snapshot.addNode(nodes[i]);
569 569
          }
570 570
        }
571 571
        virtual void erase(const Node& node) {
572 572
          snapshot.eraseNode(node);
573 573
        }
574 574
        virtual void erase(const std::vector<Node>& nodes) {
575 575
          for (int i = 0; i < int(nodes.size()); ++i) {
576 576
            snapshot.eraseNode(nodes[i]);
577 577
          }
578 578
        }
579 579
        virtual void build() {
580 580
          Node node;
581 581
          std::vector<Node> nodes;
582 582
          for (notifier()->first(node); node != INVALID;
583 583
               notifier()->next(node)) {
584 584
            nodes.push_back(node);
585 585
          }
586 586
          for (int i = nodes.size() - 1; i >= 0; --i) {
587 587
            snapshot.addNode(nodes[i]);
588 588
          }
589 589
        }
590 590
        virtual void clear() {
591 591
          Node node;
592 592
          for (notifier()->first(node); node != INVALID;
593 593
               notifier()->next(node)) {
594 594
            snapshot.eraseNode(node);
595 595
          }
596 596
        }
597 597

	
598 598
        Snapshot& snapshot;
599 599
      };
600 600

	
601 601
      class ArcObserverProxy : public ArcNotifier::ObserverBase {
602 602
      public:
603 603

	
604 604
        ArcObserverProxy(Snapshot& _snapshot)
605 605
          : snapshot(_snapshot) {}
606 606

	
607 607
        using ArcNotifier::ObserverBase::attach;
608 608
        using ArcNotifier::ObserverBase::detach;
609 609
        using ArcNotifier::ObserverBase::attached;
610 610

	
611 611
      protected:
612 612

	
613 613
        virtual void add(const Arc& arc) {
614 614
          snapshot.addArc(arc);
615 615
        }
616 616
        virtual void add(const std::vector<Arc>& arcs) {
617 617
          for (int i = arcs.size() - 1; i >= 0; ++i) {
618 618
            snapshot.addArc(arcs[i]);
619 619
          }
620 620
        }
621 621
        virtual void erase(const Arc& arc) {
622 622
          snapshot.eraseArc(arc);
623 623
        }
624 624
        virtual void erase(const std::vector<Arc>& arcs) {
625 625
          for (int i = 0; i < int(arcs.size()); ++i) {
626 626
            snapshot.eraseArc(arcs[i]);
627 627
          }
628 628
        }
629 629
        virtual void build() {
630 630
          Arc arc;
631 631
          std::vector<Arc> arcs;
632 632
          for (notifier()->first(arc); arc != INVALID;
633 633
               notifier()->next(arc)) {
634 634
            arcs.push_back(arc);
635 635
          }
636 636
          for (int i = arcs.size() - 1; i >= 0; --i) {
637 637
            snapshot.addArc(arcs[i]);
638 638
          }
639 639
        }
640 640
        virtual void clear() {
641 641
          Arc arc;
642 642
          for (notifier()->first(arc); arc != INVALID;
643 643
               notifier()->next(arc)) {
644 644
            snapshot.eraseArc(arc);
645 645
          }
646 646
        }
647 647

	
648 648
        Snapshot& snapshot;
649 649
      };
650 650

	
651 651
      ListDigraph *digraph;
652 652

	
653 653
      NodeObserverProxy node_observer_proxy;
654 654
      ArcObserverProxy arc_observer_proxy;
655 655

	
656 656
      std::list<Node> added_nodes;
657 657
      std::list<Arc> added_arcs;
658 658

	
659 659

	
660 660
      void addNode(const Node& node) {
661 661
        added_nodes.push_front(node);
662 662
      }
663 663
      void eraseNode(const Node& node) {
664 664
        std::list<Node>::iterator it =
665 665
          std::find(added_nodes.begin(), added_nodes.end(), node);
666 666
        if (it == added_nodes.end()) {
667 667
          clear();
668 668
          arc_observer_proxy.detach();
669 669
          throw NodeNotifier::ImmediateDetach();
670 670
        } else {
671 671
          added_nodes.erase(it);
672 672
        }
673 673
      }
674 674

	
675 675
      void addArc(const Arc& arc) {
676 676
        added_arcs.push_front(arc);
677 677
      }
678 678
      void eraseArc(const Arc& arc) {
679 679
        std::list<Arc>::iterator it =
680 680
          std::find(added_arcs.begin(), added_arcs.end(), arc);
681 681
        if (it == added_arcs.end()) {
682 682
          clear();
683 683
          node_observer_proxy.detach();
684 684
          throw ArcNotifier::ImmediateDetach();
685 685
        } else {
686 686
          added_arcs.erase(it);
687 687
        }
688 688
      }
689 689

	
690 690
      void attach(ListDigraph &_digraph) {
691 691
        digraph = &_digraph;
692 692
        node_observer_proxy.attach(digraph->notifier(Node()));
693 693
        arc_observer_proxy.attach(digraph->notifier(Arc()));
694 694
      }
695 695

	
696 696
      void detach() {
697 697
        node_observer_proxy.detach();
698 698
        arc_observer_proxy.detach();
699 699
      }
700 700

	
701 701
      bool attached() const {
702 702
        return node_observer_proxy.attached();
703 703
      }
704 704

	
705 705
      void clear() {
706 706
        added_nodes.clear();
707 707
        added_arcs.clear();
708 708
      }
709 709

	
710 710
    public:
711 711

	
712 712
      /// \brief Default constructor.
713 713
      ///
714 714
      /// Default constructor.
715 715
      /// To actually make a snapshot you must call save().
716 716
      Snapshot()
717 717
        : digraph(0), node_observer_proxy(*this),
718 718
          arc_observer_proxy(*this) {}
719 719

	
720 720
      /// \brief Constructor that immediately makes a snapshot.
721 721
      ///
722 722
      /// This constructor immediately makes a snapshot of the digraph.
723 723
      /// \param _digraph The digraph we make a snapshot of.
724 724
      Snapshot(ListDigraph &_digraph)
725 725
        : node_observer_proxy(*this),
726 726
          arc_observer_proxy(*this) {
727 727
        attach(_digraph);
728 728
      }
729 729

	
730 730
      /// \brief Make a snapshot.
731 731
      ///
732 732
      /// Make a snapshot of the digraph.
733 733
      ///
734 734
      /// This function can be called more than once. In case of a repeated
735 735
      /// call, the previous snapshot gets lost.
736 736
      /// \param _digraph The digraph we make the snapshot of.
737 737
      void save(ListDigraph &_digraph) {
738 738
        if (attached()) {
739 739
          detach();
740 740
          clear();
741 741
        }
742 742
        attach(_digraph);
743 743
      }
744 744

	
745 745
      /// \brief Undo the changes until the last snapshot.
746 746
      //
747 747
      /// Undo the changes until the last snapshot created by save().
748 748
      void restore() {
749 749
        detach();
750 750
        for(std::list<Arc>::iterator it = added_arcs.begin();
751 751
            it != added_arcs.end(); ++it) {
752 752
          digraph->erase(*it);
753 753
        }
754 754
        for(std::list<Node>::iterator it = added_nodes.begin();
755 755
            it != added_nodes.end(); ++it) {
756 756
          digraph->erase(*it);
757 757
        }
758 758
        clear();
759 759
      }
760 760

	
761 761
      /// \brief Gives back true when the snapshot is valid.
762 762
      ///
763 763
      /// Gives back true when the snapshot is valid.
764 764
      bool valid() const {
765 765
        return attached();
766 766
      }
767 767
    };
768 768

	
769 769
  };
770 770

	
771 771
  ///@}
772 772

	
773 773
  class ListGraphBase {
774 774

	
775 775
  protected:
776 776

	
777 777
    struct NodeT {
778 778
      int first_out;
779 779
      int prev, next;
780 780
    };
781 781

	
782 782
    struct ArcT {
783 783
      int target;
784 784
      int prev_out, next_out;
785 785
    };
786 786

	
787 787
    std::vector<NodeT> nodes;
788 788

	
789 789
    int first_node;
790 790

	
791 791
    int first_free_node;
792 792

	
793 793
    std::vector<ArcT> arcs;
794 794

	
795 795
    int first_free_arc;
796 796

	
797 797
  public:
798 798

	
799 799
    typedef ListGraphBase Digraph;
800 800

	
801 801
    class Node;
802 802
    class Arc;
803 803
    class Edge;
804 804

	
805 805
    class Node {
806 806
      friend class ListGraphBase;
807 807
    protected:
808 808

	
809 809
      int id;
810 810
      explicit Node(int pid) { id = pid;}
811 811

	
812 812
    public:
813 813
      Node() {}
814 814
      Node (Invalid) { id = -1; }
815 815
      bool operator==(const Node& node) const {return id == node.id;}
816 816
      bool operator!=(const Node& node) const {return id != node.id;}
817 817
      bool operator<(const Node& node) const {return id < node.id;}
818 818
    };
819 819

	
820 820
    class Edge {
821 821
      friend class ListGraphBase;
822 822
    protected:
823 823

	
824 824
      int id;
825 825
      explicit Edge(int pid) { id = pid;}
826 826

	
827 827
    public:
828 828
      Edge() {}
829 829
      Edge (Invalid) { id = -1; }
830 830
      bool operator==(const Edge& edge) const {return id == edge.id;}
831 831
      bool operator!=(const Edge& edge) const {return id != edge.id;}
832 832
      bool operator<(const Edge& edge) const {return id < edge.id;}
833 833
    };
834 834

	
835 835
    class Arc {
836 836
      friend class ListGraphBase;
837 837
    protected:
838 838

	
839 839
      int id;
840 840
      explicit Arc(int pid) { id = pid;}
841 841

	
842 842
    public:
843 843
      operator Edge() const { 
844 844
        return id != -1 ? edgeFromId(id / 2) : INVALID; 
845 845
      }
846 846

	
847 847
      Arc() {}
848 848
      Arc (Invalid) { id = -1; }
849 849
      bool operator==(const Arc& arc) const {return id == arc.id;}
850 850
      bool operator!=(const Arc& arc) const {return id != arc.id;}
851 851
      bool operator<(const Arc& arc) const {return id < arc.id;}
852 852
    };
853 853

	
854 854

	
855 855

	
856 856
    ListGraphBase()
857 857
      : nodes(), first_node(-1),
858 858
        first_free_node(-1), arcs(), first_free_arc(-1) {}
859 859

	
860 860

	
861 861
    int maxNodeId() const { return nodes.size()-1; }
862 862
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
863 863
    int maxArcId() const { return arcs.size()-1; }
864 864

	
865 865
    Node source(Arc e) const { return Node(arcs[e.id ^ 1].target); }
866 866
    Node target(Arc e) const { return Node(arcs[e.id].target); }
867 867

	
868 868
    Node u(Edge e) const { return Node(arcs[2 * e.id].target); }
869 869
    Node v(Edge e) const { return Node(arcs[2 * e.id + 1].target); }
870 870

	
871 871
    static bool direction(Arc e) {
872 872
      return (e.id & 1) == 1;
873 873
    }
874 874

	
875 875
    static Arc direct(Edge e, bool d) {
876 876
      return Arc(e.id * 2 + (d ? 1 : 0));
877 877
    }
878 878

	
879 879
    void first(Node& node) const {
880 880
      node.id = first_node;
881 881
    }
882 882

	
883 883
    void next(Node& node) const {
884 884
      node.id = nodes[node.id].next;
885 885
    }
886 886

	
887 887
    void first(Arc& e) const {
888 888
      int n = first_node;
889 889
      while (n != -1 && nodes[n].first_out == -1) {
890 890
        n = nodes[n].next;
891 891
      }
892 892
      e.id = (n == -1) ? -1 : nodes[n].first_out;
893 893
    }
894 894

	
895 895
    void next(Arc& e) const {
896 896
      if (arcs[e.id].next_out != -1) {
897 897
        e.id = arcs[e.id].next_out;
898 898
      } else {
899 899
        int n = nodes[arcs[e.id ^ 1].target].next;
900 900
        while(n != -1 && nodes[n].first_out == -1) {
901 901
          n = nodes[n].next;
902 902
        }
903 903
        e.id = (n == -1) ? -1 : nodes[n].first_out;
904 904
      }
905 905
    }
906 906

	
907 907
    void first(Edge& e) const {
908 908
      int n = first_node;
909 909
      while (n != -1) {
910 910
        e.id = nodes[n].first_out;
911 911
        while ((e.id & 1) != 1) {
912 912
          e.id = arcs[e.id].next_out;
913 913
        }
914 914
        if (e.id != -1) {
915 915
          e.id /= 2;
916 916
          return;
917 917
        }
918 918
        n = nodes[n].next;
919 919
      }
920 920
      e.id = -1;
921 921
    }
922 922

	
923 923
    void next(Edge& e) const {
924 924
      int n = arcs[e.id * 2].target;
925 925
      e.id = arcs[(e.id * 2) | 1].next_out;
926 926
      while ((e.id & 1) != 1) {
927 927
        e.id = arcs[e.id].next_out;
928 928
      }
929 929
      if (e.id != -1) {
930 930
        e.id /= 2;
931 931
        return;
932 932
      }
933 933
      n = nodes[n].next;
934 934
      while (n != -1) {
935 935
        e.id = nodes[n].first_out;
936 936
        while ((e.id & 1) != 1) {
937 937
          e.id = arcs[e.id].next_out;
938 938
        }
939 939
        if (e.id != -1) {
940 940
          e.id /= 2;
941 941
          return;
942 942
        }
943 943
        n = nodes[n].next;
944 944
      }
945 945
      e.id = -1;
946 946
    }
947 947

	
948 948
    void firstOut(Arc &e, const Node& v) const {
949 949
      e.id = nodes[v.id].first_out;
950 950
    }
951 951
    void nextOut(Arc &e) const {
952 952
      e.id = arcs[e.id].next_out;
953 953
    }
954 954

	
955 955
    void firstIn(Arc &e, const Node& v) const {
956 956
      e.id = ((nodes[v.id].first_out) ^ 1);
957 957
      if (e.id == -2) e.id = -1;
958 958
    }
959 959
    void nextIn(Arc &e) const {
960 960
      e.id = ((arcs[e.id ^ 1].next_out) ^ 1);
961 961
      if (e.id == -2) e.id = -1;
962 962
    }
963 963

	
964 964
    void firstInc(Edge &e, bool& d, const Node& v) const {
965 965
      int a = nodes[v.id].first_out;
966 966
      if (a != -1 ) {
967 967
        e.id = a / 2;
968 968
        d = ((a & 1) == 1);
969 969
      } else {
970 970
        e.id = -1;
971 971
        d = true;
972 972
      }
973 973
    }
974 974
    void nextInc(Edge &e, bool& d) const {
975 975
      int a = (arcs[(e.id * 2) | (d ? 1 : 0)].next_out);
976 976
      if (a != -1 ) {
977 977
        e.id = a / 2;
978 978
        d = ((a & 1) == 1);
979 979
      } else {
980 980
        e.id = -1;
981 981
        d = true;
982 982
      }
983 983
    }
984 984

	
985 985
    static int id(Node v) { return v.id; }
986 986
    static int id(Arc e) { return e.id; }
987 987
    static int id(Edge e) { return e.id; }
988 988

	
989 989
    static Node nodeFromId(int id) { return Node(id);}
990 990
    static Arc arcFromId(int id) { return Arc(id);}
991 991
    static Edge edgeFromId(int id) { return Edge(id);}
992 992

	
993 993
    bool valid(Node n) const {
994 994
      return n.id >= 0 && n.id < static_cast<int>(nodes.size()) &&
995 995
        nodes[n.id].prev != -2;
996 996
    }
997 997

	
998 998
    bool valid(Arc a) const {
999 999
      return a.id >= 0 && a.id < static_cast<int>(arcs.size()) &&
1000 1000
        arcs[a.id].prev_out != -2;
1001 1001
    }
1002 1002

	
1003 1003
    bool valid(Edge e) const {
1004 1004
      return e.id >= 0 && 2 * e.id < static_cast<int>(arcs.size()) &&
1005 1005
        arcs[2 * e.id].prev_out != -2;
1006 1006
    }
1007 1007

	
1008 1008
    Node addNode() {
1009 1009
      int n;
1010 1010

	
1011 1011
      if(first_free_node==-1) {
1012 1012
        n = nodes.size();
1013 1013
        nodes.push_back(NodeT());
1014 1014
      } else {
1015 1015
        n = first_free_node;
1016 1016
        first_free_node = nodes[n].next;
1017 1017
      }
1018 1018

	
1019 1019
      nodes[n].next = first_node;
1020 1020
      if (first_node != -1) nodes[first_node].prev = n;
1021 1021
      first_node = n;
1022 1022
      nodes[n].prev = -1;
1023 1023

	
1024 1024
      nodes[n].first_out = -1;
1025 1025

	
1026 1026
      return Node(n);
1027 1027
    }
1028 1028

	
1029 1029
    Edge addEdge(Node u, Node v) {
1030 1030
      int n;
1031 1031

	
1032 1032
      if (first_free_arc == -1) {
1033 1033
        n = arcs.size();
1034 1034
        arcs.push_back(ArcT());
1035 1035
        arcs.push_back(ArcT());
1036 1036
      } else {
1037 1037
        n = first_free_arc;
1038 1038
        first_free_arc = arcs[n].next_out;
1039 1039
      }
1040 1040

	
1041 1041
      arcs[n].target = u.id;
1042 1042
      arcs[n | 1].target = v.id;
1043 1043

	
1044 1044
      arcs[n].next_out = nodes[v.id].first_out;
1045 1045
      if (nodes[v.id].first_out != -1) {
1046 1046
        arcs[nodes[v.id].first_out].prev_out = n;
1047 1047
      }
1048 1048
      arcs[n].prev_out = -1;
1049 1049
      nodes[v.id].first_out = n;
1050 1050

	
1051 1051
      arcs[n | 1].next_out = nodes[u.id].first_out;
1052 1052
      if (nodes[u.id].first_out != -1) {
1053 1053
        arcs[nodes[u.id].first_out].prev_out = (n | 1);
1054 1054
      }
1055 1055
      arcs[n | 1].prev_out = -1;
1056 1056
      nodes[u.id].first_out = (n | 1);
1057 1057

	
1058 1058
      return Edge(n / 2);
1059 1059
    }
1060 1060

	
1061 1061
    void erase(const Node& node) {
1062 1062
      int n = node.id;
1063 1063

	
1064 1064
      if(nodes[n].next != -1) {
1065 1065
        nodes[nodes[n].next].prev = nodes[n].prev;
1066 1066
      }
1067 1067

	
1068 1068
      if(nodes[n].prev != -1) {
1069 1069
        nodes[nodes[n].prev].next = nodes[n].next;
1070 1070
      } else {
1071 1071
        first_node = nodes[n].next;
1072 1072
      }
1073 1073

	
1074 1074
      nodes[n].next = first_free_node;
1075 1075
      first_free_node = n;
1076 1076
      nodes[n].prev = -2;
1077 1077
    }
1078 1078

	
1079 1079
    void erase(const Edge& edge) {
1080 1080
      int n = edge.id * 2;
1081 1081

	
1082 1082
      if (arcs[n].next_out != -1) {
1083 1083
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
1084 1084
      }
1085 1085

	
1086 1086
      if (arcs[n].prev_out != -1) {
1087 1087
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
1088 1088
      } else {
1089 1089
        nodes[arcs[n | 1].target].first_out = arcs[n].next_out;
1090 1090
      }
1091 1091

	
1092 1092
      if (arcs[n | 1].next_out != -1) {
1093 1093
        arcs[arcs[n | 1].next_out].prev_out = arcs[n | 1].prev_out;
1094 1094
      }
1095 1095

	
1096 1096
      if (arcs[n | 1].prev_out != -1) {
1097 1097
        arcs[arcs[n | 1].prev_out].next_out = arcs[n | 1].next_out;
1098 1098
      } else {
1099 1099
        nodes[arcs[n].target].first_out = arcs[n | 1].next_out;
1100 1100
      }
1101 1101

	
1102 1102
      arcs[n].next_out = first_free_arc;
1103 1103
      first_free_arc = n;
1104 1104
      arcs[n].prev_out = -2;
1105 1105
      arcs[n | 1].prev_out = -2;
1106 1106

	
1107 1107
    }
1108 1108

	
1109 1109
    void clear() {
1110 1110
      arcs.clear();
1111 1111
      nodes.clear();
1112 1112
      first_node = first_free_node = first_free_arc = -1;
1113 1113
    }
1114 1114

	
1115 1115
  protected:
1116 1116

	
1117 1117
    void changeV(Edge e, Node n) {
1118 1118
      if(arcs[2 * e.id].next_out != -1) {
1119 1119
        arcs[arcs[2 * e.id].next_out].prev_out = arcs[2 * e.id].prev_out;
1120 1120
      }
1121 1121
      if(arcs[2 * e.id].prev_out != -1) {
1122 1122
        arcs[arcs[2 * e.id].prev_out].next_out =
1123 1123
          arcs[2 * e.id].next_out;
1124 1124
      } else {
1125 1125
        nodes[arcs[(2 * e.id) | 1].target].first_out =
1126 1126
          arcs[2 * e.id].next_out;
1127 1127
      }
1128 1128

	
1129 1129
      if (nodes[n.id].first_out != -1) {
1130 1130
        arcs[nodes[n.id].first_out].prev_out = 2 * e.id;
1131 1131
      }
1132 1132
      arcs[(2 * e.id) | 1].target = n.id;
1133 1133
      arcs[2 * e.id].prev_out = -1;
1134 1134
      arcs[2 * e.id].next_out = nodes[n.id].first_out;
1135 1135
      nodes[n.id].first_out = 2 * e.id;
1136 1136
    }
1137 1137

	
1138 1138
    void changeU(Edge e, Node n) {
1139 1139
      if(arcs[(2 * e.id) | 1].next_out != -1) {
1140 1140
        arcs[arcs[(2 * e.id) | 1].next_out].prev_out =
1141 1141
          arcs[(2 * e.id) | 1].prev_out;
1142 1142
      }
1143 1143
      if(arcs[(2 * e.id) | 1].prev_out != -1) {
1144 1144
        arcs[arcs[(2 * e.id) | 1].prev_out].next_out =
1145 1145
          arcs[(2 * e.id) | 1].next_out;
1146 1146
      } else {
1147 1147
        nodes[arcs[2 * e.id].target].first_out =
1148 1148
          arcs[(2 * e.id) | 1].next_out;
1149 1149
      }
1150 1150

	
1151 1151
      if (nodes[n.id].first_out != -1) {
1152 1152
        arcs[nodes[n.id].first_out].prev_out = ((2 * e.id) | 1);
1153 1153
      }
1154 1154
      arcs[2 * e.id].target = n.id;
1155 1155
      arcs[(2 * e.id) | 1].prev_out = -1;
1156 1156
      arcs[(2 * e.id) | 1].next_out = nodes[n.id].first_out;
1157 1157
      nodes[n.id].first_out = ((2 * e.id) | 1);
1158 1158
    }
1159 1159

	
1160 1160
  };
1161 1161

	
1162 1162
  typedef GraphExtender<ListGraphBase> ExtendedListGraphBase;
1163 1163

	
1164 1164

	
1165 1165
  /// \addtogroup graphs
1166 1166
  /// @{
1167 1167

	
1168 1168
  ///A general undirected graph structure.
1169 1169

	
1170 1170
  ///\ref ListGraph is a simple and fast <em>undirected graph</em>
1171 1171
  ///implementation based on static linked lists that are stored in
1172 1172
  ///\c std::vector structures.
1173 1173
  ///
1174 1174
  ///It conforms to the \ref concepts::Graph "Graph concept" and it
1175 1175
  ///also provides several useful additional functionalities.
1176 1176
  ///Most of the member functions and nested classes are documented
1177 1177
  ///only in the concept class.
1178 1178
  ///
1179 1179
  ///An important extra feature of this graph implementation is that
1180 1180
  ///its maps are real \ref concepts::ReferenceMap "reference map"s.
1181 1181
  ///
1182 1182
  ///\sa concepts::Graph
1183 1183

	
1184 1184
  class ListGraph : public ExtendedListGraphBase {
1185 1185
  private:
1186 1186
    ///ListGraph is \e not copy constructible. Use copyGraph() instead.
1187 1187

	
1188 1188
    ///ListGraph is \e not copy constructible. Use copyGraph() instead.
1189 1189
    ///
1190 1190
    ListGraph(const ListGraph &) :ExtendedListGraphBase()  {};
1191 1191
    ///\brief Assignment of ListGraph to another one is \e not allowed.
1192 1192
    ///Use copyGraph() instead.
1193 1193

	
1194 1194
    ///Assignment of ListGraph to another one is \e not allowed.
1195 1195
    ///Use copyGraph() instead.
1196 1196
    void operator=(const ListGraph &) {}
1197 1197
  public:
1198 1198
    /// Constructor
1199 1199

	
1200 1200
    /// Constructor.
1201 1201
    ///
1202 1202
    ListGraph() {}
1203 1203

	
1204 1204
    typedef ExtendedListGraphBase Parent;
1205 1205

	
1206 1206
    typedef Parent::OutArcIt IncEdgeIt;
1207 1207

	
1208 1208
    /// \brief Add a new node to the graph.
1209 1209
    ///
1210 1210
    /// Add a new node to the graph.
1211 1211
    /// \return the new node.
1212 1212
    Node addNode() { return Parent::addNode(); }
1213 1213

	
1214 1214
    /// \brief Add a new edge to the graph.
1215 1215
    ///
1216 1216
    /// Add a new edge to the graph with source node \c s
1217 1217
    /// and target node \c t.
1218 1218
    /// \return the new edge.
1219 1219
    Edge addEdge(const Node& s, const Node& t) {
1220 1220
      return Parent::addEdge(s, t);
1221 1221
    }
1222 1222

	
1223 1223
    /// \brief Erase a node from the graph.
1224 1224
    ///
1225 1225
    /// Erase a node from the graph.
1226 1226
    ///
1227 1227
    void erase(const Node& n) { Parent::erase(n); }
1228 1228

	
1229 1229
    /// \brief Erase an edge from the graph.
1230 1230
    ///
1231 1231
    /// Erase an edge from the graph.
1232 1232
    ///
1233 1233
    void erase(const Edge& e) { Parent::erase(e); }
1234 1234
    /// Node validity check
1235 1235

	
1236 1236
    /// This function gives back true if the given node is valid,
1237 1237
    /// ie. it is a real node of the graph.
1238 1238
    ///
1239 1239
    /// \warning A Node pointing to a removed item
1240 1240
    /// could become valid again later if new nodes are
1241 1241
    /// added to the graph.
1242 1242
    bool valid(Node n) const { return Parent::valid(n); }
1243 1243
    /// Arc validity check
1244 1244

	
1245 1245
    /// This function gives back true if the given arc is valid,
1246 1246
    /// ie. it is a real arc of the graph.
1247 1247
    ///
1248 1248
    /// \warning An Arc pointing to a removed item
1249 1249
    /// could become valid again later if new edges are
1250 1250
    /// added to the graph.
1251 1251
    bool valid(Arc a) const { return Parent::valid(a); }
1252 1252
    /// Edge validity check
1253 1253

	
1254 1254
    /// This function gives back true if the given edge is valid,
1255 1255
    /// ie. it is a real arc of the graph.
1256 1256
    ///
1257 1257
    /// \warning A Edge pointing to a removed item
1258 1258
    /// could become valid again later if new edges are
1259 1259
    /// added to the graph.
1260 1260
    bool valid(Edge e) const { return Parent::valid(e); }
1261 1261
    /// \brief Change the end \c u of \c e to \c n
1262 1262
    ///
1263 1263
    /// This function changes the end \c u of \c e to node \c n.
1264 1264
    ///
1265 1265
    ///\note The <tt>EdgeIt</tt>s and <tt>ArcIt</tt>s referencing the
1266 1266
    ///changed edge are invalidated and if the changed node is the
1267 1267
    ///base node of an iterator then this iterator is also
1268 1268
    ///invalidated.
1269 1269
    ///
1270 1270
    ///\warning This functionality cannot be used together with the
1271 1271
    ///Snapshot feature.
1272 1272
    void changeU(Edge e, Node n) {
1273 1273
      Parent::changeU(e,n);
1274 1274
    }
1275 1275
    /// \brief Change the end \c v of \c e to \c n
1276 1276
    ///
1277 1277
    /// This function changes the end \c v of \c e to \c n.
1278 1278
    ///
1279 1279
    ///\note The <tt>EdgeIt</tt>s referencing the changed edge remain
1280 1280
    ///valid, however <tt>ArcIt</tt>s and if the changed node is the
1281 1281
    ///base node of an iterator then this iterator is invalidated.
1282 1282
    ///
1283 1283
    ///\warning This functionality cannot be used together with the
1284 1284
    ///Snapshot feature.
1285 1285
    void changeV(Edge e, Node n) {
1286 1286
      Parent::changeV(e,n);
1287 1287
    }
1288 1288
    /// \brief Contract two nodes.
1289 1289
    ///
1290 1290
    /// This function contracts two nodes.
1291 1291
    /// Node \p b will be removed but instead of deleting
1292 1292
    /// its neighboring arcs, they will be joined to \p a.
1293 1293
    /// The last parameter \p r controls whether to remove loops. \c true
1294 1294
    /// means that loops will be removed.
1295 1295
    ///
1296 1296
    /// \note The <tt>ArcIt</tt>s referencing a moved arc remain
1297 1297
    /// valid.
1298 1298
    ///
1299 1299
    ///\warning This functionality cannot be used together with the
1300 1300
    ///Snapshot feature.
1301 1301
    void contract(Node a, Node b, bool r = true) {
1302 1302
      for(IncEdgeIt e(*this, b); e!=INVALID;) {
1303 1303
        IncEdgeIt f = e; ++f;
1304 1304
        if (r && runningNode(e) == a) {
1305 1305
          erase(e);
1306 1306
        } else if (u(e) == b) {
1307 1307
          changeU(e, a);
1308 1308
        } else {
1309 1309
          changeV(e, a);
1310 1310
        }
1311 1311
        e = f;
1312 1312
      }
1313 1313
      erase(b);
1314 1314
    }
1315 1315

	
1316 1316

	
1317 1317
    /// \brief Class to make a snapshot of the graph and restore
1318 1318
    /// it later.
1319 1319
    ///
1320 1320
    /// Class to make a snapshot of the graph and restore it later.
1321 1321
    ///
1322 1322
    /// The newly added nodes and edges can be removed
1323 1323
    /// using the restore() function.
1324 1324
    ///
1325 1325
    /// \warning Edge and node deletions and other modifications
1326 1326
    /// (e.g. changing nodes of edges, contracting nodes) cannot be
1327 1327
    /// restored. These events invalidate the snapshot.
1328 1328
    class Snapshot {
1329 1329
    protected:
1330 1330

	
1331 1331
      typedef Parent::NodeNotifier NodeNotifier;
1332 1332

	
1333 1333
      class NodeObserverProxy : public NodeNotifier::ObserverBase {
1334 1334
      public:
1335 1335

	
1336 1336
        NodeObserverProxy(Snapshot& _snapshot)
1337 1337
          : snapshot(_snapshot) {}
1338 1338

	
1339 1339
        using NodeNotifier::ObserverBase::attach;
1340 1340
        using NodeNotifier::ObserverBase::detach;
1341 1341
        using NodeNotifier::ObserverBase::attached;
1342 1342

	
1343 1343
      protected:
1344 1344

	
1345 1345
        virtual void add(const Node& node) {
1346 1346
          snapshot.addNode(node);
1347 1347
        }
1348 1348
        virtual void add(const std::vector<Node>& nodes) {
1349 1349
          for (int i = nodes.size() - 1; i >= 0; ++i) {
1350 1350
            snapshot.addNode(nodes[i]);
1351 1351
          }
1352 1352
        }
1353 1353
        virtual void erase(const Node& node) {
1354 1354
          snapshot.eraseNode(node);
1355 1355
        }
1356 1356
        virtual void erase(const std::vector<Node>& nodes) {
1357 1357
          for (int i = 0; i < int(nodes.size()); ++i) {
1358 1358
            snapshot.eraseNode(nodes[i]);
1359 1359
          }
1360 1360
        }
1361 1361
        virtual void build() {
1362 1362
          Node node;
1363 1363
          std::vector<Node> nodes;
1364 1364
          for (notifier()->first(node); node != INVALID;
1365 1365
               notifier()->next(node)) {
1366 1366
            nodes.push_back(node);
1367 1367
          }
1368 1368
          for (int i = nodes.size() - 1; i >= 0; --i) {
1369 1369
            snapshot.addNode(nodes[i]);
1370 1370
          }
1371 1371
        }
1372 1372
        virtual void clear() {
1373 1373
          Node node;
1374 1374
          for (notifier()->first(node); node != INVALID;
1375 1375
               notifier()->next(node)) {
1376 1376
            snapshot.eraseNode(node);
1377 1377
          }
1378 1378
        }
1379 1379

	
1380 1380
        Snapshot& snapshot;
1381 1381
      };
1382 1382

	
1383 1383
      class EdgeObserverProxy : public EdgeNotifier::ObserverBase {
1384 1384
      public:
1385 1385

	
1386 1386
        EdgeObserverProxy(Snapshot& _snapshot)
1387 1387
          : snapshot(_snapshot) {}
1388 1388

	
1389 1389
        using EdgeNotifier::ObserverBase::attach;
1390 1390
        using EdgeNotifier::ObserverBase::detach;
1391 1391
        using EdgeNotifier::ObserverBase::attached;
1392 1392

	
1393 1393
      protected:
1394 1394

	
1395 1395
        virtual void add(const Edge& edge) {
1396 1396
          snapshot.addEdge(edge);
1397 1397
        }
1398 1398
        virtual void add(const std::vector<Edge>& edges) {
1399 1399
          for (int i = edges.size() - 1; i >= 0; ++i) {
1400 1400
            snapshot.addEdge(edges[i]);
1401 1401
          }
1402 1402
        }
1403 1403
        virtual void erase(const Edge& edge) {
1404 1404
          snapshot.eraseEdge(edge);
1405 1405
        }
1406 1406
        virtual void erase(const std::vector<Edge>& edges) {
1407 1407
          for (int i = 0; i < int(edges.size()); ++i) {
1408 1408
            snapshot.eraseEdge(edges[i]);
1409 1409
          }
1410 1410
        }
1411 1411
        virtual void build() {
1412 1412
          Edge edge;
1413 1413
          std::vector<Edge> edges;
1414 1414
          for (notifier()->first(edge); edge != INVALID;
1415 1415
               notifier()->next(edge)) {
1416 1416
            edges.push_back(edge);
1417 1417
          }
1418 1418
          for (int i = edges.size() - 1; i >= 0; --i) {
1419 1419
            snapshot.addEdge(edges[i]);
1420 1420
          }
1421 1421
        }
1422 1422
        virtual void clear() {
1423 1423
          Edge edge;
1424 1424
          for (notifier()->first(edge); edge != INVALID;
1425 1425
               notifier()->next(edge)) {
1426 1426
            snapshot.eraseEdge(edge);
1427 1427
          }
1428 1428
        }
1429 1429

	
1430 1430
        Snapshot& snapshot;
1431 1431
      };
1432 1432

	
1433 1433
      ListGraph *graph;
1434 1434

	
1435 1435
      NodeObserverProxy node_observer_proxy;
1436 1436
      EdgeObserverProxy edge_observer_proxy;
1437 1437

	
1438 1438
      std::list<Node> added_nodes;
1439 1439
      std::list<Edge> added_edges;
1440 1440

	
1441 1441

	
1442 1442
      void addNode(const Node& node) {
1443 1443
        added_nodes.push_front(node);
1444 1444
      }
1445 1445
      void eraseNode(const Node& node) {
1446 1446
        std::list<Node>::iterator it =
1447 1447
          std::find(added_nodes.begin(), added_nodes.end(), node);
1448 1448
        if (it == added_nodes.end()) {
1449 1449
          clear();
1450 1450
          edge_observer_proxy.detach();
1451 1451
          throw NodeNotifier::ImmediateDetach();
1452 1452
        } else {
1453 1453
          added_nodes.erase(it);
1454 1454
        }
1455 1455
      }
1456 1456

	
1457 1457
      void addEdge(const Edge& edge) {
1458 1458
        added_edges.push_front(edge);
1459 1459
      }
1460 1460
      void eraseEdge(const Edge& edge) {
1461 1461
        std::list<Edge>::iterator it =
1462 1462
          std::find(added_edges.begin(), added_edges.end(), edge);
1463 1463
        if (it == added_edges.end()) {
1464 1464
          clear();
1465 1465
          node_observer_proxy.detach();
1466 1466
          throw EdgeNotifier::ImmediateDetach();
1467 1467
        } else {
1468 1468
          added_edges.erase(it);
1469 1469
        }
1470 1470
      }
1471 1471

	
1472 1472
      void attach(ListGraph &_graph) {
1473 1473
        graph = &_graph;
1474 1474
        node_observer_proxy.attach(graph->notifier(Node()));
1475 1475
        edge_observer_proxy.attach(graph->notifier(Edge()));
1476 1476
      }
1477 1477

	
1478 1478
      void detach() {
1479 1479
        node_observer_proxy.detach();
1480 1480
        edge_observer_proxy.detach();
1481 1481
      }
1482 1482

	
1483 1483
      bool attached() const {
1484 1484
        return node_observer_proxy.attached();
1485 1485
      }
1486 1486

	
1487 1487
      void clear() {
1488 1488
        added_nodes.clear();
1489 1489
        added_edges.clear();
1490 1490
      }
1491 1491

	
1492 1492
    public:
1493 1493

	
1494 1494
      /// \brief Default constructor.
1495 1495
      ///
1496 1496
      /// Default constructor.
1497 1497
      /// To actually make a snapshot you must call save().
1498 1498
      Snapshot()
1499 1499
        : graph(0), node_observer_proxy(*this),
1500 1500
          edge_observer_proxy(*this) {}
1501 1501

	
1502 1502
      /// \brief Constructor that immediately makes a snapshot.
1503 1503
      ///
1504 1504
      /// This constructor immediately makes a snapshot of the graph.
1505 1505
      /// \param _graph The graph we make a snapshot of.
1506 1506
      Snapshot(ListGraph &_graph)
1507 1507
        : node_observer_proxy(*this),
1508 1508
          edge_observer_proxy(*this) {
1509 1509
        attach(_graph);
1510 1510
      }
1511 1511

	
1512 1512
      /// \brief Make a snapshot.
1513 1513
      ///
1514 1514
      /// Make a snapshot of the graph.
1515 1515
      ///
1516 1516
      /// This function can be called more than once. In case of a repeated
1517 1517
      /// call, the previous snapshot gets lost.
1518 1518
      /// \param _graph The graph we make the snapshot of.
1519 1519
      void save(ListGraph &_graph) {
1520 1520
        if (attached()) {
1521 1521
          detach();
1522 1522
          clear();
1523 1523
        }
1524 1524
        attach(_graph);
1525 1525
      }
1526 1526

	
1527 1527
      /// \brief Undo the changes until the last snapshot.
1528 1528
      //
1529 1529
      /// Undo the changes until the last snapshot created by save().
1530 1530
      void restore() {
1531 1531
        detach();
1532 1532
        for(std::list<Edge>::iterator it = added_edges.begin();
1533 1533
            it != added_edges.end(); ++it) {
1534 1534
          graph->erase(*it);
1535 1535
        }
1536 1536
        for(std::list<Node>::iterator it = added_nodes.begin();
1537 1537
            it != added_nodes.end(); ++it) {
1538 1538
          graph->erase(*it);
1539 1539
        }
1540 1540
        clear();
1541 1541
      }
1542 1542

	
1543 1543
      /// \brief Gives back true when the snapshot is valid.
1544 1544
      ///
1545 1545
      /// Gives back true when the snapshot is valid.
1546 1546
      bool valid() const {
1547 1547
        return attached();
1548 1548
      }
1549 1549
    };
1550 1550
  };
1551 1551

	
1552 1552
  /// @}
1553 1553
} //namespace lemon
1554 1554

	
1555 1555

	
1556 1556
#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_MAPS_H
20 20
#define LEMON_MAPS_H
21 21

	
22 22
#include <iterator>
23 23
#include <functional>
24 24
#include <vector>
25 25

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

	
28 28
///\file
29 29
///\ingroup maps
30 30
///\brief Miscellaneous property maps
31 31

	
32 32
#include <map>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \addtogroup maps
37 37
  /// @{
38 38

	
39 39
  /// Base class of maps.
40 40

	
41 41
  /// Base class of maps. It provides the necessary type definitions
42 42
  /// required by the map %concepts.
43 43
  template<typename K, typename V>
44 44
  class MapBase {
45 45
  public:
46
    /// \biref The key type of the map.
46
    /// \brief The key type of the map.
47 47
    typedef K Key;
48 48
    /// \brief The value type of the map.
49 49
    /// (The type of objects associated with the keys).
50 50
    typedef V Value;
51 51
  };
52 52

	
53 53

	
54 54
  /// Null map. (a.k.a. DoNothingMap)
55 55

	
56 56
  /// This map can be used if you have to provide a map only for
57 57
  /// its type definitions, or if you have to provide a writable map,
58 58
  /// but data written to it is not required (i.e. it will be sent to
59 59
  /// <tt>/dev/null</tt>).
60 60
  /// It conforms the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
61 61
  ///
62 62
  /// \sa ConstMap
63 63
  template<typename K, typename V>
64 64
  class NullMap : public MapBase<K, V> {
65 65
  public:
66 66
    typedef MapBase<K, V> Parent;
67 67
    typedef typename Parent::Key Key;
68 68
    typedef typename Parent::Value Value;
69 69

	
70 70
    /// Gives back a default constructed element.
71 71
    Value operator[](const Key&) const { return Value(); }
72 72
    /// Absorbs the value.
73 73
    void set(const Key&, const Value&) {}
74 74
  };
75 75

	
76 76
  /// Returns a \c NullMap class
77 77

	
78 78
  /// This function just returns a \c NullMap class.
79 79
  /// \relates NullMap
80 80
  template <typename K, typename V>
81 81
  NullMap<K, V> nullMap() {
82 82
    return NullMap<K, V>();
83 83
  }
84 84

	
85 85

	
86 86
  /// Constant map.
87 87

	
88 88
  /// This \ref concepts::ReadMap "readable map" assigns a specified
89 89
  /// value to each key.
90 90
  ///
91 91
  /// In other aspects it is equivalent to \c NullMap.
92 92
  /// So it conforms the \ref concepts::ReadWriteMap "ReadWriteMap"
93 93
  /// concept, but it absorbs the data written to it.
94 94
  ///
95 95
  /// The simplest way of using this map is through the constMap()
96 96
  /// function.
97 97
  ///
98 98
  /// \sa NullMap
99 99
  /// \sa IdentityMap
100 100
  template<typename K, typename V>
101 101
  class ConstMap : public MapBase<K, V> {
102 102
  private:
103 103
    V _value;
104 104
  public:
105 105
    typedef MapBase<K, V> Parent;
106 106
    typedef typename Parent::Key Key;
107 107
    typedef typename Parent::Value Value;
108 108

	
109 109
    /// Default constructor
110 110

	
111 111
    /// Default constructor.
112 112
    /// The value of the map will be default constructed.
113 113
    ConstMap() {}
114 114

	
115 115
    /// Constructor with specified initial value
116 116

	
117 117
    /// Constructor with specified initial value.
118 118
    /// \param v The initial value of the map.
119 119
    ConstMap(const Value &v) : _value(v) {}
120 120

	
121 121
    /// Gives back the specified value.
122 122
    Value operator[](const Key&) const { return _value; }
123 123

	
124 124
    /// Absorbs the value.
125 125
    void set(const Key&, const Value&) {}
126 126

	
127 127
    /// Sets the value that is assigned to each key.
128 128
    void setAll(const Value &v) {
129 129
      _value = v;
130 130
    }
131 131

	
132 132
    template<typename V1>
133 133
    ConstMap(const ConstMap<K, V1> &, const Value &v) : _value(v) {}
134 134
  };
135 135

	
136 136
  /// Returns a \c ConstMap class
137 137

	
138 138
  /// This function just returns a \c ConstMap class.
139 139
  /// \relates ConstMap
140 140
  template<typename K, typename V>
141 141
  inline ConstMap<K, V> constMap(const V &v) {
142 142
    return ConstMap<K, V>(v);
143 143
  }
144 144

	
145 145
  template<typename K, typename V>
146 146
  inline ConstMap<K, V> constMap() {
147 147
    return ConstMap<K, V>();
148 148
  }
149 149

	
150 150

	
151 151
  template<typename T, T v>
152 152
  struct Const {};
153 153

	
154 154
  /// Constant map with inlined constant value.
155 155

	
156 156
  /// This \ref concepts::ReadMap "readable map" assigns a specified
157 157
  /// value to each key.
158 158
  ///
159 159
  /// In other aspects it is equivalent to \c NullMap.
160 160
  /// So it conforms the \ref concepts::ReadWriteMap "ReadWriteMap"
161 161
  /// concept, but it absorbs the data written to it.
162 162
  ///
163 163
  /// The simplest way of using this map is through the constMap()
164 164
  /// function.
165 165
  ///
166 166
  /// \sa NullMap
167 167
  /// \sa IdentityMap
168 168
  template<typename K, typename V, V v>
169 169
  class ConstMap<K, Const<V, v> > : public MapBase<K, V> {
170 170
  public:
171 171
    typedef MapBase<K, V> Parent;
172 172
    typedef typename Parent::Key Key;
173 173
    typedef typename Parent::Value Value;
174 174

	
175 175
    /// Constructor.
176 176
    ConstMap() {}
177 177

	
178 178
    /// Gives back the specified value.
179 179
    Value operator[](const Key&) const { return v; }
180 180

	
181 181
    /// Absorbs the value.
182 182
    void set(const Key&, const Value&) {}
183 183
  };
184 184

	
185 185
  /// Returns a \c ConstMap class with inlined constant value
186 186

	
187 187
  /// This function just returns a \c ConstMap class with inlined
188 188
  /// constant value.
189 189
  /// \relates ConstMap
190 190
  template<typename K, typename V, V v>
191 191
  inline ConstMap<K, Const<V, v> > constMap() {
192 192
    return ConstMap<K, Const<V, v> >();
193 193
  }
194 194

	
195 195

	
196 196
  /// Identity map.
197 197

	
198 198
  /// This \ref concepts::ReadMap "read-only map" gives back the given
199 199
  /// key as value without any modification.
200 200
  ///
201 201
  /// \sa ConstMap
202 202
  template <typename T>
203 203
  class IdentityMap : public MapBase<T, T> {
204 204
  public:
205 205
    typedef MapBase<T, T> Parent;
206 206
    typedef typename Parent::Key Key;
207 207
    typedef typename Parent::Value Value;
208 208

	
209 209
    /// Gives back the given value without any modification.
210 210
    Value operator[](const Key &k) const {
211 211
      return k;
212 212
    }
213 213
  };
214 214

	
215 215
  /// Returns an \c IdentityMap class
216 216

	
217 217
  /// This function just returns an \c IdentityMap class.
218 218
  /// \relates IdentityMap
219 219
  template<typename T>
220 220
  inline IdentityMap<T> identityMap() {
221 221
    return IdentityMap<T>();
222 222
  }
223 223

	
224 224

	
225 225
  /// \brief Map for storing values for integer keys from the range
226 226
  /// <tt>[0..size-1]</tt>.
227 227
  ///
228 228
  /// This map is essentially a wrapper for \c std::vector. It assigns
229 229
  /// values to integer keys from the range <tt>[0..size-1]</tt>.
230 230
  /// It can be used with some data structures, for example
231 231
  /// \c UnionFind, \c BinHeap, when the used items are small
232 232
  /// integers. This map conforms the \ref concepts::ReferenceMap
233 233
  /// "ReferenceMap" concept.
234 234
  ///
235 235
  /// The simplest way of using this map is through the rangeMap()
236 236
  /// function.
237 237
  template <typename V>
238 238
  class RangeMap : public MapBase<int, V> {
239 239
    template <typename V1>
240 240
    friend class RangeMap;
241 241
  private:
242 242

	
243 243
    typedef std::vector<V> Vector;
244 244
    Vector _vector;
245 245

	
246 246
  public:
247 247

	
248 248
    typedef MapBase<int, V> Parent;
249 249
    /// Key type
250 250
    typedef typename Parent::Key Key;
251 251
    /// Value type
252 252
    typedef typename Parent::Value Value;
253 253
    /// Reference type
254 254
    typedef typename Vector::reference Reference;
255 255
    /// Const reference type
256 256
    typedef typename Vector::const_reference ConstReference;
257 257

	
258 258
    typedef True ReferenceMapTag;
259 259

	
260 260
  public:
261 261

	
262 262
    /// Constructor with specified default value.
263 263
    RangeMap(int size = 0, const Value &value = Value())
264 264
      : _vector(size, value) {}
265 265

	
266 266
    /// Constructs the map from an appropriate \c std::vector.
267 267
    template <typename V1>
268 268
    RangeMap(const std::vector<V1>& vector)
269 269
      : _vector(vector.begin(), vector.end()) {}
270 270

	
271 271
    /// Constructs the map from another \c RangeMap.
272 272
    template <typename V1>
273 273
    RangeMap(const RangeMap<V1> &c)
274 274
      : _vector(c._vector.begin(), c._vector.end()) {}
275 275

	
276 276
    /// Returns the size of the map.
277 277
    int size() {
278 278
      return _vector.size();
279 279
    }
280 280

	
281 281
    /// Resizes the map.
282 282

	
283 283
    /// Resizes the underlying \c std::vector container, so changes the
284 284
    /// keyset of the map.
285 285
    /// \param size The new size of the map. The new keyset will be the
286 286
    /// range <tt>[0..size-1]</tt>.
287 287
    /// \param value The default value to assign to the new keys.
288 288
    void resize(int size, const Value &value = Value()) {
289 289
      _vector.resize(size, value);
290 290
    }
291 291

	
292 292
  private:
293 293

	
294 294
    RangeMap& operator=(const RangeMap&);
295 295

	
296 296
  public:
297 297

	
298 298
    ///\e
299 299
    Reference operator[](const Key &k) {
300 300
      return _vector[k];
301 301
    }
302 302

	
303 303
    ///\e
304 304
    ConstReference operator[](const Key &k) const {
305 305
      return _vector[k];
306 306
    }
307 307

	
308 308
    ///\e
309 309
    void set(const Key &k, const Value &v) {
310 310
      _vector[k] = v;
311 311
    }
312 312
  };
313 313

	
314 314
  /// Returns a \c RangeMap class
315 315

	
316 316
  /// This function just returns a \c RangeMap class.
317 317
  /// \relates RangeMap
318 318
  template<typename V>
319 319
  inline RangeMap<V> rangeMap(int size = 0, const V &value = V()) {
320 320
    return RangeMap<V>(size, value);
321 321
  }
322 322

	
323 323
  /// \brief Returns a \c RangeMap class created from an appropriate
324 324
  /// \c std::vector
325 325

	
326 326
  /// This function just returns a \c RangeMap class created from an
327 327
  /// appropriate \c std::vector.
328 328
  /// \relates RangeMap
329 329
  template<typename V>
330 330
  inline RangeMap<V> rangeMap(const std::vector<V> &vector) {
331 331
    return RangeMap<V>(vector);
332 332
  }
333 333

	
334 334

	
335 335
  /// Map type based on \c std::map
336 336

	
337 337
  /// This map is essentially a wrapper for \c std::map with addition
338 338
  /// that you can specify a default value for the keys that are not
339 339
  /// stored actually. This value can be different from the default
340 340
  /// contructed value (i.e. \c %Value()).
341 341
  /// This type conforms the \ref concepts::ReferenceMap "ReferenceMap"
342 342
  /// concept.
343 343
  ///
344 344
  /// This map is useful if a default value should be assigned to most of
345 345
  /// the keys and different values should be assigned only to a few
346 346
  /// keys (i.e. the map is "sparse").
347 347
  /// The name of this type also refers to this important usage.
348 348
  ///
349 349
  /// Apart form that this map can be used in many other cases since it
350 350
  /// is based on \c std::map, which is a general associative container.
351 351
  /// However keep in mind that it is usually not as efficient as other
352 352
  /// maps.
353 353
  ///
354 354
  /// The simplest way of using this map is through the sparseMap()
355 355
  /// function.
356 356
  template <typename K, typename V, typename Compare = std::less<K> >
357 357
  class SparseMap : public MapBase<K, V> {
358 358
    template <typename K1, typename V1, typename C1>
359 359
    friend class SparseMap;
360 360
  public:
361 361

	
362 362
    typedef MapBase<K, V> Parent;
363 363
    /// Key type
364 364
    typedef typename Parent::Key Key;
365 365
    /// Value type
366 366
    typedef typename Parent::Value Value;
367 367
    /// Reference type
368 368
    typedef Value& Reference;
369 369
    /// Const reference type
370 370
    typedef const Value& ConstReference;
371 371

	
372 372
    typedef True ReferenceMapTag;
373 373

	
374 374
  private:
375 375

	
376 376
    typedef std::map<K, V, Compare> Map;
377 377
    Map _map;
378 378
    Value _value;
379 379

	
380 380
  public:
381 381

	
382 382
    /// \brief Constructor with specified default value.
383 383
    SparseMap(const Value &value = Value()) : _value(value) {}
384 384
    /// \brief Constructs the map from an appropriate \c std::map, and
385 385
    /// explicitly specifies a default value.
386 386
    template <typename V1, typename Comp1>
387 387
    SparseMap(const std::map<Key, V1, Comp1> &map,
388 388
              const Value &value = Value())
389 389
      : _map(map.begin(), map.end()), _value(value) {}
390 390

	
391 391
    /// \brief Constructs the map from another \c SparseMap.
392 392
    template<typename V1, typename Comp1>
393 393
    SparseMap(const SparseMap<Key, V1, Comp1> &c)
394 394
      : _map(c._map.begin(), c._map.end()), _value(c._value) {}
395 395

	
396 396
  private:
397 397

	
398 398
    SparseMap& operator=(const SparseMap&);
399 399

	
400 400
  public:
401 401

	
402 402
    ///\e
403 403
    Reference operator[](const Key &k) {
404 404
      typename Map::iterator it = _map.lower_bound(k);
405 405
      if (it != _map.end() && !_map.key_comp()(k, it->first))
406 406
        return it->second;
407 407
      else
408 408
        return _map.insert(it, std::make_pair(k, _value))->second;
409 409
    }
410 410

	
411 411
    ///\e
412 412
    ConstReference operator[](const Key &k) const {
413 413
      typename Map::const_iterator it = _map.find(k);
414 414
      if (it != _map.end())
415 415
        return it->second;
416 416
      else
417 417
        return _value;
418 418
    }
419 419

	
420 420
    ///\e
421 421
    void set(const Key &k, const Value &v) {
422 422
      typename Map::iterator it = _map.lower_bound(k);
423 423
      if (it != _map.end() && !_map.key_comp()(k, it->first))
424 424
        it->second = v;
425 425
      else
426 426
        _map.insert(it, std::make_pair(k, v));
427 427
    }
428 428

	
429 429
    ///\e
430 430
    void setAll(const Value &v) {
431 431
      _value = v;
432 432
      _map.clear();
433 433
    }
434 434
  };
435 435

	
436 436
  /// Returns a \c SparseMap class
437 437

	
438 438
  /// This function just returns a \c SparseMap class with specified
439 439
  /// default value.
440 440
  /// \relates SparseMap
441 441
  template<typename K, typename V, typename Compare>
442 442
  inline SparseMap<K, V, Compare> sparseMap(const V& value = V()) {
443 443
    return SparseMap<K, V, Compare>(value);
444 444
  }
445 445

	
446 446
  template<typename K, typename V>
447 447
  inline SparseMap<K, V, std::less<K> > sparseMap(const V& value = V()) {
448 448
    return SparseMap<K, V, std::less<K> >(value);
449 449
  }
450 450

	
451 451
  /// \brief Returns a \c SparseMap class created from an appropriate
452 452
  /// \c std::map
453 453

	
454 454
  /// This function just returns a \c SparseMap class created from an
455 455
  /// appropriate \c std::map.
456 456
  /// \relates SparseMap
457 457
  template<typename K, typename V, typename Compare>
458 458
  inline SparseMap<K, V, Compare>
459 459
    sparseMap(const std::map<K, V, Compare> &map, const V& value = V())
460 460
  {
461 461
    return SparseMap<K, V, Compare>(map, value);
462 462
  }
463 463

	
464 464
  /// @}
465 465

	
466 466
  /// \addtogroup map_adaptors
467 467
  /// @{
468 468

	
469 469
  /// Composition of two maps
470 470

	
471 471
  /// This \ref concepts::ReadMap "read-only map" returns the
472 472
  /// composition of two given maps. That is to say, if \c m1 is of
473 473
  /// type \c M1 and \c m2 is of \c M2, then for
474 474
  /// \code
475 475
  ///   ComposeMap<M1, M2> cm(m1,m2);
476 476
  /// \endcode
477 477
  /// <tt>cm[x]</tt> will be equal to <tt>m1[m2[x]]</tt>.
478 478
  ///
479 479
  /// The \c Key type of the map is inherited from \c M2 and the
480 480
  /// \c Value type is from \c M1.
481 481
  /// \c M2::Value must be convertible to \c M1::Key.
482 482
  ///
483 483
  /// The simplest way of using this map is through the composeMap()
484 484
  /// function.
485 485
  ///
486 486
  /// \sa CombineMap
487 487
  template <typename M1, typename M2>
488 488
  class ComposeMap : public MapBase<typename M2::Key, typename M1::Value> {
489 489
    const M1 &_m1;
490 490
    const M2 &_m2;
491 491
  public:
492 492
    typedef MapBase<typename M2::Key, typename M1::Value> Parent;
493 493
    typedef typename Parent::Key Key;
494 494
    typedef typename Parent::Value Value;
495 495

	
496 496
    /// Constructor
497 497
    ComposeMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
498 498

	
499 499
    /// \e
500 500
    typename MapTraits<M1>::ConstReturnValue
501 501
    operator[](const Key &k) const { return _m1[_m2[k]]; }
502 502
  };
503 503

	
504 504
  /// Returns a \c ComposeMap class
505 505

	
506 506
  /// This function just returns a \c ComposeMap class.
507 507
  ///
508 508
  /// If \c m1 and \c m2 are maps and the \c Value type of \c m2 is
509 509
  /// convertible to the \c Key of \c m1, then <tt>composeMap(m1,m2)[x]</tt>
510 510
  /// will be equal to <tt>m1[m2[x]]</tt>.
511 511
  ///
512 512
  /// \relates ComposeMap
513 513
  template <typename M1, typename M2>
514 514
  inline ComposeMap<M1, M2> composeMap(const M1 &m1, const M2 &m2) {
515 515
    return ComposeMap<M1, M2>(m1, m2);
516 516
  }
517 517

	
518 518

	
519 519
  /// Combination of two maps using an STL (binary) functor.
520 520

	
521 521
  /// This \ref concepts::ReadMap "read-only map" takes two maps and a
522 522
  /// binary functor and returns the combination of the two given maps
523 523
  /// using the functor.
524 524
  /// That is to say, if \c m1 is of type \c M1 and \c m2 is of \c M2
525 525
  /// and \c f is of \c F, then for
526 526
  /// \code
527 527
  ///   CombineMap<M1,M2,F,V> cm(m1,m2,f);
528 528
  /// \endcode
529 529
  /// <tt>cm[x]</tt> will be equal to <tt>f(m1[x],m2[x])</tt>.
530 530
  ///
531 531
  /// The \c Key type of the map is inherited from \c M1 (\c M1::Key
532 532
  /// must be convertible to \c M2::Key) and the \c Value type is \c V.
533 533
  /// \c M2::Value and \c M1::Value must be convertible to the
534 534
  /// corresponding input parameter of \c F and the return type of \c F
535 535
  /// must be convertible to \c V.
536 536
  ///
537 537
  /// The simplest way of using this map is through the combineMap()
538 538
  /// function.
539 539
  ///
540 540
  /// \sa ComposeMap
541 541
  template<typename M1, typename M2, typename F,
542 542
           typename V = typename F::result_type>
543 543
  class CombineMap : public MapBase<typename M1::Key, V> {
544 544
    const M1 &_m1;
545 545
    const M2 &_m2;
546 546
    F _f;
547 547
  public:
548 548
    typedef MapBase<typename M1::Key, V> Parent;
549 549
    typedef typename Parent::Key Key;
550 550
    typedef typename Parent::Value Value;
551 551

	
552 552
    /// Constructor
553 553
    CombineMap(const M1 &m1, const M2 &m2, const F &f = F())
554 554
      : _m1(m1), _m2(m2), _f(f) {}
555 555
    /// \e
556 556
    Value operator[](const Key &k) const { return _f(_m1[k],_m2[k]); }
557 557
  };
558 558

	
559 559
  /// Returns a \c CombineMap class
560 560

	
561 561
  /// This function just returns a \c CombineMap class.
562 562
  ///
563 563
  /// For example, if \c m1 and \c m2 are both maps with \c double
564 564
  /// values, then
565 565
  /// \code
566 566
  ///   combineMap(m1,m2,std::plus<double>())
567 567
  /// \endcode
568 568
  /// is equivalent to
569 569
  /// \code
570 570
  ///   addMap(m1,m2)
571 571
  /// \endcode
572 572
  ///
573 573
  /// This function is specialized for adaptable binary function
574 574
  /// classes and C++ functions.
575 575
  ///
576 576
  /// \relates CombineMap
577 577
  template<typename M1, typename M2, typename F, typename V>
578 578
  inline CombineMap<M1, M2, F, V>
579 579
  combineMap(const M1 &m1, const M2 &m2, const F &f) {
580 580
    return CombineMap<M1, M2, F, V>(m1,m2,f);
581 581
  }
582 582

	
583 583
  template<typename M1, typename M2, typename F>
584 584
  inline CombineMap<M1, M2, F, typename F::result_type>
585 585
  combineMap(const M1 &m1, const M2 &m2, const F &f) {
586 586
    return combineMap<M1, M2, F, typename F::result_type>(m1,m2,f);
587 587
  }
588 588

	
589 589
  template<typename M1, typename M2, typename K1, typename K2, typename V>
590 590
  inline CombineMap<M1, M2, V (*)(K1, K2), V>
591 591
  combineMap(const M1 &m1, const M2 &m2, V (*f)(K1, K2)) {
592 592
    return combineMap<M1, M2, V (*)(K1, K2), V>(m1,m2,f);
593 593
  }
594 594

	
595 595

	
596 596
  /// Converts an STL style (unary) functor to a map
597 597

	
598 598
  /// This \ref concepts::ReadMap "read-only map" returns the value
599 599
  /// of a given functor. Actually, it just wraps the functor and
600 600
  /// provides the \c Key and \c Value typedefs.
601 601
  ///
602 602
  /// Template parameters \c K and \c V will become its \c Key and
603 603
  /// \c Value. In most cases they have to be given explicitly because
604 604
  /// a functor typically does not provide \c argument_type and
605 605
  /// \c result_type typedefs.
606 606
  /// Parameter \c F is the type of the used functor.
607 607
  ///
608 608
  /// The simplest way of using this map is through the functorToMap()
609 609
  /// function.
610 610
  ///
611 611
  /// \sa MapToFunctor
612 612
  template<typename F,
613 613
           typename K = typename F::argument_type,
614 614
           typename V = typename F::result_type>
615 615
  class FunctorToMap : public MapBase<K, V> {
616 616
    F _f;
617 617
  public:
618 618
    typedef MapBase<K, V> Parent;
619 619
    typedef typename Parent::Key Key;
620 620
    typedef typename Parent::Value Value;
621 621

	
622 622
    /// Constructor
623 623
    FunctorToMap(const F &f = F()) : _f(f) {}
624 624
    /// \e
625 625
    Value operator[](const Key &k) const { return _f(k); }
626 626
  };
627 627

	
628 628
  /// Returns a \c FunctorToMap class
629 629

	
630 630
  /// This function just returns a \c FunctorToMap class.
631 631
  ///
632 632
  /// This function is specialized for adaptable binary function
633 633
  /// classes and C++ functions.
634 634
  ///
635 635
  /// \relates FunctorToMap
636 636
  template<typename K, typename V, typename F>
637 637
  inline FunctorToMap<F, K, V> functorToMap(const F &f) {
638 638
    return FunctorToMap<F, K, V>(f);
639 639
  }
640 640

	
641 641
  template <typename F>
642 642
  inline FunctorToMap<F, typename F::argument_type, typename F::result_type>
643 643
    functorToMap(const F &f)
644 644
  {
645 645
    return FunctorToMap<F, typename F::argument_type,
646 646
      typename F::result_type>(f);
647 647
  }
648 648

	
649 649
  template <typename K, typename V>
650 650
  inline FunctorToMap<V (*)(K), K, V> functorToMap(V (*f)(K)) {
651 651
    return FunctorToMap<V (*)(K), K, V>(f);
652 652
  }
653 653

	
654 654

	
655 655
  /// Converts a map to an STL style (unary) functor
656 656

	
657 657
  /// This class converts a map to an STL style (unary) functor.
658 658
  /// That is it provides an <tt>operator()</tt> to read its values.
659 659
  ///
660 660
  /// For the sake of convenience it also works as a usual
661 661
  /// \ref concepts::ReadMap "readable map", i.e. <tt>operator[]</tt>
662 662
  /// and the \c Key and \c Value typedefs also exist.
663 663
  ///
664 664
  /// The simplest way of using this map is through the mapToFunctor()
665 665
  /// function.
666 666
  ///
667 667
  ///\sa FunctorToMap
668 668
  template <typename M>
669 669
  class MapToFunctor : public MapBase<typename M::Key, typename M::Value> {
670 670
    const M &_m;
671 671
  public:
672 672
    typedef MapBase<typename M::Key, typename M::Value> Parent;
673 673
    typedef typename Parent::Key Key;
674 674
    typedef typename Parent::Value Value;
675 675

	
676 676
    typedef typename Parent::Key argument_type;
677 677
    typedef typename Parent::Value result_type;
678 678

	
679 679
    /// Constructor
680 680
    MapToFunctor(const M &m) : _m(m) {}
681 681
    /// \e
682 682
    Value operator()(const Key &k) const { return _m[k]; }
683 683
    /// \e
684 684
    Value operator[](const Key &k) const { return _m[k]; }
685 685
  };
686 686

	
687 687
  /// Returns a \c MapToFunctor class
688 688

	
689 689
  /// This function just returns a \c MapToFunctor class.
690 690
  /// \relates MapToFunctor
691 691
  template<typename M>
692 692
  inline MapToFunctor<M> mapToFunctor(const M &m) {
693 693
    return MapToFunctor<M>(m);
694 694
  }
695 695

	
696 696

	
697 697
  /// \brief Map adaptor to convert the \c Value type of a map to
698 698
  /// another type using the default conversion.
699 699

	
700 700
  /// Map adaptor to convert the \c Value type of a \ref concepts::ReadMap
701 701
  /// "readable map" to another type using the default conversion.
702 702
  /// The \c Key type of it is inherited from \c M and the \c Value
703 703
  /// type is \c V.
704 704
  /// This type conforms the \ref concepts::ReadMap "ReadMap" concept.
705 705
  ///
706 706
  /// The simplest way of using this map is through the convertMap()
707 707
  /// function.
708 708
  template <typename M, typename V>
709 709
  class ConvertMap : public MapBase<typename M::Key, V> {
710 710
    const M &_m;
711 711
  public:
712 712
    typedef MapBase<typename M::Key, V> Parent;
713 713
    typedef typename Parent::Key Key;
714 714
    typedef typename Parent::Value Value;
715 715

	
716 716
    /// Constructor
717 717

	
718 718
    /// Constructor.
719 719
    /// \param m The underlying map.
720 720
    ConvertMap(const M &m) : _m(m) {}
721 721

	
722 722
    /// \e
723 723
    Value operator[](const Key &k) const { return _m[k]; }
724 724
  };
725 725

	
726 726
  /// Returns a \c ConvertMap class
727 727

	
728 728
  /// This function just returns a \c ConvertMap class.
729 729
  /// \relates ConvertMap
730 730
  template<typename V, typename M>
731 731
  inline ConvertMap<M, V> convertMap(const M &map) {
732 732
    return ConvertMap<M, V>(map);
733 733
  }
734 734

	
735 735

	
736 736
  /// Applies all map setting operations to two maps
737 737

	
738 738
  /// This map has two \ref concepts::WriteMap "writable map" parameters
739 739
  /// and each write request will be passed to both of them.
740 740
  /// If \c M1 is also \ref concepts::ReadMap "readable", then the read
741 741
  /// operations will return the corresponding values of \c M1.
742 742
  ///
743 743
  /// The \c Key and \c Value types are inherited from \c M1.
744 744
  /// The \c Key and \c Value of \c M2 must be convertible from those
745 745
  /// of \c M1.
746 746
  ///
747 747
  /// The simplest way of using this map is through the forkMap()
748 748
  /// function.
749 749
  template<typename  M1, typename M2>
750 750
  class ForkMap : public MapBase<typename M1::Key, typename M1::Value> {
751 751
    M1 &_m1;
752 752
    M2 &_m2;
753 753
  public:
754 754
    typedef MapBase<typename M1::Key, typename M1::Value> Parent;
755 755
    typedef typename Parent::Key Key;
756 756
    typedef typename Parent::Value Value;
757 757

	
758 758
    /// Constructor
759 759
    ForkMap(M1 &m1, M2 &m2) : _m1(m1), _m2(m2) {}
760 760
    /// Returns the value associated with the given key in the first map.
761 761
    Value operator[](const Key &k) const { return _m1[k]; }
762 762
    /// Sets the value associated with the given key in both maps.
763 763
    void set(const Key &k, const Value &v) { _m1.set(k,v); _m2.set(k,v); }
764 764
  };
765 765

	
766 766
  /// Returns a \c ForkMap class
767 767

	
768 768
  /// This function just returns a \c ForkMap class.
769 769
  /// \relates ForkMap
770 770
  template <typename M1, typename M2>
771 771
  inline ForkMap<M1,M2> forkMap(M1 &m1, M2 &m2) {
772 772
    return ForkMap<M1,M2>(m1,m2);
773 773
  }
774 774

	
775 775

	
776 776
  /// Sum of two maps
777 777

	
778 778
  /// This \ref concepts::ReadMap "read-only map" returns the sum
779 779
  /// of the values of the two given maps.
780 780
  /// Its \c Key and \c Value types are inherited from \c M1.
781 781
  /// The \c Key and \c Value of \c M2 must be convertible to those of
782 782
  /// \c M1.
783 783
  ///
784 784
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
785 785
  /// \code
786 786
  ///   AddMap<M1,M2> am(m1,m2);
787 787
  /// \endcode
788 788
  /// <tt>am[x]</tt> will be equal to <tt>m1[x]+m2[x]</tt>.
789 789
  ///
790 790
  /// The simplest way of using this map is through the addMap()
791 791
  /// function.
792 792
  ///
793 793
  /// \sa SubMap, MulMap, DivMap
794 794
  /// \sa ShiftMap, ShiftWriteMap
795 795
  template<typename M1, typename M2>
796 796
  class AddMap : public MapBase<typename M1::Key, typename M1::Value> {
797 797
    const M1 &_m1;
798 798
    const M2 &_m2;
799 799
  public:
800 800
    typedef MapBase<typename M1::Key, typename M1::Value> Parent;
801 801
    typedef typename Parent::Key Key;
802 802
    typedef typename Parent::Value Value;
803 803

	
804 804
    /// Constructor
805 805
    AddMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
806 806
    /// \e
807 807
    Value operator[](const Key &k) const { return _m1[k]+_m2[k]; }
808 808
  };
809 809

	
810 810
  /// Returns an \c AddMap class
811 811

	
812 812
  /// This function just returns an \c AddMap class.
813 813
  ///
814 814
  /// For example, if \c m1 and \c m2 are both maps with \c double
815 815
  /// values, then <tt>addMap(m1,m2)[x]</tt> will be equal to
816 816
  /// <tt>m1[x]+m2[x]</tt>.
817 817
  ///
818 818
  /// \relates AddMap
819 819
  template<typename M1, typename M2>
820 820
  inline AddMap<M1, M2> addMap(const M1 &m1, const M2 &m2) {
821 821
    return AddMap<M1, M2>(m1,m2);
822 822
  }
823 823

	
824 824

	
825 825
  /// Difference of two maps
826 826

	
827 827
  /// This \ref concepts::ReadMap "read-only map" returns the difference
828 828
  /// of the values of the two given maps.
829 829
  /// Its \c Key and \c Value types are inherited from \c M1.
830 830
  /// The \c Key and \c Value of \c M2 must be convertible to those of
831 831
  /// \c M1.
832 832
  ///
833 833
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
834 834
  /// \code
835 835
  ///   SubMap<M1,M2> sm(m1,m2);
836 836
  /// \endcode
837 837
  /// <tt>sm[x]</tt> will be equal to <tt>m1[x]-m2[x]</tt>.
838 838
  ///
839 839
  /// The simplest way of using this map is through the subMap()
840 840
  /// function.
841 841
  ///
842 842
  /// \sa AddMap, MulMap, DivMap
843 843
  template<typename M1, typename M2>
844 844
  class SubMap : public MapBase<typename M1::Key, typename M1::Value> {
845 845
    const M1 &_m1;
846 846
    const M2 &_m2;
847 847
  public:
848 848
    typedef MapBase<typename M1::Key, typename M1::Value> Parent;
849 849
    typedef typename Parent::Key Key;
850 850
    typedef typename Parent::Value Value;
851 851

	
852 852
    /// Constructor
853 853
    SubMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
854 854
    /// \e
855 855
    Value operator[](const Key &k) const { return _m1[k]-_m2[k]; }
856 856
  };
857 857

	
858 858
  /// Returns a \c SubMap class
859 859

	
860 860
  /// This function just returns a \c SubMap class.
861 861
  ///
862 862
  /// For example, if \c m1 and \c m2 are both maps with \c double
863 863
  /// values, then <tt>subMap(m1,m2)[x]</tt> will be equal to
864 864
  /// <tt>m1[x]-m2[x]</tt>.
865 865
  ///
866 866
  /// \relates SubMap
867 867
  template<typename M1, typename M2>
868 868
  inline SubMap<M1, M2> subMap(const M1 &m1, const M2 &m2) {
869 869
    return SubMap<M1, M2>(m1,m2);
870 870
  }
871 871

	
872 872

	
873 873
  /// Product of two maps
874 874

	
875 875
  /// This \ref concepts::ReadMap "read-only map" returns the product
876 876
  /// of the values of the two given maps.
877 877
  /// Its \c Key and \c Value types are inherited from \c M1.
878 878
  /// The \c Key and \c Value of \c M2 must be convertible to those of
879 879
  /// \c M1.
880 880
  ///
881 881
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
882 882
  /// \code
883 883
  ///   MulMap<M1,M2> mm(m1,m2);
884 884
  /// \endcode
885 885
  /// <tt>mm[x]</tt> will be equal to <tt>m1[x]*m2[x]</tt>.
886 886
  ///
887 887
  /// The simplest way of using this map is through the mulMap()
888 888
  /// function.
889 889
  ///
890 890
  /// \sa AddMap, SubMap, DivMap
891 891
  /// \sa ScaleMap, ScaleWriteMap
892 892
  template<typename M1, typename M2>
893 893
  class MulMap : public MapBase<typename M1::Key, typename M1::Value> {
894 894
    const M1 &_m1;
895 895
    const M2 &_m2;
896 896
  public:
897 897
    typedef MapBase<typename M1::Key, typename M1::Value> Parent;
898 898
    typedef typename Parent::Key Key;
899 899
    typedef typename Parent::Value Value;
900 900

	
901 901
    /// Constructor
902 902
    MulMap(const M1 &m1,const M2 &m2) : _m1(m1), _m2(m2) {}
903 903
    /// \e
904 904
    Value operator[](const Key &k) const { return _m1[k]*_m2[k]; }
905 905
  };
906 906

	
907 907
  /// Returns a \c MulMap class
908 908

	
909 909
  /// This function just returns a \c MulMap class.
910 910
  ///
911 911
  /// For example, if \c m1 and \c m2 are both maps with \c double
912 912
  /// values, then <tt>mulMap(m1,m2)[x]</tt> will be equal to
913 913
  /// <tt>m1[x]*m2[x]</tt>.
914 914
  ///
915 915
  /// \relates MulMap
916 916
  template<typename M1, typename M2>
917 917
  inline MulMap<M1, M2> mulMap(const M1 &m1,const M2 &m2) {
918 918
    return MulMap<M1, M2>(m1,m2);
919 919
  }
920 920

	
921 921

	
922 922
  /// Quotient of two maps
923 923

	
924 924
  /// This \ref concepts::ReadMap "read-only map" returns the quotient
925 925
  /// of the values of the two given maps.
926 926
  /// Its \c Key and \c Value types are inherited from \c M1.
927 927
  /// The \c Key and \c Value of \c M2 must be convertible to those of
928 928
  /// \c M1.
929 929
  ///
930 930
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
931 931
  /// \code
932 932
  ///   DivMap<M1,M2> dm(m1,m2);
933 933
  /// \endcode
934 934
  /// <tt>dm[x]</tt> will be equal to <tt>m1[x]/m2[x]</tt>.
935 935
  ///
936 936
  /// The simplest way of using this map is through the divMap()
937 937
  /// function.
938 938
  ///
939 939
  /// \sa AddMap, SubMap, MulMap
940 940
  template<typename M1, typename M2>
941 941
  class DivMap : public MapBase<typename M1::Key, typename M1::Value> {
942 942
    const M1 &_m1;
943 943
    const M2 &_m2;
944 944
  public:
945 945
    typedef MapBase<typename M1::Key, typename M1::Value> Parent;
946 946
    typedef typename Parent::Key Key;
947 947
    typedef typename Parent::Value Value;
948 948

	
949 949
    /// Constructor
950 950
    DivMap(const M1 &m1,const M2 &m2) : _m1(m1), _m2(m2) {}
951 951
    /// \e
952 952
    Value operator[](const Key &k) const { return _m1[k]/_m2[k]; }
953 953
  };
954 954

	
955 955
  /// Returns a \c DivMap class
956 956

	
957 957
  /// This function just returns a \c DivMap class.
958 958
  ///
959 959
  /// For example, if \c m1 and \c m2 are both maps with \c double
960 960
  /// values, then <tt>divMap(m1,m2)[x]</tt> will be equal to
961 961
  /// <tt>m1[x]/m2[x]</tt>.
962 962
  ///
963 963
  /// \relates DivMap
964 964
  template<typename M1, typename M2>
965 965
  inline DivMap<M1, M2> divMap(const M1 &m1,const M2 &m2) {
966 966
    return DivMap<M1, M2>(m1,m2);
967 967
  }
968 968

	
969 969

	
970 970
  /// Shifts a map with a constant.
971 971

	
972 972
  /// This \ref concepts::ReadMap "read-only map" returns the sum of
973 973
  /// the given map and a constant value (i.e. it shifts the map with
974 974
  /// the constant). Its \c Key and \c Value are inherited from \c M.
975 975
  ///
976 976
  /// Actually,
977 977
  /// \code
978 978
  ///   ShiftMap<M> sh(m,v);
979 979
  /// \endcode
980 980
  /// is equivalent to
981 981
  /// \code
982 982
  ///   ConstMap<M::Key, M::Value> cm(v);
983 983
  ///   AddMap<M, ConstMap<M::Key, M::Value> > sh(m,cm);
984 984
  /// \endcode
985 985
  ///
986 986
  /// The simplest way of using this map is through the shiftMap()
987 987
  /// function.
988 988
  ///
989 989
  /// \sa ShiftWriteMap
990 990
  template<typename M, typename C = typename M::Value>
991 991
  class ShiftMap : public MapBase<typename M::Key, typename M::Value> {
992 992
    const M &_m;
993 993
    C _v;
994 994
  public:
995 995
    typedef MapBase<typename M::Key, typename M::Value> Parent;
996 996
    typedef typename Parent::Key Key;
997 997
    typedef typename Parent::Value Value;
998 998

	
999 999
    /// Constructor
1000 1000

	
1001 1001
    /// Constructor.
1002 1002
    /// \param m The undelying map.
1003 1003
    /// \param v The constant value.
1004 1004
    ShiftMap(const M &m, const C &v) : _m(m), _v(v) {}
1005 1005
    /// \e
1006 1006
    Value operator[](const Key &k) const { return _m[k]+_v; }
1007 1007
  };
1008 1008

	
1009 1009
  /// Shifts a map with a constant (read-write version).
1010 1010

	
1011 1011
  /// This \ref concepts::ReadWriteMap "read-write map" returns the sum
1012 1012
  /// of the given map and a constant value (i.e. it shifts the map with
1013 1013
  /// the constant). Its \c Key and \c Value are inherited from \c M.
1014 1014
  /// It makes also possible to write the map.
1015 1015
  ///
1016 1016
  /// The simplest way of using this map is through the shiftWriteMap()
1017 1017
  /// function.
1018 1018
  ///
1019 1019
  /// \sa ShiftMap
1020 1020
  template<typename M, typename C = typename M::Value>
1021 1021
  class ShiftWriteMap : public MapBase<typename M::Key, typename M::Value> {
1022 1022
    M &_m;
1023 1023
    C _v;
1024 1024
  public:
1025 1025
    typedef MapBase<typename M::Key, typename M::Value> Parent;
1026 1026
    typedef typename Parent::Key Key;
1027 1027
    typedef typename Parent::Value Value;
1028 1028

	
1029 1029
    /// Constructor
1030 1030

	
1031 1031
    /// Constructor.
1032 1032
    /// \param m The undelying map.
1033 1033
    /// \param v The constant value.
1034 1034
    ShiftWriteMap(M &m, const C &v) : _m(m), _v(v) {}
1035 1035
    /// \e
1036 1036
    Value operator[](const Key &k) const { return _m[k]+_v; }
1037 1037
    /// \e
1038 1038
    void set(const Key &k, const Value &v) { _m.set(k, v-_v); }
1039 1039
  };
1040 1040

	
1041 1041
  /// Returns a \c ShiftMap class
1042 1042

	
1043 1043
  /// This function just returns a \c ShiftMap class.
1044 1044
  ///
1045 1045
  /// For example, if \c m is a map with \c double values and \c v is
1046 1046
  /// \c double, then <tt>shiftMap(m,v)[x]</tt> will be equal to
1047 1047
  /// <tt>m[x]+v</tt>.
1048 1048
  ///
1049 1049
  /// \relates ShiftMap
1050 1050
  template<typename M, typename C>
1051 1051
  inline ShiftMap<M, C> shiftMap(const M &m, const C &v) {
1052 1052
    return ShiftMap<M, C>(m,v);
1053 1053
  }
1054 1054

	
1055 1055
  /// Returns a \c ShiftWriteMap class
1056 1056

	
1057 1057
  /// This function just returns a \c ShiftWriteMap class.
1058 1058
  ///
1059 1059
  /// For example, if \c m is a map with \c double values and \c v is
1060 1060
  /// \c double, then <tt>shiftWriteMap(m,v)[x]</tt> will be equal to
1061 1061
  /// <tt>m[x]+v</tt>.
1062 1062
  /// Moreover it makes also possible to write the map.
1063 1063
  ///
1064 1064
  /// \relates ShiftWriteMap
1065 1065
  template<typename M, typename C>
1066 1066
  inline ShiftWriteMap<M, C> shiftWriteMap(M &m, const C &v) {
1067 1067
    return ShiftWriteMap<M, C>(m,v);
1068 1068
  }
1069 1069

	
1070 1070

	
1071 1071
  /// Scales a map with a constant.
1072 1072

	
1073 1073
  /// This \ref concepts::ReadMap "read-only map" returns the value of
1074 1074
  /// the given map multiplied from the left side with a constant value.
1075 1075
  /// Its \c Key and \c Value are inherited from \c M.
1076 1076
  ///
1077 1077
  /// Actually,
1078 1078
  /// \code
1079 1079
  ///   ScaleMap<M> sc(m,v);
1080 1080
  /// \endcode
1081 1081
  /// is equivalent to
1082 1082
  /// \code
1083 1083
  ///   ConstMap<M::Key, M::Value> cm(v);
1084 1084
  ///   MulMap<ConstMap<M::Key, M::Value>, M> sc(cm,m);
1085 1085
  /// \endcode
1086 1086
  ///
1087 1087
  /// The simplest way of using this map is through the scaleMap()
1088 1088
  /// function.
1089 1089
  ///
1090 1090
  /// \sa ScaleWriteMap
1091 1091
  template<typename M, typename C = typename M::Value>
1092 1092
  class ScaleMap : public MapBase<typename M::Key, typename M::Value> {
1093 1093
    const M &_m;
1094 1094
    C _v;
1095 1095
  public:
1096 1096
    typedef MapBase<typename M::Key, typename M::Value> Parent;
1097 1097
    typedef typename Parent::Key Key;
1098 1098
    typedef typename Parent::Value Value;
1099 1099

	
1100 1100
    /// Constructor
1101 1101

	
1102 1102
    /// Constructor.
1103 1103
    /// \param m The undelying map.
1104 1104
    /// \param v The constant value.
1105 1105
    ScaleMap(const M &m, const C &v) : _m(m), _v(v) {}
1106 1106
    /// \e
1107 1107
    Value operator[](const Key &k) const { return _v*_m[k]; }
1108 1108
  };
1109 1109

	
1110 1110
  /// Scales a map with a constant (read-write version).
1111 1111

	
1112 1112
  /// This \ref concepts::ReadWriteMap "read-write map" returns the value of
1113 1113
  /// the given map multiplied from the left side with a constant value.
1114 1114
  /// Its \c Key and \c Value are inherited from \c M.
1115 1115
  /// It can also be used as write map if the \c / operator is defined
1116 1116
  /// between \c Value and \c C and the given multiplier is not zero.
1117 1117
  ///
1118 1118
  /// The simplest way of using this map is through the scaleWriteMap()
1119 1119
  /// function.
1120 1120
  ///
1121 1121
  /// \sa ScaleMap
1122 1122
  template<typename M, typename C = typename M::Value>
1123 1123
  class ScaleWriteMap : public MapBase<typename M::Key, typename M::Value> {
1124 1124
    M &_m;
1125 1125
    C _v;
1126 1126
  public:
1127 1127
    typedef MapBase<typename M::Key, typename M::Value> Parent;
1128 1128
    typedef typename Parent::Key Key;
1129 1129
    typedef typename Parent::Value Value;
1130 1130

	
1131 1131
    /// Constructor
1132 1132

	
1133 1133
    /// Constructor.
1134 1134
    /// \param m The undelying map.
1135 1135
    /// \param v The constant value.
1136 1136
    ScaleWriteMap(M &m, const C &v) : _m(m), _v(v) {}
1137 1137
    /// \e
1138 1138
    Value operator[](const Key &k) const { return _v*_m[k]; }
1139 1139
    /// \e
1140 1140
    void set(const Key &k, const Value &v) { _m.set(k, v/_v); }
1141 1141
  };
1142 1142

	
1143 1143
  /// Returns a \c ScaleMap class
1144 1144

	
1145 1145
  /// This function just returns a \c ScaleMap class.
1146 1146
  ///
1147 1147
  /// For example, if \c m is a map with \c double values and \c v is
1148 1148
  /// \c double, then <tt>scaleMap(m,v)[x]</tt> will be equal to
1149 1149
  /// <tt>v*m[x]</tt>.
1150 1150
  ///
1151 1151
  /// \relates ScaleMap
1152 1152
  template<typename M, typename C>
1153 1153
  inline ScaleMap<M, C> scaleMap(const M &m, const C &v) {
1154 1154
    return ScaleMap<M, C>(m,v);
1155 1155
  }
1156 1156

	
1157 1157
  /// Returns a \c ScaleWriteMap class
1158 1158

	
1159 1159
  /// This function just returns a \c ScaleWriteMap class.
1160 1160
  ///
1161 1161
  /// For example, if \c m is a map with \c double values and \c v is
1162 1162
  /// \c double, then <tt>scaleWriteMap(m,v)[x]</tt> will be equal to
1163 1163
  /// <tt>v*m[x]</tt>.
1164 1164
  /// Moreover it makes also possible to write the map.
1165 1165
  ///
1166 1166
  /// \relates ScaleWriteMap
1167 1167
  template<typename M, typename C>
1168 1168
  inline ScaleWriteMap<M, C> scaleWriteMap(M &m, const C &v) {
1169 1169
    return ScaleWriteMap<M, C>(m,v);
1170 1170
  }
1171 1171

	
1172 1172

	
1173 1173
  /// Negative of a map
1174 1174

	
1175 1175
  /// This \ref concepts::ReadMap "read-only map" returns the negative
1176 1176
  /// of the values of the given map (using the unary \c - operator).
1177 1177
  /// Its \c Key and \c Value are inherited from \c M.
1178 1178
  ///
1179 1179
  /// If M::Value is \c int, \c double etc., then
1180 1180
  /// \code
1181 1181
  ///   NegMap<M> neg(m);
1182 1182
  /// \endcode
1183 1183
  /// is equivalent to
1184 1184
  /// \code
1185 1185
  ///   ScaleMap<M> neg(m,-1);
1186 1186
  /// \endcode
1187 1187
  ///
1188 1188
  /// The simplest way of using this map is through the negMap()
1189 1189
  /// function.
1190 1190
  ///
1191 1191
  /// \sa NegWriteMap
1192 1192
  template<typename M>
1193 1193
  class NegMap : public MapBase<typename M::Key, typename M::Value> {
1194 1194
    const M& _m;
1195 1195
  public:
1196 1196
    typedef MapBase<typename M::Key, typename M::Value> Parent;
1197 1197
    typedef typename Parent::Key Key;
1198 1198
    typedef typename Parent::Value Value;
1199 1199

	
1200 1200
    /// Constructor
1201 1201
    NegMap(const M &m) : _m(m) {}
1202 1202
    /// \e
1203 1203
    Value operator[](const Key &k) const { return -_m[k]; }
1204 1204
  };
1205 1205

	
1206 1206
  /// Negative of a map (read-write version)
1207 1207

	
1208 1208
  /// This \ref concepts::ReadWriteMap "read-write map" returns the
1209 1209
  /// negative of the values of the given map (using the unary \c -
1210 1210
  /// operator).
1211 1211
  /// Its \c Key and \c Value are inherited from \c M.
1212 1212
  /// It makes also possible to write the map.
1213 1213
  ///
1214 1214
  /// If M::Value is \c int, \c double etc., then
1215 1215
  /// \code
1216 1216
  ///   NegWriteMap<M> neg(m);
1217 1217
  /// \endcode
1218 1218
  /// is equivalent to
1219 1219
  /// \code
1220 1220
  ///   ScaleWriteMap<M> neg(m,-1);
1221 1221
  /// \endcode
1222 1222
  ///
1223 1223
  /// The simplest way of using this map is through the negWriteMap()
1224 1224
  /// function.
1225 1225
  ///
1226 1226
  /// \sa NegMap
1227 1227
  template<typename M>
1228 1228
  class NegWriteMap : public MapBase<typename M::Key, typename M::Value> {
1229 1229
    M &_m;
1230 1230
  public:
1231 1231
    typedef MapBase<typename M::Key, typename M::Value> Parent;
1232 1232
    typedef typename Parent::Key Key;
1233 1233
    typedef typename Parent::Value Value;
1234 1234

	
1235 1235
    /// Constructor
1236 1236
    NegWriteMap(M &m) : _m(m) {}
1237 1237
    /// \e
1238 1238
    Value operator[](const Key &k) const { return -_m[k]; }
1239 1239
    /// \e
1240 1240
    void set(const Key &k, const Value &v) { _m.set(k, -v); }
1241 1241
  };
1242 1242

	
1243 1243
  /// Returns a \c NegMap class
1244 1244

	
1245 1245
  /// This function just returns a \c NegMap class.
1246 1246
  ///
1247 1247
  /// For example, if \c m is a map with \c double values, then
1248 1248
  /// <tt>negMap(m)[x]</tt> will be equal to <tt>-m[x]</tt>.
1249 1249
  ///
1250 1250
  /// \relates NegMap
1251 1251
  template <typename M>
1252 1252
  inline NegMap<M> negMap(const M &m) {
1253 1253
    return NegMap<M>(m);
1254 1254
  }
1255 1255

	
1256 1256
  /// Returns a \c NegWriteMap class
1257 1257

	
1258 1258
  /// This function just returns a \c NegWriteMap class.
1259 1259
  ///
1260 1260
  /// For example, if \c m is a map with \c double values, then
1261 1261
  /// <tt>negWriteMap(m)[x]</tt> will be equal to <tt>-m[x]</tt>.
1262 1262
  /// Moreover it makes also possible to write the map.
1263 1263
  ///
1264 1264
  /// \relates NegWriteMap
1265 1265
  template <typename M>
1266 1266
  inline NegWriteMap<M> negWriteMap(M &m) {
1267 1267
    return NegWriteMap<M>(m);
1268 1268
  }
1269 1269

	
1270 1270

	
1271 1271
  /// Absolute value of a map
1272 1272

	
1273 1273
  /// This \ref concepts::ReadMap "read-only map" returns the absolute
1274 1274
  /// value of the values of the given map.
1275 1275
  /// Its \c Key and \c Value are inherited from \c M.
1276 1276
  /// \c Value must be comparable to \c 0 and the unary \c -
1277 1277
  /// operator must be defined for it, of course.
1278 1278
  ///
1279 1279
  /// The simplest way of using this map is through the absMap()
1280 1280
  /// function.
1281 1281
  template<typename M>
1282 1282
  class AbsMap : public MapBase<typename M::Key, typename M::Value> {
1283 1283
    const M &_m;
1284 1284
  public:
1285 1285
    typedef MapBase<typename M::Key, typename M::Value> Parent;
1286 1286
    typedef typename Parent::Key Key;
1287 1287
    typedef typename Parent::Value Value;
1288 1288

	
1289 1289
    /// Constructor
1290 1290
    AbsMap(const M &m) : _m(m) {}
1291 1291
    /// \e
1292 1292
    Value operator[](const Key &k) const {
1293 1293
      Value tmp = _m[k];
1294 1294
      return tmp >= 0 ? tmp : -tmp;
1295 1295
    }
1296 1296

	
1297 1297
  };
1298 1298

	
1299 1299
  /// Returns an \c AbsMap class
1300 1300

	
1301 1301
  /// This function just returns an \c AbsMap class.
1302 1302
  ///
1303 1303
  /// For example, if \c m is a map with \c double values, then
1304 1304
  /// <tt>absMap(m)[x]</tt> will be equal to <tt>m[x]</tt> if
1305 1305
  /// it is positive or zero and <tt>-m[x]</tt> if <tt>m[x]</tt> is
1306 1306
  /// negative.
1307 1307
  ///
1308 1308
  /// \relates AbsMap
1309 1309
  template<typename M>
1310 1310
  inline AbsMap<M> absMap(const M &m) {
1311 1311
    return AbsMap<M>(m);
1312 1312
  }
1313 1313

	
1314 1314
  /// @}
1315 1315

	
1316 1316
  // Logical maps and map adaptors:
1317 1317

	
1318 1318
  /// \addtogroup maps
1319 1319
  /// @{
1320 1320

	
1321 1321
  /// Constant \c true map.
1322 1322

	
1323 1323
  /// This \ref concepts::ReadMap "read-only map" assigns \c true to
1324 1324
  /// each key.
1325 1325
  ///
1326 1326
  /// Note that
1327 1327
  /// \code
1328 1328
  ///   TrueMap<K> tm;
1329 1329
  /// \endcode
1330 1330
  /// is equivalent to
1331 1331
  /// \code
1332 1332
  ///   ConstMap<K,bool> tm(true);
1333 1333
  /// \endcode
1334 1334
  ///
1335 1335
  /// \sa FalseMap
1336 1336
  /// \sa ConstMap
1337 1337
  template <typename K>
1338 1338
  class TrueMap : public MapBase<K, bool> {
1339 1339
  public:
1340 1340
    typedef MapBase<K, bool> Parent;
1341 1341
    typedef typename Parent::Key Key;
1342 1342
    typedef typename Parent::Value Value;
1343 1343

	
1344 1344
    /// Gives back \c true.
1345 1345
    Value operator[](const Key&) const { return true; }
1346 1346
  };
1347 1347

	
1348 1348
  /// Returns a \c TrueMap class
1349 1349

	
1350 1350
  /// This function just returns a \c TrueMap class.
1351 1351
  /// \relates TrueMap
1352 1352
  template<typename K>
1353 1353
  inline TrueMap<K> trueMap() {
1354 1354
    return TrueMap<K>();
1355 1355
  }
1356 1356

	
1357 1357

	
1358 1358
  /// Constant \c false map.
1359 1359

	
1360 1360
  /// This \ref concepts::ReadMap "read-only map" assigns \c false to
1361 1361
  /// each key.
1362 1362
  ///
1363 1363
  /// Note that
1364 1364
  /// \code
1365 1365
  ///   FalseMap<K> fm;
1366 1366
  /// \endcode
1367 1367
  /// is equivalent to
1368 1368
  /// \code
1369 1369
  ///   ConstMap<K,bool> fm(false);
1370 1370
  /// \endcode
1371 1371
  ///
1372 1372
  /// \sa TrueMap
1373 1373
  /// \sa ConstMap
1374 1374
  template <typename K>
1375 1375
  class FalseMap : public MapBase<K, bool> {
1376 1376
  public:
1377 1377
    typedef MapBase<K, bool> Parent;
1378 1378
    typedef typename Parent::Key Key;
1379 1379
    typedef typename Parent::Value Value;
1380 1380

	
1381 1381
    /// Gives back \c false.
1382 1382
    Value operator[](const Key&) const { return false; }
1383 1383
  };
1384 1384

	
1385 1385
  /// Returns a \c FalseMap class
1386 1386

	
1387 1387
  /// This function just returns a \c FalseMap class.
1388 1388
  /// \relates FalseMap
1389 1389
  template<typename K>
1390 1390
  inline FalseMap<K> falseMap() {
1391 1391
    return FalseMap<K>();
1392 1392
  }
1393 1393

	
1394 1394
  /// @}
1395 1395

	
1396 1396
  /// \addtogroup map_adaptors
1397 1397
  /// @{
1398 1398

	
1399 1399
  /// Logical 'and' of two maps
1400 1400

	
1401 1401
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1402 1402
  /// 'and' of the values of the two given maps.
1403 1403
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1404 1404
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1405 1405
  ///
1406 1406
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1407 1407
  /// \code
1408 1408
  ///   AndMap<M1,M2> am(m1,m2);
1409 1409
  /// \endcode
1410 1410
  /// <tt>am[x]</tt> will be equal to <tt>m1[x]&&m2[x]</tt>.
1411 1411
  ///
1412 1412
  /// The simplest way of using this map is through the andMap()
1413 1413
  /// function.
1414 1414
  ///
1415 1415
  /// \sa OrMap
1416 1416
  /// \sa NotMap, NotWriteMap
1417 1417
  template<typename M1, typename M2>
1418 1418
  class AndMap : public MapBase<typename M1::Key, bool> {
1419 1419
    const M1 &_m1;
1420 1420
    const M2 &_m2;
1421 1421
  public:
1422 1422
    typedef MapBase<typename M1::Key, bool> Parent;
1423 1423
    typedef typename Parent::Key Key;
1424 1424
    typedef typename Parent::Value Value;
1425 1425

	
1426 1426
    /// Constructor
1427 1427
    AndMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1428 1428
    /// \e
1429 1429
    Value operator[](const Key &k) const { return _m1[k]&&_m2[k]; }
1430 1430
  };
1431 1431

	
1432 1432
  /// Returns an \c AndMap class
1433 1433

	
1434 1434
  /// This function just returns an \c AndMap class.
1435 1435
  ///
1436 1436
  /// For example, if \c m1 and \c m2 are both maps with \c bool values,
1437 1437
  /// then <tt>andMap(m1,m2)[x]</tt> will be equal to
1438 1438
  /// <tt>m1[x]&&m2[x]</tt>.
1439 1439
  ///
1440 1440
  /// \relates AndMap
1441 1441
  template<typename M1, typename M2>
1442 1442
  inline AndMap<M1, M2> andMap(const M1 &m1, const M2 &m2) {
1443 1443
    return AndMap<M1, M2>(m1,m2);
1444 1444
  }
1445 1445

	
1446 1446

	
1447 1447
  /// Logical 'or' of two maps
1448 1448

	
1449 1449
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1450 1450
  /// 'or' of the values of the two given maps.
1451 1451
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1452 1452
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1453 1453
  ///
1454 1454
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1455 1455
  /// \code
1456 1456
  ///   OrMap<M1,M2> om(m1,m2);
1457 1457
  /// \endcode
1458 1458
  /// <tt>om[x]</tt> will be equal to <tt>m1[x]||m2[x]</tt>.
1459 1459
  ///
1460 1460
  /// The simplest way of using this map is through the orMap()
1461 1461
  /// function.
1462 1462
  ///
1463 1463
  /// \sa AndMap
1464 1464
  /// \sa NotMap, NotWriteMap
1465 1465
  template<typename M1, typename M2>
1466 1466
  class OrMap : public MapBase<typename M1::Key, bool> {
1467 1467
    const M1 &_m1;
1468 1468
    const M2 &_m2;
1469 1469
  public:
1470 1470
    typedef MapBase<typename M1::Key, bool> Parent;
1471 1471
    typedef typename Parent::Key Key;
1472 1472
    typedef typename Parent::Value Value;
1473 1473

	
1474 1474
    /// Constructor
1475 1475
    OrMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1476 1476
    /// \e
1477 1477
    Value operator[](const Key &k) const { return _m1[k]||_m2[k]; }
1478 1478
  };
1479 1479

	
1480 1480
  /// Returns an \c OrMap class
1481 1481

	
1482 1482
  /// This function just returns an \c OrMap class.
1483 1483
  ///
1484 1484
  /// For example, if \c m1 and \c m2 are both maps with \c bool values,
1485 1485
  /// then <tt>orMap(m1,m2)[x]</tt> will be equal to
1486 1486
  /// <tt>m1[x]||m2[x]</tt>.
1487 1487
  ///
1488 1488
  /// \relates OrMap
1489 1489
  template<typename M1, typename M2>
1490 1490
  inline OrMap<M1, M2> orMap(const M1 &m1, const M2 &m2) {
1491 1491
    return OrMap<M1, M2>(m1,m2);
1492 1492
  }
1493 1493

	
1494 1494

	
1495 1495
  /// Logical 'not' of a map
1496 1496

	
1497 1497
  /// This \ref concepts::ReadMap "read-only map" returns the logical
1498 1498
  /// negation of the values of the given map.
1499 1499
  /// Its \c Key is inherited from \c M and its \c Value is \c bool.
1500 1500
  ///
1501 1501
  /// The simplest way of using this map is through the notMap()
1502 1502
  /// function.
1503 1503
  ///
1504 1504
  /// \sa NotWriteMap
1505 1505
  template <typename M>
1506 1506
  class NotMap : public MapBase<typename M::Key, bool> {
1507 1507
    const M &_m;
1508 1508
  public:
1509 1509
    typedef MapBase<typename M::Key, bool> Parent;
1510 1510
    typedef typename Parent::Key Key;
1511 1511
    typedef typename Parent::Value Value;
1512 1512

	
1513 1513
    /// Constructor
1514 1514
    NotMap(const M &m) : _m(m) {}
1515 1515
    /// \e
1516 1516
    Value operator[](const Key &k) const { return !_m[k]; }
1517 1517
  };
1518 1518

	
1519 1519
  /// Logical 'not' of a map (read-write version)
1520 1520

	
1521 1521
  /// This \ref concepts::ReadWriteMap "read-write map" returns the
1522 1522
  /// logical negation of the values of the given map.
1523 1523
  /// Its \c Key is inherited from \c M and its \c Value is \c bool.
1524 1524
  /// It makes also possible to write the map. When a value is set,
1525 1525
  /// the opposite value is set to the original map.
1526 1526
  ///
1527 1527
  /// The simplest way of using this map is through the notWriteMap()
1528 1528
  /// function.
1529 1529
  ///
1530 1530
  /// \sa NotMap
1531 1531
  template <typename M>
1532 1532
  class NotWriteMap : public MapBase<typename M::Key, bool> {
1533 1533
    M &_m;
1534 1534
  public:
1535 1535
    typedef MapBase<typename M::Key, bool> Parent;
1536 1536
    typedef typename Parent::Key Key;
1537 1537
    typedef typename Parent::Value Value;
1538 1538

	
1539 1539
    /// Constructor
1540 1540
    NotWriteMap(M &m) : _m(m) {}
1541 1541
    /// \e
1542 1542
    Value operator[](const Key &k) const { return !_m[k]; }
1543 1543
    /// \e
1544 1544
    void set(const Key &k, bool v) { _m.set(k, !v); }
1545 1545
  };
1546 1546

	
1547 1547
  /// Returns a \c NotMap class
1548 1548

	
1549 1549
  /// This function just returns a \c NotMap class.
1550 1550
  ///
1551 1551
  /// For example, if \c m is a map with \c bool values, then
1552 1552
  /// <tt>notMap(m)[x]</tt> will be equal to <tt>!m[x]</tt>.
1553 1553
  ///
1554 1554
  /// \relates NotMap
1555 1555
  template <typename M>
1556 1556
  inline NotMap<M> notMap(const M &m) {
1557 1557
    return NotMap<M>(m);
1558 1558
  }
1559 1559

	
1560 1560
  /// Returns a \c NotWriteMap class
1561 1561

	
1562 1562
  /// This function just returns a \c NotWriteMap class.
1563 1563
  ///
1564 1564
  /// For example, if \c m is a map with \c bool values, then
1565 1565
  /// <tt>notWriteMap(m)[x]</tt> will be equal to <tt>!m[x]</tt>.
1566 1566
  /// Moreover it makes also possible to write the map.
1567 1567
  ///
1568 1568
  /// \relates NotWriteMap
1569 1569
  template <typename M>
1570 1570
  inline NotWriteMap<M> notWriteMap(M &m) {
1571 1571
    return NotWriteMap<M>(m);
1572 1572
  }
1573 1573

	
1574 1574

	
1575 1575
  /// Combination of two maps using the \c == operator
1576 1576

	
1577 1577
  /// This \ref concepts::ReadMap "read-only map" assigns \c true to
1578 1578
  /// the keys for which the corresponding values of the two maps are
1579 1579
  /// equal.
1580 1580
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1581 1581
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1582 1582
  ///
1583 1583
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1584 1584
  /// \code
1585 1585
  ///   EqualMap<M1,M2> em(m1,m2);
1586 1586
  /// \endcode
1587 1587
  /// <tt>em[x]</tt> will be equal to <tt>m1[x]==m2[x]</tt>.
1588 1588
  ///
1589 1589
  /// The simplest way of using this map is through the equalMap()
1590 1590
  /// function.
1591 1591
  ///
1592 1592
  /// \sa LessMap
1593 1593
  template<typename M1, typename M2>
1594 1594
  class EqualMap : public MapBase<typename M1::Key, bool> {
1595 1595
    const M1 &_m1;
1596 1596
    const M2 &_m2;
1597 1597
  public:
1598 1598
    typedef MapBase<typename M1::Key, bool> Parent;
1599 1599
    typedef typename Parent::Key Key;
1600 1600
    typedef typename Parent::Value Value;
1601 1601

	
1602 1602
    /// Constructor
1603 1603
    EqualMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1604 1604
    /// \e
1605 1605
    Value operator[](const Key &k) const { return _m1[k]==_m2[k]; }
1606 1606
  };
1607 1607

	
1608 1608
  /// Returns an \c EqualMap class
1609 1609

	
1610 1610
  /// This function just returns an \c EqualMap class.
1611 1611
  ///
1612 1612
  /// For example, if \c m1 and \c m2 are maps with keys and values of
1613 1613
  /// the same type, then <tt>equalMap(m1,m2)[x]</tt> will be equal to
1614 1614
  /// <tt>m1[x]==m2[x]</tt>.
1615 1615
  ///
1616 1616
  /// \relates EqualMap
1617 1617
  template<typename M1, typename M2>
1618 1618
  inline EqualMap<M1, M2> equalMap(const M1 &m1, const M2 &m2) {
1619 1619
    return EqualMap<M1, M2>(m1,m2);
1620 1620
  }
1621 1621

	
1622 1622

	
1623 1623
  /// Combination of two maps using the \c < operator
1624 1624

	
1625 1625
  /// This \ref concepts::ReadMap "read-only map" assigns \c true to
1626 1626
  /// the keys for which the corresponding value of the first map is
1627 1627
  /// less then the value of the second map.
1628 1628
  /// Its \c Key type is inherited from \c M1 and its \c Value type is
1629 1629
  /// \c bool. \c M2::Key must be convertible to \c M1::Key.
1630 1630
  ///
1631 1631
  /// If \c m1 is of type \c M1 and \c m2 is of \c M2, then for
1632 1632
  /// \code
1633 1633
  ///   LessMap<M1,M2> lm(m1,m2);
1634 1634
  /// \endcode
1635 1635
  /// <tt>lm[x]</tt> will be equal to <tt>m1[x]<m2[x]</tt>.
1636 1636
  ///
1637 1637
  /// The simplest way of using this map is through the lessMap()
1638 1638
  /// function.
1639 1639
  ///
1640 1640
  /// \sa EqualMap
1641 1641
  template<typename M1, typename M2>
1642 1642
  class LessMap : public MapBase<typename M1::Key, bool> {
1643 1643
    const M1 &_m1;
1644 1644
    const M2 &_m2;
1645 1645
  public:
1646 1646
    typedef MapBase<typename M1::Key, bool> Parent;
1647 1647
    typedef typename Parent::Key Key;
1648 1648
    typedef typename Parent::Value Value;
1649 1649

	
1650 1650
    /// Constructor
1651 1651
    LessMap(const M1 &m1, const M2 &m2) : _m1(m1), _m2(m2) {}
1652 1652
    /// \e
1653 1653
    Value operator[](const Key &k) const { return _m1[k]<_m2[k]; }
1654 1654
  };
1655 1655

	
1656 1656
  /// Returns an \c LessMap class
1657 1657

	
1658 1658
  /// This function just returns an \c LessMap class.
1659 1659
  ///
1660 1660
  /// For example, if \c m1 and \c m2 are maps with keys and values of
1661 1661
  /// the same type, then <tt>lessMap(m1,m2)[x]</tt> will be equal to
1662 1662
  /// <tt>m1[x]<m2[x]</tt>.
1663 1663
  ///
1664 1664
  /// \relates LessMap
1665 1665
  template<typename M1, typename M2>
1666 1666
  inline LessMap<M1, M2> lessMap(const M1 &m1, const M2 &m2) {
1667 1667
    return LessMap<M1, M2>(m1,m2);
1668 1668
  }
1669 1669

	
1670 1670
  namespace _maps_bits {
1671 1671

	
1672 1672
    template <typename _Iterator, typename Enable = void>
1673 1673
    struct IteratorTraits {
1674 1674
      typedef typename std::iterator_traits<_Iterator>::value_type Value;
1675 1675
    };
1676 1676

	
1677 1677
    template <typename _Iterator>
1678 1678
    struct IteratorTraits<_Iterator,
1679 1679
      typename exists<typename _Iterator::container_type>::type>
1680 1680
    {
1681 1681
      typedef typename _Iterator::container_type::value_type Value;
1682 1682
    };
1683 1683

	
1684 1684
  }
1685 1685

	
1686 1686
  /// \brief Writable bool map for logging each \c true assigned element
1687 1687
  ///
1688 1688
  /// A \ref concepts::WriteMap "writable" bool map for logging
1689 1689
  /// each \c true assigned element, i.e it copies subsequently each
1690 1690
  /// keys set to \c true to the given iterator.
1691 1691
  /// The most important usage of it is storing certain nodes or arcs
1692 1692
  /// that were marked \c true by an algorithm.
1693 1693
  ///
1694 1694
  /// There are several algorithms that provide solutions through bool
1695 1695
  /// maps and most of them assign \c true at most once for each key.
1696 1696
  /// In these cases it is a natural request to store each \c true
1697 1697
  /// assigned elements (in order of the assignment), which can be
1698 1698
  /// easily done with LoggerBoolMap.
1699 1699
  ///
1700 1700
  /// The simplest way of using this map is through the loggerBoolMap()
1701 1701
  /// function.
1702 1702
  ///
1703 1703
  /// \tparam It The type of the iterator.
1704 1704
  /// \tparam Ke The key type of the map. The default value set
1705 1705
  /// according to the iterator type should work in most cases.
1706 1706
  ///
1707 1707
  /// \note The container of the iterator must contain enough space
1708 1708
  /// for the elements or the iterator should be an inserter iterator.
1709 1709
#ifdef DOXYGEN
1710 1710
  template <typename It, typename Ke>
1711 1711
#else
1712 1712
  template <typename It,
1713 1713
            typename Ke=typename _maps_bits::IteratorTraits<It>::Value>
1714 1714
#endif
1715 1715
  class LoggerBoolMap {
1716 1716
  public:
1717 1717
    typedef It Iterator;
1718 1718

	
1719 1719
    typedef Ke Key;
1720 1720
    typedef bool Value;
1721 1721

	
1722 1722
    /// Constructor
1723 1723
    LoggerBoolMap(Iterator it)
1724 1724
      : _begin(it), _end(it) {}
1725 1725

	
1726 1726
    /// Gives back the given iterator set for the first key
1727 1727
    Iterator begin() const {
1728 1728
      return _begin;
1729 1729
    }
1730 1730

	
1731 1731
    /// Gives back the the 'after the last' iterator
1732 1732
    Iterator end() const {
1733 1733
      return _end;
1734 1734
    }
1735 1735

	
1736 1736
    /// The set function of the map
1737 1737
    void set(const Key& key, Value value) {
1738 1738
      if (value) {
1739 1739
        *_end++ = key;
1740 1740
      }
1741 1741
    }
1742 1742

	
1743 1743
  private:
1744 1744
    Iterator _begin;
1745 1745
    Iterator _end;
1746 1746
  };
1747 1747

	
1748 1748
  /// Returns a \c LoggerBoolMap class
1749 1749

	
1750 1750
  /// This function just returns a \c LoggerBoolMap class.
1751 1751
  ///
1752 1752
  /// The most important usage of it is storing certain nodes or arcs
1753 1753
  /// that were marked \c true by an algorithm.
1754 1754
  /// For example it makes easier to store the nodes in the processing
1755 1755
  /// order of Dfs algorithm, as the following examples show.
1756 1756
  /// \code
1757 1757
  ///   std::vector<Node> v;
1758 1758
  ///   dfs(g,s).processedMap(loggerBoolMap(std::back_inserter(v))).run();
1759 1759
  /// \endcode
1760 1760
  /// \code
1761 1761
  ///   std::vector<Node> v(countNodes(g));
1762 1762
  ///   dfs(g,s).processedMap(loggerBoolMap(v.begin())).run();
1763 1763
  /// \endcode
1764 1764
  ///
1765 1765
  /// \note The container of the iterator must contain enough space
1766 1766
  /// for the elements or the iterator should be an inserter iterator.
1767 1767
  ///
1768 1768
  /// \note LoggerBoolMap is just \ref concepts::WriteMap "writable", so
1769 1769
  /// it cannot be used when a readable map is needed, for example as
1770 1770
  /// \c ReachedMap for \c Bfs, \c Dfs and \c Dijkstra algorithms.
1771 1771
  ///
1772 1772
  /// \relates LoggerBoolMap
1773 1773
  template<typename Iterator>
1774 1774
  inline LoggerBoolMap<Iterator> loggerBoolMap(Iterator it) {
1775 1775
    return LoggerBoolMap<Iterator>(it);
1776 1776
  }
1777 1777

	
1778 1778
  /// Provides an immutable and unique id for each item in the graph.
1779 1779

	
1780 1780
  /// The IdMap class provides a unique and immutable id for each item of the
1781 1781
  /// same type (e.g. node) in the graph. This id is <ul><li>\b unique:
1782 1782
  /// different items (nodes) get different ids <li>\b immutable: the id of an
1783 1783
  /// item (node) does not change (even if you delete other nodes).  </ul>
1784 1784
  /// Through this map you get access (i.e. can read) the inner id values of
1785 1785
  /// the items stored in the graph. This map can be inverted with its member
1786 1786
  /// class \c InverseMap or with the \c operator() member.
1787 1787
  ///
1788 1788
  template <typename _Graph, typename _Item>
1789 1789
  class IdMap {
1790 1790
  public:
1791 1791
    typedef _Graph Graph;
1792 1792
    typedef int Value;
1793 1793
    typedef _Item Item;
1794 1794
    typedef _Item Key;
1795 1795

	
1796 1796
    /// \brief Constructor.
1797 1797
    ///
1798 1798
    /// Constructor of the map.
1799 1799
    explicit IdMap(const Graph& graph) : _graph(&graph) {}
1800 1800

	
1801 1801
    /// \brief Gives back the \e id of the item.
1802 1802
    ///
1803 1803
    /// Gives back the immutable and unique \e id of the item.
1804 1804
    int operator[](const Item& item) const { return _graph->id(item);}
1805 1805

	
1806 1806
    /// \brief Gives back the item by its id.
1807 1807
    ///
1808 1808
    /// Gives back the item by its id.
1809 1809
    Item operator()(int id) { return _graph->fromId(id, Item()); }
1810 1810

	
1811 1811
  private:
1812 1812
    const Graph* _graph;
1813 1813

	
1814 1814
  public:
1815 1815

	
1816 1816
    /// \brief The class represents the inverse of its owner (IdMap).
1817 1817
    ///
1818 1818
    /// The class represents the inverse of its owner (IdMap).
1819 1819
    /// \see inverse()
1820 1820
    class InverseMap {
1821 1821
    public:
1822 1822

	
1823 1823
      /// \brief Constructor.
1824 1824
      ///
1825 1825
      /// Constructor for creating an id-to-item map.
1826 1826
      explicit InverseMap(const Graph& graph) : _graph(&graph) {}
1827 1827

	
1828 1828
      /// \brief Constructor.
1829 1829
      ///
1830 1830
      /// Constructor for creating an id-to-item map.
1831 1831
      explicit InverseMap(const IdMap& map) : _graph(map._graph) {}
1832 1832

	
1833 1833
      /// \brief Gives back the given item from its id.
1834 1834
      ///
1835 1835
      /// Gives back the given item from its id.
1836 1836
      ///
1837 1837
      Item operator[](int id) const { return _graph->fromId(id, Item());}
1838 1838

	
1839 1839
    private:
1840 1840
      const Graph* _graph;
1841 1841
    };
1842 1842

	
1843 1843
    /// \brief Gives back the inverse of the map.
1844 1844
    ///
1845 1845
    /// Gives back the inverse of the IdMap.
1846 1846
    InverseMap inverse() const { return InverseMap(*_graph);}
1847 1847

	
1848 1848
  };
1849 1849

	
1850 1850

	
1851 1851
  /// \brief General invertable graph-map type.
1852 1852

	
1853 1853
  /// This type provides simple invertable graph-maps.
1854 1854
  /// The InvertableMap wraps an arbitrary ReadWriteMap
1855 1855
  /// and if a key is set to a new value then store it
1856 1856
  /// in the inverse map.
1857 1857
  ///
1858 1858
  /// The values of the map can be accessed
1859 1859
  /// with stl compatible forward iterator.
1860 1860
  ///
1861 1861
  /// \tparam _Graph The graph type.
1862 1862
  /// \tparam _Item The item type of the graph.
1863 1863
  /// \tparam _Value The value type of the map.
1864 1864
  ///
1865 1865
  /// \see IterableValueMap
1866 1866
  template <typename _Graph, typename _Item, typename _Value>
1867 1867
  class InvertableMap
1868 1868
    : protected ItemSetTraits<_Graph, _Item>::template Map<_Value>::Type {
1869 1869
  private:
1870 1870

	
1871 1871
    typedef typename ItemSetTraits<_Graph, _Item>::
1872 1872
    template Map<_Value>::Type Map;
1873 1873
    typedef _Graph Graph;
1874 1874

	
1875 1875
    typedef std::map<_Value, _Item> Container;
1876 1876
    Container _inv_map;
1877 1877

	
1878 1878
  public:
1879 1879

	
1880 1880
    /// The key type of InvertableMap (Node, Arc, Edge).
1881 1881
    typedef typename Map::Key Key;
1882 1882
    /// The value type of the InvertableMap.
1883 1883
    typedef typename Map::Value Value;
1884 1884

	
1885 1885

	
1886 1886

	
1887 1887
    /// \brief Constructor.
1888 1888
    ///
1889 1889
    /// Construct a new InvertableMap for the graph.
1890 1890
    ///
1891 1891
    explicit InvertableMap(const Graph& graph) : Map(graph) {}
1892 1892

	
1893 1893
    /// \brief Forward iterator for values.
1894 1894
    ///
1895 1895
    /// This iterator is an stl compatible forward
1896 1896
    /// iterator on the values of the map. The values can
1897 1897
    /// be accessed in the [beginValue, endValue) range.
1898 1898
    ///
1899 1899
    class ValueIterator
1900 1900
      : public std::iterator<std::forward_iterator_tag, Value> {
1901 1901
      friend class InvertableMap;
1902 1902
    private:
1903 1903
      ValueIterator(typename Container::const_iterator _it)
1904 1904
        : it(_it) {}
1905 1905
    public:
1906 1906

	
1907 1907
      ValueIterator() {}
1908 1908

	
1909 1909
      ValueIterator& operator++() { ++it; return *this; }
1910 1910
      ValueIterator operator++(int) {
1911 1911
        ValueIterator tmp(*this);
1912 1912
        operator++();
1913 1913
        return tmp;
1914 1914
      }
1915 1915

	
1916 1916
      const Value& operator*() const { return it->first; }
1917 1917
      const Value* operator->() const { return &(it->first); }
1918 1918

	
1919 1919
      bool operator==(ValueIterator jt) const { return it == jt.it; }
1920 1920
      bool operator!=(ValueIterator jt) const { return it != jt.it; }
1921 1921

	
1922 1922
    private:
1923 1923
      typename Container::const_iterator it;
1924 1924
    };
1925 1925

	
1926 1926
    /// \brief Returns an iterator to the first value.
1927 1927
    ///
1928 1928
    /// Returns an stl compatible iterator to the
1929 1929
    /// first value of the map. The values of the
1930 1930
    /// map can be accessed in the [beginValue, endValue)
1931 1931
    /// range.
1932 1932
    ValueIterator beginValue() const {
1933 1933
      return ValueIterator(_inv_map.begin());
1934 1934
    }
1935 1935

	
1936 1936
    /// \brief Returns an iterator after the last value.
1937 1937
    ///
1938 1938
    /// Returns an stl compatible iterator after the
1939 1939
    /// last value of the map. The values of the
1940 1940
    /// map can be accessed in the [beginValue, endValue)
1941 1941
    /// range.
1942 1942
    ValueIterator endValue() const {
1943 1943
      return ValueIterator(_inv_map.end());
1944 1944
    }
1945 1945

	
1946 1946
    /// \brief The setter function of the map.
1947 1947
    ///
1948 1948
    /// Sets the mapped value.
1949 1949
    void set(const Key& key, const Value& val) {
1950 1950
      Value oldval = Map::operator[](key);
1951 1951
      typename Container::iterator it = _inv_map.find(oldval);
1952 1952
      if (it != _inv_map.end() && it->second == key) {
1953 1953
        _inv_map.erase(it);
1954 1954
      }
1955 1955
      _inv_map.insert(make_pair(val, key));
1956 1956
      Map::set(key, val);
1957 1957
    }
1958 1958

	
1959 1959
    /// \brief The getter function of the map.
1960 1960
    ///
1961 1961
    /// It gives back the value associated with the key.
1962 1962
    typename MapTraits<Map>::ConstReturnValue
1963 1963
    operator[](const Key& key) const {
1964 1964
      return Map::operator[](key);
1965 1965
    }
1966 1966

	
1967 1967
    /// \brief Gives back the item by its value.
1968 1968
    ///
1969 1969
    /// Gives back the item by its value.
1970 1970
    Key operator()(const Value& key) const {
1971 1971
      typename Container::const_iterator it = _inv_map.find(key);
1972 1972
      return it != _inv_map.end() ? it->second : INVALID;
1973 1973
    }
1974 1974

	
1975 1975
  protected:
1976 1976

	
1977 1977
    /// \brief Erase the key from the map.
1978 1978
    ///
1979 1979
    /// Erase the key to the map. It is called by the
1980 1980
    /// \c AlterationNotifier.
1981 1981
    virtual void erase(const Key& key) {
1982 1982
      Value val = Map::operator[](key);
1983 1983
      typename Container::iterator it = _inv_map.find(val);
1984 1984
      if (it != _inv_map.end() && it->second == key) {
1985 1985
        _inv_map.erase(it);
1986 1986
      }
1987 1987
      Map::erase(key);
1988 1988
    }
1989 1989

	
1990 1990
    /// \brief Erase more keys from the map.
1991 1991
    ///
1992 1992
    /// Erase more keys from the map. It is called by the
1993 1993
    /// \c AlterationNotifier.
1994 1994
    virtual void erase(const std::vector<Key>& keys) {
1995 1995
      for (int i = 0; i < int(keys.size()); ++i) {
1996 1996
        Value val = Map::operator[](keys[i]);
1997 1997
        typename Container::iterator it = _inv_map.find(val);
1998 1998
        if (it != _inv_map.end() && it->second == keys[i]) {
1999 1999
          _inv_map.erase(it);
2000 2000
        }
2001 2001
      }
2002 2002
      Map::erase(keys);
2003 2003
    }
2004 2004

	
2005 2005
    /// \brief Clear the keys from the map and inverse map.
2006 2006
    ///
2007 2007
    /// Clear the keys from the map and inverse map. It is called by the
2008 2008
    /// \c AlterationNotifier.
2009 2009
    virtual void clear() {
2010 2010
      _inv_map.clear();
2011 2011
      Map::clear();
2012 2012
    }
2013 2013

	
2014 2014
  public:
2015 2015

	
2016 2016
    /// \brief The inverse map type.
2017 2017
    ///
2018 2018
    /// The inverse of this map. The subscript operator of the map
2019 2019
    /// gives back always the item what was last assigned to the value.
2020 2020
    class InverseMap {
2021 2021
    public:
2022 2022
      /// \brief Constructor of the InverseMap.
2023 2023
      ///
2024 2024
      /// Constructor of the InverseMap.
2025 2025
      explicit InverseMap(const InvertableMap& inverted)
2026 2026
        : _inverted(inverted) {}
2027 2027

	
2028 2028
      /// The value type of the InverseMap.
2029 2029
      typedef typename InvertableMap::Key Value;
2030 2030
      /// The key type of the InverseMap.
2031 2031
      typedef typename InvertableMap::Value Key;
2032 2032

	
2033 2033
      /// \brief Subscript operator.
2034 2034
      ///
2035 2035
      /// Subscript operator. It gives back always the item
2036 2036
      /// what was last assigned to the value.
2037 2037
      Value operator[](const Key& key) const {
2038 2038
        return _inverted(key);
2039 2039
      }
2040 2040

	
2041 2041
    private:
2042 2042
      const InvertableMap& _inverted;
2043 2043
    };
2044 2044

	
2045 2045
    /// \brief It gives back the just readable inverse map.
2046 2046
    ///
2047 2047
    /// It gives back the just readable inverse map.
2048 2048
    InverseMap inverse() const {
2049 2049
      return InverseMap(*this);
2050 2050
    }
2051 2051

	
2052 2052

	
2053 2053

	
2054 2054
  };
2055 2055

	
2056 2056
  /// \brief Provides a mutable, continuous and unique descriptor for each
2057 2057
  /// item in the graph.
2058 2058
  ///
2059 2059
  /// The DescriptorMap class provides a unique and continuous (but mutable)
2060 2060
  /// descriptor (id) for each item of the same type (e.g. node) in the
2061 2061
  /// graph. This id is <ul><li>\b unique: different items (nodes) get
2062 2062
  /// different ids <li>\b continuous: the range of the ids is the set of
2063 2063
  /// integers between 0 and \c n-1, where \c n is the number of the items of
2064 2064
  /// this type (e.g. nodes) (so the id of a node can change if you delete an
2065 2065
  /// other node, i.e. this id is mutable).  </ul> This map can be inverted
2066 2066
  /// with its member class \c InverseMap, or with the \c operator() member.
2067 2067
  ///
2068 2068
  /// \tparam _Graph The graph class the \c DescriptorMap belongs to.
2069 2069
  /// \tparam _Item The Item is the Key of the Map. It may be Node, Arc or
2070 2070
  /// Edge.
2071 2071
  template <typename _Graph, typename _Item>
2072 2072
  class DescriptorMap
2073 2073
    : protected ItemSetTraits<_Graph, _Item>::template Map<int>::Type {
2074 2074

	
2075 2075
    typedef _Item Item;
2076 2076
    typedef typename ItemSetTraits<_Graph, _Item>::template Map<int>::Type Map;
2077 2077

	
2078 2078
  public:
2079 2079
    /// The graph class of DescriptorMap.
2080 2080
    typedef _Graph Graph;
2081 2081

	
2082 2082
    /// The key type of DescriptorMap (Node, Arc, Edge).
2083 2083
    typedef typename Map::Key Key;
2084 2084
    /// The value type of DescriptorMap.
2085 2085
    typedef typename Map::Value Value;
2086 2086

	
2087 2087
    /// \brief Constructor.
2088 2088
    ///
2089 2089
    /// Constructor for descriptor map.
2090 2090
    explicit DescriptorMap(const Graph& _graph) : Map(_graph) {
2091 2091
      Item it;
2092 2092
      const typename Map::Notifier* nf = Map::notifier();
2093 2093
      for (nf->first(it); it != INVALID; nf->next(it)) {
2094 2094
        Map::set(it, _inv_map.size());
2095 2095
        _inv_map.push_back(it);
2096 2096
      }
2097 2097
    }
2098 2098

	
2099 2099
  protected:
2100 2100

	
2101 2101
    /// \brief Add a new key to the map.
2102 2102
    ///
2103 2103
    /// Add a new key to the map. It is called by the
2104 2104
    /// \c AlterationNotifier.
2105 2105
    virtual void add(const Item& item) {
2106 2106
      Map::add(item);
2107 2107
      Map::set(item, _inv_map.size());
2108 2108
      _inv_map.push_back(item);
2109 2109
    }
2110 2110

	
2111 2111
    /// \brief Add more new keys to the map.
2112 2112
    ///
2113 2113
    /// Add more new keys to the map. It is called by the
2114 2114
    /// \c AlterationNotifier.
2115 2115
    virtual void add(const std::vector<Item>& items) {
2116 2116
      Map::add(items);
2117 2117
      for (int i = 0; i < int(items.size()); ++i) {
2118 2118
        Map::set(items[i], _inv_map.size());
2119 2119
        _inv_map.push_back(items[i]);
2120 2120
      }
2121 2121
    }
2122 2122

	
2123 2123
    /// \brief Erase the key from the map.
2124 2124
    ///
2125 2125
    /// Erase the key from the map. It is called by the
2126 2126
    /// \c AlterationNotifier.
2127 2127
    virtual void erase(const Item& item) {
2128 2128
      Map::set(_inv_map.back(), Map::operator[](item));
2129 2129
      _inv_map[Map::operator[](item)] = _inv_map.back();
2130 2130
      _inv_map.pop_back();
2131 2131
      Map::erase(item);
2132 2132
    }
2133 2133

	
2134 2134
    /// \brief Erase more keys from the map.
2135 2135
    ///
2136 2136
    /// Erase more keys from the map. It is called by the
2137 2137
    /// \c AlterationNotifier.
2138 2138
    virtual void erase(const std::vector<Item>& items) {
2139 2139
      for (int i = 0; i < int(items.size()); ++i) {
2140 2140
        Map::set(_inv_map.back(), Map::operator[](items[i]));
2141 2141
        _inv_map[Map::operator[](items[i])] = _inv_map.back();
2142 2142
        _inv_map.pop_back();
2143 2143
      }
2144 2144
      Map::erase(items);
2145 2145
    }
2146 2146

	
2147 2147
    /// \brief Build the unique map.
2148 2148
    ///
2149 2149
    /// Build the unique map. It is called by the
2150 2150
    /// \c AlterationNotifier.
2151 2151
    virtual void build() {
2152 2152
      Map::build();
2153 2153
      Item it;
2154 2154
      const typename Map::Notifier* nf = Map::notifier();
2155 2155
      for (nf->first(it); it != INVALID; nf->next(it)) {
2156 2156
        Map::set(it, _inv_map.size());
2157 2157
        _inv_map.push_back(it);
2158 2158
      }
2159 2159
    }
2160 2160

	
2161 2161
    /// \brief Clear the keys from the map.
2162 2162
    ///
2163 2163
    /// Clear the keys from the map. It is called by the
2164 2164
    /// \c AlterationNotifier.
2165 2165
    virtual void clear() {
2166 2166
      _inv_map.clear();
2167 2167
      Map::clear();
2168 2168
    }
2169 2169

	
2170 2170
  public:
2171 2171

	
2172 2172
    /// \brief Returns the maximal value plus one.
2173 2173
    ///
2174 2174
    /// Returns the maximal value plus one in the map.
2175 2175
    unsigned int size() const {
2176 2176
      return _inv_map.size();
2177 2177
    }
2178 2178

	
2179 2179
    /// \brief Swaps the position of the two items in the map.
2180 2180
    ///
2181 2181
    /// Swaps the position of the two items in the map.
2182 2182
    void swap(const Item& p, const Item& q) {
2183 2183
      int pi = Map::operator[](p);
2184 2184
      int qi = Map::operator[](q);
2185 2185
      Map::set(p, qi);
2186 2186
      _inv_map[qi] = p;
2187 2187
      Map::set(q, pi);
2188 2188
      _inv_map[pi] = q;
2189 2189
    }
2190 2190

	
2191 2191
    /// \brief Gives back the \e descriptor of the item.
2192 2192
    ///
2193 2193
    /// Gives back the mutable and unique \e descriptor of the map.
2194 2194
    int operator[](const Item& item) const {
2195 2195
      return Map::operator[](item);
2196 2196
    }
2197 2197

	
2198 2198
    /// \brief Gives back the item by its descriptor.
2199 2199
    ///
2200 2200
    /// Gives back th item by its descriptor.
2201 2201
    Item operator()(int id) const {
2202 2202
      return _inv_map[id];
2203 2203
    }
2204 2204

	
2205 2205
  private:
2206 2206

	
2207 2207
    typedef std::vector<Item> Container;
2208 2208
    Container _inv_map;
2209 2209

	
2210 2210
  public:
2211 2211
    /// \brief The inverse map type of DescriptorMap.
2212 2212
    ///
2213 2213
    /// The inverse map type of DescriptorMap.
2214 2214
    class InverseMap {
2215 2215
    public:
2216 2216
      /// \brief Constructor of the InverseMap.
2217 2217
      ///
2218 2218
      /// Constructor of the InverseMap.
2219 2219
      explicit InverseMap(const DescriptorMap& inverted)
2220 2220
        : _inverted(inverted) {}
2221 2221

	
2222 2222

	
2223 2223
      /// The value type of the InverseMap.
2224 2224
      typedef typename DescriptorMap::Key Value;
2225 2225
      /// The key type of the InverseMap.
2226 2226
      typedef typename DescriptorMap::Value Key;
2227 2227

	
2228 2228
      /// \brief Subscript operator.
2229 2229
      ///
2230 2230
      /// Subscript operator. It gives back the item
2231 2231
      /// that the descriptor belongs to currently.
2232 2232
      Value operator[](const Key& key) const {
2233 2233
        return _inverted(key);
2234 2234
      }
2235 2235

	
2236 2236
      /// \brief Size of the map.
2237 2237
      ///
2238 2238
      /// Returns the size of the map.
2239 2239
      unsigned int size() const {
2240 2240
        return _inverted.size();
2241 2241
      }
2242 2242

	
2243 2243
    private:
2244 2244
      const DescriptorMap& _inverted;
2245 2245
    };
2246 2246

	
2247 2247
    /// \brief Gives back the inverse of the map.
2248 2248
    ///
2249 2249
    /// Gives back the inverse of the map.
2250 2250
    const InverseMap inverse() const {
2251 2251
      return InverseMap(*this);
2252 2252
    }
2253 2253
  };
2254 2254

	
2255 2255
  /// \brief Returns the source of the given arc.
2256 2256
  ///
2257 2257
  /// The SourceMap gives back the source Node of the given arc.
2258 2258
  /// \see TargetMap
2259 2259
  template <typename Digraph>
2260 2260
  class SourceMap {
2261 2261
  public:
2262 2262

	
2263 2263
    typedef typename Digraph::Node Value;
2264 2264
    typedef typename Digraph::Arc Key;
2265 2265

	
2266 2266
    /// \brief Constructor
2267 2267
    ///
2268 2268
    /// Constructor
2269
    /// \param _digraph The digraph that the map belongs to.
2269
    /// \param digraph The digraph that the map belongs to.
2270 2270
    explicit SourceMap(const Digraph& digraph) : _digraph(digraph) {}
2271 2271

	
2272 2272
    /// \brief The subscript operator.
2273 2273
    ///
2274 2274
    /// The subscript operator.
2275 2275
    /// \param arc The arc
2276 2276
    /// \return The source of the arc
2277 2277
    Value operator[](const Key& arc) const {
2278 2278
      return _digraph.source(arc);
2279 2279
    }
2280 2280

	
2281 2281
  private:
2282 2282
    const Digraph& _digraph;
2283 2283
  };
2284 2284

	
2285 2285
  /// \brief Returns a \c SourceMap class.
2286 2286
  ///
2287 2287
  /// This function just returns an \c SourceMap class.
2288 2288
  /// \relates SourceMap
2289 2289
  template <typename Digraph>
2290 2290
  inline SourceMap<Digraph> sourceMap(const Digraph& digraph) {
2291 2291
    return SourceMap<Digraph>(digraph);
2292 2292
  }
2293 2293

	
2294 2294
  /// \brief Returns the target of the given arc.
2295 2295
  ///
2296 2296
  /// The TargetMap gives back the target Node of the given arc.
2297 2297
  /// \see SourceMap
2298 2298
  template <typename Digraph>
2299 2299
  class TargetMap {
2300 2300
  public:
2301 2301

	
2302 2302
    typedef typename Digraph::Node Value;
2303 2303
    typedef typename Digraph::Arc Key;
2304 2304

	
2305 2305
    /// \brief Constructor
2306 2306
    ///
2307 2307
    /// Constructor
2308
    /// \param _digraph The digraph that the map belongs to.
2308
    /// \param digraph The digraph that the map belongs to.
2309 2309
    explicit TargetMap(const Digraph& digraph) : _digraph(digraph) {}
2310 2310

	
2311 2311
    /// \brief The subscript operator.
2312 2312
    ///
2313 2313
    /// The subscript operator.
2314 2314
    /// \param e The arc
2315 2315
    /// \return The target of the arc
2316 2316
    Value operator[](const Key& e) const {
2317 2317
      return _digraph.target(e);
2318 2318
    }
2319 2319

	
2320 2320
  private:
2321 2321
    const Digraph& _digraph;
2322 2322
  };
2323 2323

	
2324 2324
  /// \brief Returns a \c TargetMap class.
2325 2325
  ///
2326 2326
  /// This function just returns a \c TargetMap class.
2327 2327
  /// \relates TargetMap
2328 2328
  template <typename Digraph>
2329 2329
  inline TargetMap<Digraph> targetMap(const Digraph& digraph) {
2330 2330
    return TargetMap<Digraph>(digraph);
2331 2331
  }
2332 2332

	
2333 2333
  /// \brief Returns the "forward" directed arc view of an edge.
2334 2334
  ///
2335 2335
  /// Returns the "forward" directed arc view of an edge.
2336 2336
  /// \see BackwardMap
2337 2337
  template <typename Graph>
2338 2338
  class ForwardMap {
2339 2339
  public:
2340 2340

	
2341 2341
    typedef typename Graph::Arc Value;
2342 2342
    typedef typename Graph::Edge Key;
2343 2343

	
2344 2344
    /// \brief Constructor
2345 2345
    ///
2346 2346
    /// Constructor
2347
    /// \param _graph The graph that the map belongs to.
2347
    /// \param graph The graph that the map belongs to.
2348 2348
    explicit ForwardMap(const Graph& graph) : _graph(graph) {}
2349 2349

	
2350 2350
    /// \brief The subscript operator.
2351 2351
    ///
2352 2352
    /// The subscript operator.
2353 2353
    /// \param key An edge
2354 2354
    /// \return The "forward" directed arc view of edge
2355 2355
    Value operator[](const Key& key) const {
2356 2356
      return _graph.direct(key, true);
2357 2357
    }
2358 2358

	
2359 2359
  private:
2360 2360
    const Graph& _graph;
2361 2361
  };
2362 2362

	
2363 2363
  /// \brief Returns a \c ForwardMap class.
2364 2364
  ///
2365 2365
  /// This function just returns an \c ForwardMap class.
2366 2366
  /// \relates ForwardMap
2367 2367
  template <typename Graph>
2368 2368
  inline ForwardMap<Graph> forwardMap(const Graph& graph) {
2369 2369
    return ForwardMap<Graph>(graph);
2370 2370
  }
2371 2371

	
2372 2372
  /// \brief Returns the "backward" directed arc view of an edge.
2373 2373
  ///
2374 2374
  /// Returns the "backward" directed arc view of an edge.
2375 2375
  /// \see ForwardMap
2376 2376
  template <typename Graph>
2377 2377
  class BackwardMap {
2378 2378
  public:
2379 2379

	
2380 2380
    typedef typename Graph::Arc Value;
2381 2381
    typedef typename Graph::Edge Key;
2382 2382

	
2383 2383
    /// \brief Constructor
2384 2384
    ///
2385 2385
    /// Constructor
2386
    /// \param _graph The graph that the map belongs to.
2386
    /// \param graph The graph that the map belongs to.
2387 2387
    explicit BackwardMap(const Graph& graph) : _graph(graph) {}
2388 2388

	
2389 2389
    /// \brief The subscript operator.
2390 2390
    ///
2391 2391
    /// The subscript operator.
2392 2392
    /// \param key An edge
2393 2393
    /// \return The "backward" directed arc view of edge
2394 2394
    Value operator[](const Key& key) const {
2395 2395
      return _graph.direct(key, false);
2396 2396
    }
2397 2397

	
2398 2398
  private:
2399 2399
    const Graph& _graph;
2400 2400
  };
2401 2401

	
2402 2402
  /// \brief Returns a \c BackwardMap class
2403 2403

	
2404 2404
  /// This function just returns a \c BackwardMap class.
2405 2405
  /// \relates BackwardMap
2406 2406
  template <typename Graph>
2407 2407
  inline BackwardMap<Graph> backwardMap(const Graph& graph) {
2408 2408
    return BackwardMap<Graph>(graph);
2409 2409
  }
2410 2410

	
2411 2411
  /// \brief Potential difference map
2412 2412
  ///
2413 2413
  /// If there is an potential map on the nodes then we
2414 2414
  /// can get an arc map as we get the substraction of the
2415 2415
  /// values of the target and source.
2416 2416
  template <typename Digraph, typename NodeMap>
2417 2417
  class PotentialDifferenceMap {
2418 2418
  public:
2419 2419
    typedef typename Digraph::Arc Key;
2420 2420
    typedef typename NodeMap::Value Value;
2421 2421

	
2422 2422
    /// \brief Constructor
2423 2423
    ///
2424 2424
    /// Contructor of the map
2425 2425
    explicit PotentialDifferenceMap(const Digraph& digraph,
2426 2426
                                    const NodeMap& potential)
2427 2427
      : _digraph(digraph), _potential(potential) {}
2428 2428

	
2429 2429
    /// \brief Const subscription operator
2430 2430
    ///
2431 2431
    /// Const subscription operator
2432 2432
    Value operator[](const Key& arc) const {
2433 2433
      return _potential[_digraph.target(arc)] -
2434 2434
        _potential[_digraph.source(arc)];
2435 2435
    }
2436 2436

	
2437 2437
  private:
2438 2438
    const Digraph& _digraph;
2439 2439
    const NodeMap& _potential;
2440 2440
  };
2441 2441

	
2442 2442
  /// \brief Returns a PotentialDifferenceMap.
2443 2443
  ///
2444 2444
  /// This function just returns a PotentialDifferenceMap.
2445 2445
  /// \relates PotentialDifferenceMap
2446 2446
  template <typename Digraph, typename NodeMap>
2447 2447
  PotentialDifferenceMap<Digraph, NodeMap>
2448 2448
  potentialDifferenceMap(const Digraph& digraph, const NodeMap& potential) {
2449 2449
    return PotentialDifferenceMap<Digraph, NodeMap>(digraph, potential);
2450 2450
  }
2451 2451

	
2452 2452
  /// \brief Map of the node in-degrees.
2453 2453
  ///
2454 2454
  /// This map returns the in-degree of a node. Once it is constructed,
2455 2455
  /// the degrees are stored in a standard NodeMap, so each query is done
2456 2456
  /// in constant time. On the other hand, the values are updated automatically
2457 2457
  /// whenever the digraph changes.
2458 2458
  ///
2459 2459
  /// \warning Besides addNode() and addArc(), a digraph structure may provide
2460 2460
  /// alternative ways to modify the digraph. The correct behavior of InDegMap
2461 2461
  /// is not guarantied if these additional features are used. For example
2462 2462
  /// the functions \ref ListDigraph::changeSource() "changeSource()",
2463 2463
  /// \ref ListDigraph::changeTarget() "changeTarget()" and
2464 2464
  /// \ref ListDigraph::reverseArc() "reverseArc()"
2465 2465
  /// of \ref ListDigraph will \e not update the degree values correctly.
2466 2466
  ///
2467 2467
  /// \sa OutDegMap
2468 2468

	
2469 2469
  template <typename _Digraph>
2470 2470
  class InDegMap
2471 2471
    : protected ItemSetTraits<_Digraph, typename _Digraph::Arc>
2472 2472
      ::ItemNotifier::ObserverBase {
2473 2473

	
2474 2474
  public:
2475 2475

	
2476 2476
    typedef _Digraph Digraph;
2477 2477
    typedef int Value;
2478 2478
    typedef typename Digraph::Node Key;
2479 2479

	
2480 2480
    typedef typename ItemSetTraits<Digraph, typename Digraph::Arc>
2481 2481
    ::ItemNotifier::ObserverBase Parent;
2482 2482

	
2483 2483
  private:
2484 2484

	
2485 2485
    class AutoNodeMap
2486 2486
      : public ItemSetTraits<Digraph, Key>::template Map<int>::Type {
2487 2487
    public:
2488 2488

	
2489 2489
      typedef typename ItemSetTraits<Digraph, Key>::
2490 2490
      template Map<int>::Type Parent;
2491 2491

	
2492 2492
      AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {}
2493 2493

	
2494 2494
      virtual void add(const Key& key) {
2495 2495
        Parent::add(key);
2496 2496
        Parent::set(key, 0);
2497 2497
      }
2498 2498

	
2499 2499
      virtual void add(const std::vector<Key>& keys) {
2500 2500
        Parent::add(keys);
2501 2501
        for (int i = 0; i < int(keys.size()); ++i) {
2502 2502
          Parent::set(keys[i], 0);
2503 2503
        }
2504 2504
      }
2505 2505

	
2506 2506
      virtual void build() {
2507 2507
        Parent::build();
2508 2508
        Key it;
2509 2509
        typename Parent::Notifier* nf = Parent::notifier();
2510 2510
        for (nf->first(it); it != INVALID; nf->next(it)) {
2511 2511
          Parent::set(it, 0);
2512 2512
        }
2513 2513
      }
2514 2514
    };
2515 2515

	
2516 2516
  public:
2517 2517

	
2518 2518
    /// \brief Constructor.
2519 2519
    ///
2520 2520
    /// Constructor for creating in-degree map.
2521 2521
    explicit InDegMap(const Digraph& digraph)
2522 2522
      : _digraph(digraph), _deg(digraph) {
2523 2523
      Parent::attach(_digraph.notifier(typename Digraph::Arc()));
2524 2524

	
2525 2525
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2526 2526
        _deg[it] = countInArcs(_digraph, it);
2527 2527
      }
2528 2528
    }
2529 2529

	
2530 2530
    /// Gives back the in-degree of a Node.
2531 2531
    int operator[](const Key& key) const {
2532 2532
      return _deg[key];
2533 2533
    }
2534 2534

	
2535 2535
  protected:
2536 2536

	
2537 2537
    typedef typename Digraph::Arc Arc;
2538 2538

	
2539 2539
    virtual void add(const Arc& arc) {
2540 2540
      ++_deg[_digraph.target(arc)];
2541 2541
    }
2542 2542

	
2543 2543
    virtual void add(const std::vector<Arc>& arcs) {
2544 2544
      for (int i = 0; i < int(arcs.size()); ++i) {
2545 2545
        ++_deg[_digraph.target(arcs[i])];
2546 2546
      }
2547 2547
    }
2548 2548

	
2549 2549
    virtual void erase(const Arc& arc) {
2550 2550
      --_deg[_digraph.target(arc)];
2551 2551
    }
2552 2552

	
2553 2553
    virtual void erase(const std::vector<Arc>& arcs) {
2554 2554
      for (int i = 0; i < int(arcs.size()); ++i) {
2555 2555
        --_deg[_digraph.target(arcs[i])];
2556 2556
      }
2557 2557
    }
2558 2558

	
2559 2559
    virtual void build() {
2560 2560
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2561 2561
        _deg[it] = countInArcs(_digraph, it);
2562 2562
      }
2563 2563
    }
2564 2564

	
2565 2565
    virtual void clear() {
2566 2566
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2567 2567
        _deg[it] = 0;
2568 2568
      }
2569 2569
    }
2570 2570
  private:
2571 2571

	
2572 2572
    const Digraph& _digraph;
2573 2573
    AutoNodeMap _deg;
2574 2574
  };
2575 2575

	
2576 2576
  /// \brief Map of the node out-degrees.
2577 2577
  ///
2578 2578
  /// This map returns the out-degree of a node. Once it is constructed,
2579 2579
  /// the degrees are stored in a standard NodeMap, so each query is done
2580 2580
  /// in constant time. On the other hand, the values are updated automatically
2581 2581
  /// whenever the digraph changes.
2582 2582
  ///
2583 2583
  /// \warning Besides addNode() and addArc(), a digraph structure may provide
2584 2584
  /// alternative ways to modify the digraph. The correct behavior of OutDegMap
2585 2585
  /// is not guarantied if these additional features are used. For example
2586 2586
  /// the functions \ref ListDigraph::changeSource() "changeSource()",
2587 2587
  /// \ref ListDigraph::changeTarget() "changeTarget()" and
2588 2588
  /// \ref ListDigraph::reverseArc() "reverseArc()"
2589 2589
  /// of \ref ListDigraph will \e not update the degree values correctly.
2590 2590
  ///
2591 2591
  /// \sa InDegMap
2592 2592

	
2593 2593
  template <typename _Digraph>
2594 2594
  class OutDegMap
2595 2595
    : protected ItemSetTraits<_Digraph, typename _Digraph::Arc>
2596 2596
      ::ItemNotifier::ObserverBase {
2597 2597

	
2598 2598
  public:
2599 2599

	
2600 2600
    typedef _Digraph Digraph;
2601 2601
    typedef int Value;
2602 2602
    typedef typename Digraph::Node Key;
2603 2603

	
2604 2604
    typedef typename ItemSetTraits<Digraph, typename Digraph::Arc>
2605 2605
    ::ItemNotifier::ObserverBase Parent;
2606 2606

	
2607 2607
  private:
2608 2608

	
2609 2609
    class AutoNodeMap
2610 2610
      : public ItemSetTraits<Digraph, Key>::template Map<int>::Type {
2611 2611
    public:
2612 2612

	
2613 2613
      typedef typename ItemSetTraits<Digraph, Key>::
2614 2614
      template Map<int>::Type Parent;
2615 2615

	
2616 2616
      AutoNodeMap(const Digraph& digraph) : Parent(digraph, 0) {}
2617 2617

	
2618 2618
      virtual void add(const Key& key) {
2619 2619
        Parent::add(key);
2620 2620
        Parent::set(key, 0);
2621 2621
      }
2622 2622
      virtual void add(const std::vector<Key>& keys) {
2623 2623
        Parent::add(keys);
2624 2624
        for (int i = 0; i < int(keys.size()); ++i) {
2625 2625
          Parent::set(keys[i], 0);
2626 2626
        }
2627 2627
      }
2628 2628
      virtual void build() {
2629 2629
        Parent::build();
2630 2630
        Key it;
2631 2631
        typename Parent::Notifier* nf = Parent::notifier();
2632 2632
        for (nf->first(it); it != INVALID; nf->next(it)) {
2633 2633
          Parent::set(it, 0);
2634 2634
        }
2635 2635
      }
2636 2636
    };
2637 2637

	
2638 2638
  public:
2639 2639

	
2640 2640
    /// \brief Constructor.
2641 2641
    ///
2642 2642
    /// Constructor for creating out-degree map.
2643 2643
    explicit OutDegMap(const Digraph& digraph)
2644 2644
      : _digraph(digraph), _deg(digraph) {
2645 2645
      Parent::attach(_digraph.notifier(typename Digraph::Arc()));
2646 2646

	
2647 2647
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2648 2648
        _deg[it] = countOutArcs(_digraph, it);
2649 2649
      }
2650 2650
    }
2651 2651

	
2652 2652
    /// Gives back the out-degree of a Node.
2653 2653
    int operator[](const Key& key) const {
2654 2654
      return _deg[key];
2655 2655
    }
2656 2656

	
2657 2657
  protected:
2658 2658

	
2659 2659
    typedef typename Digraph::Arc Arc;
2660 2660

	
2661 2661
    virtual void add(const Arc& arc) {
2662 2662
      ++_deg[_digraph.source(arc)];
2663 2663
    }
2664 2664

	
2665 2665
    virtual void add(const std::vector<Arc>& arcs) {
2666 2666
      for (int i = 0; i < int(arcs.size()); ++i) {
2667 2667
        ++_deg[_digraph.source(arcs[i])];
2668 2668
      }
2669 2669
    }
2670 2670

	
2671 2671
    virtual void erase(const Arc& arc) {
2672 2672
      --_deg[_digraph.source(arc)];
2673 2673
    }
2674 2674

	
2675 2675
    virtual void erase(const std::vector<Arc>& arcs) {
2676 2676
      for (int i = 0; i < int(arcs.size()); ++i) {
2677 2677
        --_deg[_digraph.source(arcs[i])];
2678 2678
      }
2679 2679
    }
2680 2680

	
2681 2681
    virtual void build() {
2682 2682
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2683 2683
        _deg[it] = countOutArcs(_digraph, it);
2684 2684
      }
2685 2685
    }
2686 2686

	
2687 2687
    virtual void clear() {
2688 2688
      for(typename Digraph::NodeIt it(_digraph); it != INVALID; ++it) {
2689 2689
        _deg[it] = 0;
2690 2690
      }
2691 2691
    }
2692 2692
  private:
2693 2693

	
2694 2694
    const Digraph& _digraph;
2695 2695
    AutoNodeMap _deg;
2696 2696
  };
2697 2697

	
2698 2698
  /// @}
2699 2699
}
2700 2700

	
2701 2701
#endif // LEMON_MAPS_H
Ignore white space 12582912 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 paths
20 20
///\file
21 21
///\brief Classes for representing paths in digraphs.
22 22
///
23 23

	
24 24
#ifndef LEMON_PATH_H
25 25
#define LEMON_PATH_H
26 26

	
27 27
#include <vector>
28 28
#include <algorithm>
29 29

	
30 30
#include <lemon/error.h>
31 31
#include <lemon/core.h>
32 32
#include <lemon/concepts/path.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \addtogroup paths
37 37
  /// @{
38 38

	
39 39

	
40 40
  /// \brief A structure for representing directed paths in a digraph.
41 41
  ///
42 42
  /// A structure for representing directed path in a digraph.
43 43
  /// \tparam _Digraph The digraph type in which the path is.
44 44
  ///
45 45
  /// In a sense, the path can be treated as a list of arcs. The
46 46
  /// lemon path type stores just this list. As a consequence, it
47 47
  /// cannot enumerate the nodes of the path and the source node of
48 48
  /// a zero length path is undefined.
49 49
  ///
50 50
  /// This implementation is a back and front insertable and erasable
51 51
  /// path type. It can be indexed in O(1) time. The front and back
52 52
  /// insertion and erase is done in O(1) (amortized) time. The
53 53
  /// implementation uses two vectors for storing the front and back
54 54
  /// insertions.
55 55
  template <typename _Digraph>
56 56
  class Path {
57 57
  public:
58 58

	
59 59
    typedef _Digraph Digraph;
60 60
    typedef typename Digraph::Arc Arc;
61 61

	
62 62
    /// \brief Default constructor
63 63
    ///
64 64
    /// Default constructor
65 65
    Path() {}
66 66

	
67 67
    /// \brief Template copy constructor
68 68
    ///
69 69
    /// This constuctor initializes the path from any other path type.
70 70
    /// It simply makes a copy of the given path.
71 71
    template <typename CPath>
72 72
    Path(const CPath& cpath) {
73 73
      copyPath(*this, cpath);
74 74
    }
75 75

	
76 76
    /// \brief Template copy assignment
77 77
    ///
78 78
    /// This operator makes a copy of a path of any other type.
79 79
    template <typename CPath>
80 80
    Path& operator=(const CPath& cpath) {
81 81
      copyPath(*this, cpath);
82 82
      return *this;
83 83
    }
84 84

	
85 85
    /// \brief LEMON style iterator for path arcs
86 86
    ///
87 87
    /// This class is used to iterate on the arcs of the paths.
88 88
    class ArcIt {
89 89
      friend class Path;
90 90
    public:
91 91
      /// \brief Default constructor
92 92
      ArcIt() {}
93 93
      /// \brief Invalid constructor
94 94
      ArcIt(Invalid) : path(0), idx(-1) {}
95 95
      /// \brief Initializate the iterator to the first arc of path
96 96
      ArcIt(const Path &_path)
97 97
        : path(&_path), idx(_path.empty() ? -1 : 0) {}
98 98

	
99 99
    private:
100 100

	
101 101
      ArcIt(const Path &_path, int _idx)
102 102
        : path(&_path), idx(_idx) {}
103 103

	
104 104
    public:
105 105

	
106 106
      /// \brief Conversion to Arc
107 107
      operator const Arc&() const {
108 108
        return path->nth(idx);
109 109
      }
110 110

	
111 111
      /// \brief Next arc
112 112
      ArcIt& operator++() {
113 113
        ++idx;
114 114
        if (idx >= path->length()) idx = -1;
115 115
        return *this;
116 116
      }
117 117

	
118 118
      /// \brief Comparison operator
119 119
      bool operator==(const ArcIt& e) const { return idx==e.idx; }
120 120
      /// \brief Comparison operator
121 121
      bool operator!=(const ArcIt& e) const { return idx!=e.idx; }
122 122
      /// \brief Comparison operator
123 123
      bool operator<(const ArcIt& e) const { return idx<e.idx; }
124 124

	
125 125
    private:
126 126
      const Path *path;
127 127
      int idx;
128 128
    };
129 129

	
130 130
    /// \brief Length of the path.
131 131
    int length() const { return head.size() + tail.size(); }
132 132
    /// \brief Return whether the path is empty.
133 133
    bool empty() const { return head.empty() && tail.empty(); }
134 134

	
135 135
    /// \brief Reset the path to an empty one.
136 136
    void clear() { head.clear(); tail.clear(); }
137 137

	
138 138
    /// \brief The nth arc.
139 139
    ///
140 140
    /// \pre n is in the [0..length() - 1] range
141 141
    const Arc& nth(int n) const {
142 142
      return n < int(head.size()) ? *(head.rbegin() + n) :
143 143
        *(tail.begin() + (n - head.size()));
144 144
    }
145 145

	
146 146
    /// \brief Initialize arc iterator to point to the nth arc
147 147
    ///
148 148
    /// \pre n is in the [0..length() - 1] range
149 149
    ArcIt nthIt(int n) const {
150 150
      return ArcIt(*this, n);
151 151
    }
152 152

	
153 153
    /// \brief The first arc of the path
154 154
    const Arc& front() const {
155 155
      return head.empty() ? tail.front() : head.back();
156 156
    }
157 157

	
158 158
    /// \brief Add a new arc before the current path
159 159
    void addFront(const Arc& arc) {
160 160
      head.push_back(arc);
161 161
    }
162 162

	
163 163
    /// \brief Erase the first arc of the path
164 164
    void eraseFront() {
165 165
      if (!head.empty()) {
166 166
        head.pop_back();
167 167
      } else {
168 168
        head.clear();
169 169
        int halfsize = tail.size() / 2;
170 170
        head.resize(halfsize);
171 171
        std::copy(tail.begin() + 1, tail.begin() + halfsize + 1,
172 172
                  head.rbegin());
173 173
        std::copy(tail.begin() + halfsize + 1, tail.end(), tail.begin());
174 174
        tail.resize(tail.size() - halfsize - 1);
175 175
      }
176 176
    }
177 177

	
178 178
    /// \brief The last arc of the path
179 179
    const Arc& back() const {
180 180
      return tail.empty() ? head.front() : tail.back();
181 181
    }
182 182

	
183 183
    /// \brief Add a new arc behind the current path
184 184
    void addBack(const Arc& arc) {
185 185
      tail.push_back(arc);
186 186
    }
187 187

	
188 188
    /// \brief Erase the last arc of the path
189 189
    void eraseBack() {
190 190
      if (!tail.empty()) {
191 191
        tail.pop_back();
192 192
      } else {
193 193
        int halfsize = head.size() / 2;
194 194
        tail.resize(halfsize);
195 195
        std::copy(head.begin() + 1, head.begin() + halfsize + 1,
196 196
                  tail.rbegin());
197 197
        std::copy(head.begin() + halfsize + 1, head.end(), head.begin());
198 198
        head.resize(head.size() - halfsize - 1);
199 199
      }
200 200
    }
201 201

	
202 202
    typedef True BuildTag;
203 203

	
204 204
    template <typename CPath>
205 205
    void build(const CPath& path) {
206 206
      int len = path.length();
207 207
      tail.reserve(len);
208 208
      for (typename CPath::ArcIt it(path); it != INVALID; ++it) {
209 209
        tail.push_back(it);
210 210
      }
211 211
    }
212 212

	
213 213
    template <typename CPath>
214 214
    void buildRev(const CPath& path) {
215 215
      int len = path.length();
216 216
      head.reserve(len);
217 217
      for (typename CPath::RevArcIt it(path); it != INVALID; ++it) {
218 218
        head.push_back(it);
219 219
      }
220 220
    }
221 221

	
222 222
  protected:
223 223
    typedef std::vector<Arc> Container;
224 224
    Container head, tail;
225 225

	
226 226
  };
227 227

	
228 228
  /// \brief A structure for representing directed paths in a digraph.
229 229
  ///
230 230
  /// A structure for representing directed path in a digraph.
231 231
  /// \tparam _Digraph The digraph type in which the path is.
232 232
  ///
233 233
  /// In a sense, the path can be treated as a list of arcs. The
234 234
  /// lemon path type stores just this list. As a consequence it
235 235
  /// cannot enumerate the nodes in the path and the zero length paths
236 236
  /// cannot store the source.
237 237
  ///
238 238
  /// This implementation is a just back insertable and erasable path
239 239
  /// type. It can be indexed in O(1) time. The back insertion and
240 240
  /// erasure is amortized O(1) time. This implementation is faster
241 241
  /// then the \c Path type because it use just one vector for the
242 242
  /// arcs.
243 243
  template <typename _Digraph>
244 244
  class SimplePath {
245 245
  public:
246 246

	
247 247
    typedef _Digraph Digraph;
248 248
    typedef typename Digraph::Arc Arc;
249 249

	
250 250
    /// \brief Default constructor
251 251
    ///
252 252
    /// Default constructor
253 253
    SimplePath() {}
254 254

	
255 255
    /// \brief Template copy constructor
256 256
    ///
257 257
    /// This path can be initialized with any other path type. It just
258 258
    /// makes a copy of the given path.
259 259
    template <typename CPath>
260 260
    SimplePath(const CPath& cpath) {
261 261
      copyPath(*this, cpath);
262 262
    }
263 263

	
264 264
    /// \brief Template copy assignment
265 265
    ///
266 266
    /// This path can be initialized with any other path type. It just
267 267
    /// makes a copy of the given path.
268 268
    template <typename CPath>
269 269
    SimplePath& operator=(const CPath& cpath) {
270 270
      copyPath(*this, cpath);
271 271
      return *this;
272 272
    }
273 273

	
274 274
    /// \brief Iterator class to iterate on the arcs of the paths
275 275
    ///
276 276
    /// This class is used to iterate on the arcs of the paths
277 277
    ///
278 278
    /// Of course it converts to Digraph::Arc
279 279
    class ArcIt {
280 280
      friend class SimplePath;
281 281
    public:
282 282
      /// Default constructor
283 283
      ArcIt() {}
284 284
      /// Invalid constructor
285 285
      ArcIt(Invalid) : path(0), idx(-1) {}
286 286
      /// \brief Initializate the constructor to the first arc of path
287 287
      ArcIt(const SimplePath &_path)
288 288
        : path(&_path), idx(_path.empty() ? -1 : 0) {}
289 289

	
290 290
    private:
291 291

	
292 292
      /// Constructor with starting point
293 293
      ArcIt(const SimplePath &_path, int _idx)
294 294
        : idx(_idx), path(&_path) {}
295 295

	
296 296
    public:
297 297

	
298 298
      ///Conversion to Digraph::Arc
299 299
      operator const Arc&() const {
300 300
        return path->nth(idx);
301 301
      }
302 302

	
303 303
      /// Next arc
304 304
      ArcIt& operator++() {
305 305
        ++idx;
306 306
        if (idx >= path->length()) idx = -1;
307 307
        return *this;
308 308
      }
309 309

	
310 310
      /// Comparison operator
311 311
      bool operator==(const ArcIt& e) const { return idx==e.idx; }
312 312
      /// Comparison operator
313 313
      bool operator!=(const ArcIt& e) const { return idx!=e.idx; }
314 314
      /// Comparison operator
315 315
      bool operator<(const ArcIt& e) const { return idx<e.idx; }
316 316

	
317 317
    private:
318 318
      const SimplePath *path;
319 319
      int idx;
320 320
    };
321 321

	
322 322
    /// \brief Length of the path.
323 323
    int length() const { return data.size(); }
324 324
    /// \brief Return true if the path is empty.
325 325
    bool empty() const { return data.empty(); }
326 326

	
327 327
    /// \brief Reset the path to an empty one.
328 328
    void clear() { data.clear(); }
329 329

	
330 330
    /// \brief The nth arc.
331 331
    ///
332 332
    /// \pre n is in the [0..length() - 1] range
333 333
    const Arc& nth(int n) const {
334 334
      return data[n];
335 335
    }
336 336

	
337 337
    /// \brief  Initializes arc iterator to point to the nth arc.
338 338
    ArcIt nthIt(int n) const {
339 339
      return ArcIt(*this, n);
340 340
    }
341 341

	
342 342
    /// \brief The first arc of the path.
343 343
    const Arc& front() const {
344 344
      return data.front();
345 345
    }
346 346

	
347 347
    /// \brief The last arc of the path.
348 348
    const Arc& back() const {
349 349
      return data.back();
350 350
    }
351 351

	
352 352
    /// \brief Add a new arc behind the current path.
353 353
    void addBack(const Arc& arc) {
354 354
      data.push_back(arc);
355 355
    }
356 356

	
357 357
    /// \brief Erase the last arc of the path
358 358
    void eraseBack() {
359 359
      data.pop_back();
360 360
    }
361 361

	
362 362
    typedef True BuildTag;
363 363

	
364 364
    template <typename CPath>
365 365
    void build(const CPath& path) {
366 366
      int len = path.length();
367 367
      data.resize(len);
368 368
      int index = 0;
369 369
      for (typename CPath::ArcIt it(path); it != INVALID; ++it) {
370 370
        data[index] = it;;
371 371
        ++index;
372 372
      }
373 373
    }
374 374

	
375 375
    template <typename CPath>
376 376
    void buildRev(const CPath& path) {
377 377
      int len = path.length();
378 378
      data.resize(len);
379 379
      int index = len;
380 380
      for (typename CPath::RevArcIt it(path); it != INVALID; ++it) {
381 381
        --index;
382 382
        data[index] = it;;
383 383
      }
384 384
    }
385 385

	
386 386
  protected:
387 387
    typedef std::vector<Arc> Container;
388 388
    Container data;
389 389

	
390 390
  };
391 391

	
392 392
  /// \brief A structure for representing directed paths in a digraph.
393 393
  ///
394 394
  /// A structure for representing directed path in a digraph.
395 395
  /// \tparam _Digraph The digraph type in which the path is.
396 396
  ///
397 397
  /// In a sense, the path can be treated as a list of arcs. The
398 398
  /// lemon path type stores just this list. As a consequence it
399 399
  /// cannot enumerate the nodes in the path and the zero length paths
400 400
  /// cannot store the source.
401 401
  ///
402 402
  /// This implementation is a back and front insertable and erasable
403 403
  /// path type. It can be indexed in O(k) time, where k is the rank
404 404
  /// of the arc in the path. The length can be computed in O(n)
405 405
  /// time. The front and back insertion and erasure is O(1) time
406 406
  /// and it can be splited and spliced in O(1) time.
407 407
  template <typename _Digraph>
408 408
  class ListPath {
409 409
  public:
410 410

	
411 411
    typedef _Digraph Digraph;
412 412
    typedef typename Digraph::Arc Arc;
413 413

	
414 414
  protected:
415 415

	
416 416
    // the std::list<> is incompatible
417 417
    // hard to create invalid iterator
418 418
    struct Node {
419 419
      Arc arc;
420 420
      Node *next, *prev;
421 421
    };
422 422

	
423 423
    Node *first, *last;
424 424

	
425 425
    std::allocator<Node> alloc;
426 426

	
427 427
  public:
428 428

	
429 429
    /// \brief Default constructor
430 430
    ///
431 431
    /// Default constructor
432 432
    ListPath() : first(0), last(0) {}
433 433

	
434 434
    /// \brief Template copy constructor
435 435
    ///
436 436
    /// This path can be initialized with any other path type. It just
437 437
    /// makes a copy of the given path.
438 438
    template <typename CPath>
439 439
    ListPath(const CPath& cpath) : first(0), last(0) {
440 440
      copyPath(*this, cpath);
441 441
    }
442 442

	
443 443
    /// \brief Destructor of the path
444 444
    ///
445 445
    /// Destructor of the path
446 446
    ~ListPath() {
447 447
      clear();
448 448
    }
449 449

	
450 450
    /// \brief Template copy assignment
451 451
    ///
452 452
    /// This path can be initialized with any other path type. It just
453 453
    /// makes a copy of the given path.
454 454
    template <typename CPath>
455 455
    ListPath& operator=(const CPath& cpath) {
456 456
      copyPath(*this, cpath);
457 457
      return *this;
458 458
    }
459 459

	
460 460
    /// \brief Iterator class to iterate on the arcs of the paths
461 461
    ///
462 462
    /// This class is used to iterate on the arcs of the paths
463 463
    ///
464 464
    /// Of course it converts to Digraph::Arc
465 465
    class ArcIt {
466 466
      friend class ListPath;
467 467
    public:
468 468
      /// Default constructor
469 469
      ArcIt() {}
470 470
      /// Invalid constructor
471 471
      ArcIt(Invalid) : path(0), node(0) {}
472 472
      /// \brief Initializate the constructor to the first arc of path
473 473
      ArcIt(const ListPath &_path)
474 474
        : path(&_path), node(_path.first) {}
475 475

	
476 476
    protected:
477 477

	
478 478
      ArcIt(const ListPath &_path, Node *_node)
479 479
        : path(&_path), node(_node) {}
480 480

	
481 481

	
482 482
    public:
483 483

	
484 484
      ///Conversion to Digraph::Arc
485 485
      operator const Arc&() const {
486 486
        return node->arc;
487 487
      }
488 488

	
489 489
      /// Next arc
490 490
      ArcIt& operator++() {
491 491
        node = node->next;
492 492
        return *this;
493 493
      }
494 494

	
495 495
      /// Comparison operator
496 496
      bool operator==(const ArcIt& e) const { return node==e.node; }
497 497
      /// Comparison operator
498 498
      bool operator!=(const ArcIt& e) const { return node!=e.node; }
499 499
      /// Comparison operator
500 500
      bool operator<(const ArcIt& e) const { return node<e.node; }
501 501

	
502 502
    private:
503 503
      const ListPath *path;
504 504
      Node *node;
505 505
    };
506 506

	
507 507
    /// \brief The nth arc.
508 508
    ///
509 509
    /// This function looks for the nth arc in O(n) time.
510 510
    /// \pre n is in the [0..length() - 1] range
511 511
    const Arc& nth(int n) const {
512 512
      Node *node = first;
513 513
      for (int i = 0; i < n; ++i) {
514 514
        node = node->next;
515 515
      }
516 516
      return node->arc;
517 517
    }
518 518

	
519 519
    /// \brief Initializes arc iterator to point to the nth arc.
520 520
    ArcIt nthIt(int n) const {
521 521
      Node *node = first;
522 522
      for (int i = 0; i < n; ++i) {
523 523
        node = node->next;
524 524
      }
525 525
      return ArcIt(*this, node);
526 526
    }
527 527

	
528 528
    /// \brief Length of the path.
529 529
    int length() const {
530 530
      int len = 0;
531 531
      Node *node = first;
532 532
      while (node != 0) {
533 533
        node = node->next;
534 534
        ++len;
535 535
      }
536 536
      return len;
537 537
    }
538 538

	
539 539
    /// \brief Return true if the path is empty.
540 540
    bool empty() const { return first == 0; }
541 541

	
542 542
    /// \brief Reset the path to an empty one.
543 543
    void clear() {
544 544
      while (first != 0) {
545 545
        last = first->next;
546 546
        alloc.destroy(first);
547 547
        alloc.deallocate(first, 1);
548 548
        first = last;
549 549
      }
550 550
    }
551 551

	
552 552
    /// \brief The first arc of the path
553 553
    const Arc& front() const {
554 554
      return first->arc;
555 555
    }
556 556

	
557 557
    /// \brief Add a new arc before the current path
558 558
    void addFront(const Arc& arc) {
559 559
      Node *node = alloc.allocate(1);
560 560
      alloc.construct(node, Node());
561 561
      node->prev = 0;
562 562
      node->next = first;
563 563
      node->arc = arc;
564 564
      if (first) {
565 565
        first->prev = node;
566 566
        first = node;
567 567
      } else {
568 568
        first = last = node;
569 569
      }
570 570
    }
571 571

	
572 572
    /// \brief Erase the first arc of the path
573 573
    void eraseFront() {
574 574
      Node *node = first;
575 575
      first = first->next;
576 576
      if (first) {
577 577
        first->prev = 0;
578 578
      } else {
579 579
        last = 0;
580 580
      }
581 581
      alloc.destroy(node);
582 582
      alloc.deallocate(node, 1);
583 583
    }
584 584

	
585 585
    /// \brief The last arc of the path.
586 586
    const Arc& back() const {
587 587
      return last->arc;
588 588
    }
589 589

	
590 590
    /// \brief Add a new arc behind the current path.
591 591
    void addBack(const Arc& arc) {
592 592
      Node *node = alloc.allocate(1);
593 593
      alloc.construct(node, Node());
594 594
      node->next = 0;
595 595
      node->prev = last;
596 596
      node->arc = arc;
597 597
      if (last) {
598 598
        last->next = node;
599 599
        last = node;
600 600
      } else {
601 601
        last = first = node;
602 602
      }
603 603
    }
604 604

	
605 605
    /// \brief Erase the last arc of the path
606 606
    void eraseBack() {
607 607
      Node *node = last;
608 608
      last = last->prev;
609 609
      if (last) {
610 610
        last->next = 0;
611 611
      } else {
612 612
        first = 0;
613 613
      }
614 614
      alloc.destroy(node);
615 615
      alloc.deallocate(node, 1);
616 616
    }
617 617

	
618 618
    /// \brief Splice a path to the back of the current path.
619 619
    ///
620 620
    /// It splices \c tpath to the back of the current path and \c
621 621
    /// tpath becomes empty. The time complexity of this function is
622 622
    /// O(1).
623 623
    void spliceBack(ListPath& tpath) {
624 624
      if (first) {
625 625
        if (tpath.first) {
626 626
          last->next = tpath.first;
627 627
          tpath.first->prev = last;
628 628
          last = tpath.last;
629 629
        }
630 630
      } else {
631 631
        first = tpath.first;
632 632
        last = tpath.last;
633 633
      }
634 634
      tpath.first = tpath.last = 0;
635 635
    }
636 636

	
637 637
    /// \brief Splice a path to the front of the current path.
638 638
    ///
639 639
    /// It splices \c tpath before the current path and \c tpath
640 640
    /// becomes empty. The time complexity of this function
641 641
    /// is O(1).
642 642
    void spliceFront(ListPath& tpath) {
643 643
      if (first) {
644 644
        if (tpath.first) {
645 645
          first->prev = tpath.last;
646 646
          tpath.last->next = first;
647 647
          first = tpath.first;
648 648
        }
649 649
      } else {
650 650
        first = tpath.first;
651 651
        last = tpath.last;
652 652
      }
653 653
      tpath.first = tpath.last = 0;
654 654
    }
655 655

	
656 656
    /// \brief Splice a path into the current path.
657 657
    ///
658 658
    /// It splices the \c tpath into the current path before the
659 659
    /// position of \c it iterator and \c tpath becomes empty. The
660 660
    /// time complexity of this function is O(1). If the \c it is
661 661
    /// \c INVALID then it will splice behind the current path.
662 662
    void splice(ArcIt it, ListPath& tpath) {
663 663
      if (it.node) {
664 664
        if (tpath.first) {
665 665
          tpath.first->prev = it.node->prev;
666 666
          if (it.node->prev) {
667 667
            it.node->prev->next = tpath.first;
668 668
          } else {
669 669
            first = tpath.first;
670 670
          }
671 671
          it.node->prev = tpath.last;
672 672
          tpath.last->next = it.node;
673 673
        }
674 674
      } else {
675 675
        if (first) {
676 676
          if (tpath.first) {
677 677
            last->next = tpath.first;
678 678
            tpath.first->prev = last;
679 679
            last = tpath.last;
680 680
          }
681 681
        } else {
682 682
          first = tpath.first;
683 683
          last = tpath.last;
684 684
        }
685 685
      }
686 686
      tpath.first = tpath.last = 0;
687 687
    }
688 688

	
689 689
    /// \brief Split the current path.
690 690
    ///
691 691
    /// It splits the current path into two parts. The part before
692 692
    /// the iterator \c it will remain in the current path and the part
693 693
    /// starting with
694 694
    /// \c it will put into \c tpath. If \c tpath have arcs
695 695
    /// before the operation they are removed first.  The time
696 696
    /// complexity of this function is O(1) plus the the time of emtying
697 697
    /// \c tpath. If \c it is \c INVALID then it just clears \c tpath
698 698
    void split(ArcIt it, ListPath& tpath) {
699 699
      tpath.clear();
700 700
      if (it.node) {
701 701
        tpath.first = it.node;
702 702
        tpath.last = last;
703 703
        if (it.node->prev) {
704 704
          last = it.node->prev;
705 705
          last->next = 0;
706 706
        } else {
707 707
          first = last = 0;
708 708
        }
709 709
        it.node->prev = 0;
710 710
      }
711 711
    }
712 712

	
713 713

	
714 714
    typedef True BuildTag;
715 715

	
716 716
    template <typename CPath>
717 717
    void build(const CPath& path) {
718 718
      for (typename CPath::ArcIt it(path); it != INVALID; ++it) {
719 719
        addBack(it);
720 720
      }
721 721
    }
722 722

	
723 723
    template <typename CPath>
724 724
    void buildRev(const CPath& path) {
725 725
      for (typename CPath::RevArcIt it(path); it != INVALID; ++it) {
726 726
        addFront(it);
727 727
      }
728 728
    }
729 729

	
730 730
  };
731 731

	
732 732
  /// \brief A structure for representing directed paths in a digraph.
733 733
  ///
734 734
  /// A structure for representing directed path in a digraph.
735 735
  /// \tparam _Digraph The digraph type in which the path is.
736 736
  ///
737 737
  /// In a sense, the path can be treated as a list of arcs. The
738 738
  /// lemon path type stores just this list. As a consequence it
739 739
  /// cannot enumerate the nodes in the path and the source node of
740 740
  /// a zero length path is undefined.
741 741
  ///
742 742
  /// This implementation is completly static, i.e. it can be copy constucted
743 743
  /// or copy assigned from another path, but otherwise it cannot be
744 744
  /// modified.
745 745
  ///
746 746
  /// Being the the most memory efficient path type in LEMON,
747 747
  /// it is intented to be
748 748
  /// used when you want to store a large number of paths.
749 749
  template <typename _Digraph>
750 750
  class StaticPath {
751 751
  public:
752 752

	
753 753
    typedef _Digraph Digraph;
754 754
    typedef typename Digraph::Arc Arc;
755 755

	
756 756
    /// \brief Default constructor
757 757
    ///
758 758
    /// Default constructor
759 759
    StaticPath() : len(0), arcs(0) {}
760 760

	
761 761
    /// \brief Template copy constructor
762 762
    ///
763 763
    /// This path can be initialized from any other path type.
764 764
    template <typename CPath>
765 765
    StaticPath(const CPath& cpath) : arcs(0) {
766 766
      copyPath(*this, cpath);
767 767
    }
768 768

	
769 769
    /// \brief Destructor of the path
770 770
    ///
771 771
    /// Destructor of the path
772 772
    ~StaticPath() {
773 773
      if (arcs) delete[] arcs;
774 774
    }
775 775

	
776 776
    /// \brief Template copy assignment
777 777
    ///
778 778
    /// This path can be made equal to any other path type. It simply
779 779
    /// makes a copy of the given path.
780 780
    template <typename CPath>
781 781
    StaticPath& operator=(const CPath& cpath) {
782 782
      copyPath(*this, cpath);
783 783
      return *this;
784 784
    }
785 785

	
786 786
    /// \brief Iterator class to iterate on the arcs of the paths
787 787
    ///
788 788
    /// This class is used to iterate on the arcs of the paths
789 789
    ///
790 790
    /// Of course it converts to Digraph::Arc
791 791
    class ArcIt {
792 792
      friend class StaticPath;
793 793
    public:
794 794
      /// Default constructor
795 795
      ArcIt() {}
796 796
      /// Invalid constructor
797 797
      ArcIt(Invalid) : path(0), idx(-1) {}
798 798
      /// Initializate the constructor to the first arc of path
799 799
      ArcIt(const StaticPath &_path)
800 800
        : path(&_path), idx(_path.empty() ? -1 : 0) {}
801 801

	
802 802
    private:
803 803

	
804 804
      /// Constructor with starting point
805 805
      ArcIt(const StaticPath &_path, int _idx)
806 806
        : idx(_idx), path(&_path) {}
807 807

	
808 808
    public:
809 809

	
810 810
      ///Conversion to Digraph::Arc
811 811
      operator const Arc&() const {
812 812
        return path->nth(idx);
813 813
      }
814 814

	
815 815
      /// Next arc
816 816
      ArcIt& operator++() {
817 817
        ++idx;
818 818
        if (idx >= path->length()) idx = -1;
819 819
        return *this;
820 820
      }
821 821

	
822 822
      /// Comparison operator
823 823
      bool operator==(const ArcIt& e) const { return idx==e.idx; }
824 824
      /// Comparison operator
825 825
      bool operator!=(const ArcIt& e) const { return idx!=e.idx; }
826 826
      /// Comparison operator
827 827
      bool operator<(const ArcIt& e) const { return idx<e.idx; }
828 828

	
829 829
    private:
830 830
      const StaticPath *path;
831 831
      int idx;
832 832
    };
833 833

	
834 834
    /// \brief The nth arc.
835 835
    ///
836 836
    /// \pre n is in the [0..length() - 1] range
837 837
    const Arc& nth(int n) const {
838 838
      return arcs[n];
839 839
    }
840 840

	
841 841
    /// \brief The arc iterator pointing to the nth arc.
842 842
    ArcIt nthIt(int n) const {
843 843
      return ArcIt(*this, n);
844 844
    }
845 845

	
846 846
    /// \brief The length of the path.
847 847
    int length() const { return len; }
848 848

	
849 849
    /// \brief Return true when the path is empty.
850 850
    int empty() const { return len == 0; }
851 851

	
852
    /// \break Erase all arcs in the digraph.
852
    /// \brief Erase all arcs in the digraph.
853 853
    void clear() {
854 854
      len = 0;
855 855
      if (arcs) delete[] arcs;
856 856
      arcs = 0;
857 857
    }
858 858

	
859 859
    /// \brief The first arc of the path.
860 860
    const Arc& front() const {
861 861
      return arcs[0];
862 862
    }
863 863

	
864 864
    /// \brief The last arc of the path.
865 865
    const Arc& back() const {
866 866
      return arcs[len - 1];
867 867
    }
868 868

	
869 869

	
870 870
    typedef True BuildTag;
871 871

	
872 872
    template <typename CPath>
873 873
    void build(const CPath& path) {
874 874
      len = path.length();
875 875
      arcs = new Arc[len];
876 876
      int index = 0;
877 877
      for (typename CPath::ArcIt it(path); it != INVALID; ++it) {
878 878
        arcs[index] = it;
879 879
        ++index;
880 880
      }
881 881
    }
882 882

	
883 883
    template <typename CPath>
884 884
    void buildRev(const CPath& path) {
885 885
      len = path.length();
886 886
      arcs = new Arc[len];
887 887
      int index = len;
888 888
      for (typename CPath::RevArcIt it(path); it != INVALID; ++it) {
889 889
        --index;
890 890
        arcs[index] = it;
891 891
      }
892 892
    }
893 893

	
894 894
  private:
895 895
    int len;
896 896
    Arc* arcs;
897 897
  };
898 898

	
899 899
  ///////////////////////////////////////////////////////////////////////
900 900
  // Additional utilities
901 901
  ///////////////////////////////////////////////////////////////////////
902 902

	
903 903
  namespace _path_bits {
904 904

	
905 905
    template <typename Path, typename Enable = void>
906 906
    struct RevPathTagIndicator {
907 907
      static const bool value = false;
908 908
    };
909 909

	
910 910
    template <typename Path>
911 911
    struct RevPathTagIndicator<
912 912
      Path,
913 913
      typename enable_if<typename Path::RevPathTag, void>::type
914 914
      > {
915 915
      static const bool value = true;
916 916
    };
917 917

	
918 918
    template <typename Path, typename Enable = void>
919 919
    struct BuildTagIndicator {
920 920
      static const bool value = false;
921 921
    };
922 922

	
923 923
    template <typename Path>
924 924
    struct BuildTagIndicator<
925 925
      Path,
926 926
      typename enable_if<typename Path::BuildTag, void>::type
927 927
    > {
928 928
      static const bool value = true;
929 929
    };
930 930

	
931 931
    template <typename Target, typename Source,
932 932
              bool buildEnable = BuildTagIndicator<Target>::value,
933 933
              bool revEnable = RevPathTagIndicator<Source>::value>
934 934
    struct PathCopySelector {
935 935
      static void copy(Target& target, const Source& source) {
936 936
        target.clear();
937 937
        for (typename Source::ArcIt it(source); it != INVALID; ++it) {
938 938
          target.addBack(it);
939 939
        }
940 940
      }
941 941
    };
942 942

	
943 943
    template <typename Target, typename Source>
944 944
    struct PathCopySelector<Target, Source, false, true> {
945 945
      static void copy(Target& target, const Source& source) {
946 946
        target.clear();
947 947
        for (typename Source::RevArcIt it(source); it != INVALID; ++it) {
948 948
          target.addFront(it);
949 949
        }
950 950
      }
951 951
    };
952 952

	
953 953
    template <typename Target, typename Source>
954 954
    struct PathCopySelector<Target, Source, true, false> {
955 955
      static void copy(Target& target, const Source& source) {
956 956
        target.clear();
957 957
        target.build(source);
958 958
      }
959 959
    };
960 960

	
961 961
    template <typename Target, typename Source>
962 962
    struct PathCopySelector<Target, Source, true, true> {
963 963
      static void copy(Target& target, const Source& source) {
964 964
        target.clear();
965 965
        target.buildRev(source);
966 966
      }
967 967
    };
968 968

	
969 969
  }
970 970

	
971 971

	
972 972
  /// \brief Make a copy of a path.
973 973
  ///
974 974
  ///  This function makes a copy of a path.
975 975
  template <typename Target, typename Source>
976 976
  void copyPath(Target& target, const Source& source) {
977 977
    checkConcept<concepts::PathDumper<typename Source::Digraph>, Source>();
978 978
    _path_bits::PathCopySelector<Target, Source>::copy(target, source);
979 979
  }
980 980

	
981 981
  /// \brief Check the consistency of a path.
982 982
  ///
983 983
  /// This function checks that the target of each arc is the same
984 984
  /// as the source of the next one.
985 985
  ///
986 986
  template <typename Digraph, typename Path>
987 987
  bool checkPath(const Digraph& digraph, const Path& path) {
988 988
    typename Path::ArcIt it(path);
989 989
    if (it == INVALID) return true;
990 990
    typename Digraph::Node node = digraph.target(it);
991 991
    ++it;
992 992
    while (it != INVALID) {
993 993
      if (digraph.source(it) != node) return false;
994 994
      node = digraph.target(it);
995 995
      ++it;
996 996
    }
997 997
    return true;
998 998
  }
999 999

	
1000 1000
  /// \brief The source of a path
1001 1001
  ///
1002 1002
  /// This function returns the source of the given path.
1003 1003
  template <typename Digraph, typename Path>
1004 1004
  typename Digraph::Node pathSource(const Digraph& digraph, const Path& path) {
1005 1005
    return digraph.source(path.front());
1006 1006
  }
1007 1007

	
1008 1008
  /// \brief The target of a path
1009 1009
  ///
1010 1010
  /// This function returns the target of the given path.
1011 1011
  template <typename Digraph, typename Path>
1012 1012
  typename Digraph::Node pathTarget(const Digraph& digraph, const Path& path) {
1013 1013
    return digraph.target(path.back());
1014 1014
  }
1015 1015

	
1016 1016
  /// \brief Class which helps to iterate through the nodes of a path
1017 1017
  ///
1018 1018
  /// In a sense, the path can be treated as a list of arcs. The
1019 1019
  /// lemon path type stores only this list. As a consequence, it
1020 1020
  /// cannot enumerate the nodes in the path and the zero length paths
1021 1021
  /// cannot have a source node.
1022 1022
  ///
1023 1023
  /// This class implements the node iterator of a path structure. To
1024 1024
  /// provide this feature, the underlying digraph should be passed to
1025 1025
  /// the constructor of the iterator.
1026 1026
  template <typename Path>
1027 1027
  class PathNodeIt {
1028 1028
  private:
1029 1029
    const typename Path::Digraph *_digraph;
1030 1030
    typename Path::ArcIt _it;
1031 1031
    typename Path::Digraph::Node _nd;
1032 1032

	
1033 1033
  public:
1034 1034

	
1035 1035
    typedef typename Path::Digraph Digraph;
1036 1036
    typedef typename Digraph::Node Node;
1037 1037

	
1038 1038
    /// Default constructor
1039 1039
    PathNodeIt() {}
1040 1040
    /// Invalid constructor
1041 1041
    PathNodeIt(Invalid)
1042 1042
      : _digraph(0), _it(INVALID), _nd(INVALID) {}
1043 1043
    /// Constructor
1044 1044
    PathNodeIt(const Digraph& digraph, const Path& path)
1045 1045
      : _digraph(&digraph), _it(path) {
1046 1046
      _nd = (_it != INVALID ? _digraph->source(_it) : INVALID);
1047 1047
    }
1048 1048
    /// Constructor
1049 1049
    PathNodeIt(const Digraph& digraph, const Path& path, const Node& src)
1050 1050
      : _digraph(&digraph), _it(path), _nd(src) {}
1051 1051

	
1052 1052
    ///Conversion to Digraph::Node
1053 1053
    operator Node() const {
1054 1054
      return _nd;
1055 1055
    }
1056 1056

	
1057 1057
    /// Next node
1058 1058
    PathNodeIt& operator++() {
1059 1059
      if (_it == INVALID) _nd = INVALID;
1060 1060
      else {
1061 1061
        _nd = _digraph->target(_it);
1062 1062
        ++_it;
1063 1063
      }
1064 1064
      return *this;
1065 1065
    }
1066 1066

	
1067 1067
    /// Comparison operator
1068 1068
    bool operator==(const PathNodeIt& n) const {
1069 1069
      return _it == n._it && _nd == n._nd;
1070 1070
    }
1071 1071
    /// Comparison operator
1072 1072
    bool operator!=(const PathNodeIt& n) const {
1073 1073
      return _it != n._it || _nd != n._nd;
1074 1074
    }
1075 1075
    /// Comparison operator
1076 1076
    bool operator<(const PathNodeIt& n) const {
1077 1077
      return (_it < n._it && _nd != INVALID);
1078 1078
    }
1079 1079

	
1080 1080
  };
1081 1081

	
1082 1082
  ///@}
1083 1083

	
1084 1084
} // namespace lemon
1085 1085

	
1086 1086
#endif // LEMON_PATH_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
#ifndef LEMON_SMART_GRAPH_H
20 20
#define LEMON_SMART_GRAPH_H
21 21

	
22 22
///\ingroup graphs
23 23
///\file
24 24
///\brief SmartDigraph and SmartGraph classes.
25 25

	
26 26
#include <vector>
27 27

	
28 28
#include <lemon/core.h>
29 29
#include <lemon/error.h>
30 30
#include <lemon/bits/graph_extender.h>
31 31

	
32 32
namespace lemon {
33 33

	
34 34
  class SmartDigraph;
35 35
  ///Base of SmartDigraph
36 36

	
37 37
  ///Base of SmartDigraph
38 38
  ///
39 39
  class SmartDigraphBase {
40 40
  protected:
41 41

	
42 42
    struct NodeT
43 43
    {
44 44
      int first_in, first_out;
45 45
      NodeT() {}
46 46
    };
47 47
    struct ArcT
48 48
    {
49 49
      int target, source, next_in, next_out;
50 50
      ArcT() {}
51 51
    };
52 52

	
53 53
    std::vector<NodeT> nodes;
54 54
    std::vector<ArcT> arcs;
55 55

	
56 56
  public:
57 57

	
58 58
    typedef SmartDigraphBase Graph;
59 59

	
60 60
    class Node;
61 61
    class Arc;
62 62

	
63 63
  public:
64 64

	
65 65
    SmartDigraphBase() : nodes(), arcs() { }
66 66
    SmartDigraphBase(const SmartDigraphBase &_g)
67 67
      : nodes(_g.nodes), arcs(_g.arcs) { }
68 68

	
69 69
    typedef True NodeNumTag;
70 70
    typedef True EdgeNumTag;
71 71

	
72 72
    int nodeNum() const { return nodes.size(); }
73 73
    int arcNum() const { return arcs.size(); }
74 74

	
75 75
    int maxNodeId() const { return nodes.size()-1; }
76 76
    int maxArcId() const { return arcs.size()-1; }
77 77

	
78 78
    Node addNode() {
79 79
      int n = nodes.size();
80 80
      nodes.push_back(NodeT());
81 81
      nodes[n].first_in = -1;
82 82
      nodes[n].first_out = -1;
83 83
      return Node(n);
84 84
    }
85 85

	
86 86
    Arc addArc(Node u, Node v) {
87 87
      int n = arcs.size();
88 88
      arcs.push_back(ArcT());
89 89
      arcs[n].source = u._id;
90 90
      arcs[n].target = v._id;
91 91
      arcs[n].next_out = nodes[u._id].first_out;
92 92
      arcs[n].next_in = nodes[v._id].first_in;
93 93
      nodes[u._id].first_out = nodes[v._id].first_in = n;
94 94

	
95 95
      return Arc(n);
96 96
    }
97 97

	
98 98
    void clear() {
99 99
      arcs.clear();
100 100
      nodes.clear();
101 101
    }
102 102

	
103 103
    Node source(Arc a) const { return Node(arcs[a._id].source); }
104 104
    Node target(Arc a) const { return Node(arcs[a._id].target); }
105 105

	
106 106
    static int id(Node v) { return v._id; }
107 107
    static int id(Arc a) { return a._id; }
108 108

	
109 109
    static Node nodeFromId(int id) { return Node(id);}
110 110
    static Arc arcFromId(int id) { return Arc(id);}
111 111

	
112 112
    bool valid(Node n) const {
113 113
      return n._id >= 0 && n._id < static_cast<int>(nodes.size());
114 114
    }
115 115
    bool valid(Arc a) const {
116 116
      return a._id >= 0 && a._id < static_cast<int>(arcs.size());
117 117
    }
118 118

	
119 119
    class Node {
120 120
      friend class SmartDigraphBase;
121 121
      friend class SmartDigraph;
122 122

	
123 123
    protected:
124 124
      int _id;
125 125
      explicit Node(int id) : _id(id) {}
126 126
    public:
127 127
      Node() {}
128 128
      Node (Invalid) : _id(-1) {}
129 129
      bool operator==(const Node i) const {return _id == i._id;}
130 130
      bool operator!=(const Node i) const {return _id != i._id;}
131 131
      bool operator<(const Node i) const {return _id < i._id;}
132 132
    };
133 133

	
134 134

	
135 135
    class Arc {
136 136
      friend class SmartDigraphBase;
137 137
      friend class SmartDigraph;
138 138

	
139 139
    protected:
140 140
      int _id;
141 141
      explicit Arc(int id) : _id(id) {}
142 142
    public:
143 143
      Arc() { }
144 144
      Arc (Invalid) : _id(-1) {}
145 145
      bool operator==(const Arc i) const {return _id == i._id;}
146 146
      bool operator!=(const Arc i) const {return _id != i._id;}
147 147
      bool operator<(const Arc i) const {return _id < i._id;}
148 148
    };
149 149

	
150 150
    void first(Node& node) const {
151 151
      node._id = nodes.size() - 1;
152 152
    }
153 153

	
154 154
    static void next(Node& node) {
155 155
      --node._id;
156 156
    }
157 157

	
158 158
    void first(Arc& arc) const {
159 159
      arc._id = arcs.size() - 1;
160 160
    }
161 161

	
162 162
    static void next(Arc& arc) {
163 163
      --arc._id;
164 164
    }
165 165

	
166 166
    void firstOut(Arc& arc, const Node& node) const {
167 167
      arc._id = nodes[node._id].first_out;
168 168
    }
169 169

	
170 170
    void nextOut(Arc& arc) const {
171 171
      arc._id = arcs[arc._id].next_out;
172 172
    }
173 173

	
174 174
    void firstIn(Arc& arc, const Node& node) const {
175 175
      arc._id = nodes[node._id].first_in;
176 176
    }
177 177

	
178 178
    void nextIn(Arc& arc) const {
179 179
      arc._id = arcs[arc._id].next_in;
180 180
    }
181 181

	
182 182
  };
183 183

	
184 184
  typedef DigraphExtender<SmartDigraphBase> ExtendedSmartDigraphBase;
185 185

	
186 186
  ///\ingroup graphs
187 187
  ///
188 188
  ///\brief A smart directed graph class.
189 189
  ///
190 190
  ///This is a simple and fast digraph implementation.
191 191
  ///It is also quite memory efficient, but at the price
192 192
  ///that <b> it does support only limited (only stack-like)
193 193
  ///node and arc deletions</b>.
194 194
  ///It conforms to the \ref concepts::Digraph "Digraph concept" with
195 195
  ///an important extra feature that its maps are real \ref
196 196
  ///concepts::ReferenceMap "reference map"s.
197 197
  ///
198 198
  ///\sa concepts::Digraph.
199 199
  class SmartDigraph : public ExtendedSmartDigraphBase {
200 200
  public:
201 201

	
202 202
    typedef ExtendedSmartDigraphBase Parent;
203 203

	
204 204
  private:
205 205

	
206 206
    ///SmartDigraph is \e not copy constructible. Use DigraphCopy() instead.
207 207

	
208 208
    ///SmartDigraph is \e not copy constructible. Use DigraphCopy() instead.
209 209
    ///
210 210
    SmartDigraph(const SmartDigraph &) : ExtendedSmartDigraphBase() {};
211 211
    ///\brief Assignment of SmartDigraph to another one is \e not allowed.
212 212
    ///Use DigraphCopy() instead.
213 213

	
214 214
    ///Assignment of SmartDigraph to another one is \e not allowed.
215 215
    ///Use DigraphCopy() instead.
216 216
    void operator=(const SmartDigraph &) {}
217 217

	
218 218
  public:
219 219

	
220 220
    /// Constructor
221 221

	
222 222
    /// Constructor.
223 223
    ///
224 224
    SmartDigraph() {};
225 225

	
226 226
    ///Add a new node to the digraph.
227 227

	
228 228
    /// \return the new node.
229 229
    ///
230 230
    Node addNode() { return Parent::addNode(); }
231 231

	
232 232
    ///Add a new arc to the digraph.
233 233

	
234 234
    ///Add a new arc to the digraph with source node \c s
235 235
    ///and target node \c t.
236 236
    ///\return the new arc.
237 237
    Arc addArc(const Node& s, const Node& t) {
238 238
      return Parent::addArc(s, t);
239 239
    }
240 240

	
241 241
    /// \brief Using this it is possible to avoid the superfluous memory
242 242
    /// allocation.
243 243

	
244 244
    /// Using this it is possible to avoid the superfluous memory
245 245
    /// allocation: if you know that the digraph you want to build will
246 246
    /// be very large (e.g. it will contain millions of nodes and/or arcs)
247 247
    /// then it is worth reserving space for this amount before starting
248 248
    /// to build the digraph.
249 249
    /// \sa reserveArc
250 250
    void reserveNode(int n) { nodes.reserve(n); };
251 251

	
252 252
    /// \brief Using this it is possible to avoid the superfluous memory
253 253
    /// allocation.
254 254

	
255 255
    /// Using this it is possible to avoid the superfluous memory
256 256
    /// allocation: if you know that the digraph you want to build will
257 257
    /// be very large (e.g. it will contain millions of nodes and/or arcs)
258 258
    /// then it is worth reserving space for this amount before starting
259 259
    /// to build the digraph.
260 260
    /// \sa reserveNode
261 261
    void reserveArc(int m) { arcs.reserve(m); };
262 262

	
263 263
    /// \brief Node validity check
264 264
    ///
265 265
    /// This function gives back true if the given node is valid,
266 266
    /// ie. it is a real node of the graph.
267 267
    ///
268 268
    /// \warning A removed node (using Snapshot) could become valid again
269 269
    /// when new nodes are added to the graph.
270 270
    bool valid(Node n) const { return Parent::valid(n); }
271 271

	
272 272
    /// \brief Arc validity check
273 273
    ///
274 274
    /// This function gives back true if the given arc is valid,
275 275
    /// ie. it is a real arc of the graph.
276 276
    ///
277 277
    /// \warning A removed arc (using Snapshot) could become valid again
278 278
    /// when new arcs are added to the graph.
279 279
    bool valid(Arc a) const { return Parent::valid(a); }
280 280

	
281 281
    ///Clear the digraph.
282 282

	
283 283
    ///Erase all the nodes and arcs from the digraph.
284 284
    ///
285 285
    void clear() {
286 286
      Parent::clear();
287 287
    }
288 288

	
289 289
    ///Split a node.
290 290

	
291 291
    ///This function splits a node. First a new node is added to the digraph,
292 292
    ///then the source of each outgoing arc of \c n is moved to this new node.
293 293
    ///If \c connect is \c true (this is the default value), then a new arc
294 294
    ///from \c n to the newly created node is also added.
295 295
    ///\return The newly created node.
296 296
    ///
297 297
    ///\note The <tt>Arc</tt>s
298 298
    ///referencing a moved arc remain
299 299
    ///valid. However <tt>InArc</tt>'s and <tt>OutArc</tt>'s
300 300
    ///may be invalidated.
301 301
    ///\warning This functionality cannot be used together with the Snapshot
302 302
    ///feature.
303 303
    Node split(Node n, bool connect = true)
304 304
    {
305 305
      Node b = addNode();
306 306
      nodes[b._id].first_out=nodes[n._id].first_out;
307 307
      nodes[n._id].first_out=-1;
308 308
      for(int i=nodes[b._id].first_out;i!=-1;i++) arcs[i].source=b._id;
309 309
      if(connect) addArc(n,b);
310 310
      return b;
311 311
    }
312 312

	
313 313
  public:
314 314

	
315 315
    class Snapshot;
316 316

	
317 317
  protected:
318 318

	
319 319
    void restoreSnapshot(const Snapshot &s)
320 320
    {
321 321
      while(s.arc_num<arcs.size()) {
322 322
        Arc arc = arcFromId(arcs.size()-1);
323 323
        Parent::notifier(Arc()).erase(arc);
324 324
        nodes[arcs.back().source].first_out=arcs.back().next_out;
325 325
        nodes[arcs.back().target].first_in=arcs.back().next_in;
326 326
        arcs.pop_back();
327 327
      }
328 328
      while(s.node_num<nodes.size()) {
329 329
        Node node = nodeFromId(nodes.size()-1);
330 330
        Parent::notifier(Node()).erase(node);
331 331
        nodes.pop_back();
332 332
      }
333 333
    }
334 334

	
335 335
  public:
336 336

	
337 337
    ///Class to make a snapshot of the digraph and to restrore to it later.
338 338

	
339 339
    ///Class to make a snapshot of the digraph and to restrore to it later.
340 340
    ///
341 341
    ///The newly added nodes and arcs can be removed using the
342 342
    ///restore() function.
343 343
    ///\note After you restore a state, you cannot restore
344 344
    ///a later state, in other word you cannot add again the arcs deleted
345 345
    ///by restore() using another one Snapshot instance.
346 346
    ///
347 347
    ///\warning If you do not use correctly the snapshot that can cause
348 348
    ///either broken program, invalid state of the digraph, valid but
349 349
    ///not the restored digraph or no change. Because the runtime performance
350 350
    ///the validity of the snapshot is not stored.
351 351
    class Snapshot
352 352
    {
353 353
      SmartDigraph *_graph;
354 354
    protected:
355 355
      friend class SmartDigraph;
356 356
      unsigned int node_num;
357 357
      unsigned int arc_num;
358 358
    public:
359 359
      ///Default constructor.
360 360

	
361 361
      ///Default constructor.
362 362
      ///To actually make a snapshot you must call save().
363 363
      ///
364 364
      Snapshot() : _graph(0) {}
365 365
      ///Constructor that immediately makes a snapshot
366 366

	
367 367
      ///This constructor immediately makes a snapshot of the digraph.
368
      ///\param _g The digraph we make a snapshot of.
368
      ///\param graph The digraph we make a snapshot of.
369 369
      Snapshot(SmartDigraph &graph) : _graph(&graph) {
370 370
        node_num=_graph->nodes.size();
371 371
        arc_num=_graph->arcs.size();
372 372
      }
373 373

	
374 374
      ///Make a snapshot.
375 375

	
376 376
      ///Make a snapshot of the digraph.
377 377
      ///
378 378
      ///This function can be called more than once. In case of a repeated
379 379
      ///call, the previous snapshot gets lost.
380
      ///\param _g The digraph we make the snapshot of.
380
      ///\param graph The digraph we make the snapshot of.
381 381
      void save(SmartDigraph &graph)
382 382
      {
383 383
        _graph=&graph;
384 384
        node_num=_graph->nodes.size();
385 385
        arc_num=_graph->arcs.size();
386 386
      }
387 387

	
388 388
      ///Undo the changes until a snapshot.
389 389

	
390 390
      ///Undo the changes until a snapshot created by save().
391 391
      ///
392 392
      ///\note After you restored a state, you cannot restore
393 393
      ///a later state, in other word you cannot add again the arcs deleted
394 394
      ///by restore().
395 395
      void restore()
396 396
      {
397 397
        _graph->restoreSnapshot(*this);
398 398
      }
399 399
    };
400 400
  };
401 401

	
402 402

	
403 403
  class SmartGraphBase {
404 404

	
405 405
  protected:
406 406

	
407 407
    struct NodeT {
408 408
      int first_out;
409 409
    };
410 410

	
411 411
    struct ArcT {
412 412
      int target;
413 413
      int next_out;
414 414
    };
415 415

	
416 416
    std::vector<NodeT> nodes;
417 417
    std::vector<ArcT> arcs;
418 418

	
419 419
    int first_free_arc;
420 420

	
421 421
  public:
422 422

	
423 423
    typedef SmartGraphBase Digraph;
424 424

	
425 425
    class Node;
426 426
    class Arc;
427 427
    class Edge;
428 428

	
429 429
    class Node {
430 430
      friend class SmartGraphBase;
431 431
    protected:
432 432

	
433 433
      int _id;
434 434
      explicit Node(int id) { _id = id;}
435 435

	
436 436
    public:
437 437
      Node() {}
438 438
      Node (Invalid) { _id = -1; }
439 439
      bool operator==(const Node& node) const {return _id == node._id;}
440 440
      bool operator!=(const Node& node) const {return _id != node._id;}
441 441
      bool operator<(const Node& node) const {return _id < node._id;}
442 442
    };
443 443

	
444 444
    class Edge {
445 445
      friend class SmartGraphBase;
446 446
    protected:
447 447

	
448 448
      int _id;
449 449
      explicit Edge(int id) { _id = id;}
450 450

	
451 451
    public:
452 452
      Edge() {}
453 453
      Edge (Invalid) { _id = -1; }
454 454
      bool operator==(const Edge& arc) const {return _id == arc._id;}
455 455
      bool operator!=(const Edge& arc) const {return _id != arc._id;}
456 456
      bool operator<(const Edge& arc) const {return _id < arc._id;}
457 457
    };
458 458

	
459 459
    class Arc {
460 460
      friend class SmartGraphBase;
461 461
    protected:
462 462

	
463 463
      int _id;
464 464
      explicit Arc(int id) { _id = id;}
465 465

	
466 466
    public:
467 467
      operator Edge() const { 
468 468
        return _id != -1 ? edgeFromId(_id / 2) : INVALID; 
469 469
      }
470 470

	
471 471
      Arc() {}
472 472
      Arc (Invalid) { _id = -1; }
473 473
      bool operator==(const Arc& arc) const {return _id == arc._id;}
474 474
      bool operator!=(const Arc& arc) const {return _id != arc._id;}
475 475
      bool operator<(const Arc& arc) const {return _id < arc._id;}
476 476
    };
477 477

	
478 478

	
479 479

	
480 480
    SmartGraphBase()
481 481
      : nodes(), arcs() {}
482 482

	
483 483

	
484 484
    int maxNodeId() const { return nodes.size()-1; }
485 485
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
486 486
    int maxArcId() const { return arcs.size()-1; }
487 487

	
488 488
    Node source(Arc e) const { return Node(arcs[e._id ^ 1].target); }
489 489
    Node target(Arc e) const { return Node(arcs[e._id].target); }
490 490

	
491 491
    Node u(Edge e) const { return Node(arcs[2 * e._id].target); }
492 492
    Node v(Edge e) const { return Node(arcs[2 * e._id + 1].target); }
493 493

	
494 494
    static bool direction(Arc e) {
495 495
      return (e._id & 1) == 1;
496 496
    }
497 497

	
498 498
    static Arc direct(Edge e, bool d) {
499 499
      return Arc(e._id * 2 + (d ? 1 : 0));
500 500
    }
501 501

	
502 502
    void first(Node& node) const {
503 503
      node._id = nodes.size() - 1;
504 504
    }
505 505

	
506 506
    void next(Node& node) const {
507 507
      --node._id;
508 508
    }
509 509

	
510 510
    void first(Arc& arc) const {
511 511
      arc._id = arcs.size() - 1;
512 512
    }
513 513

	
514 514
    void next(Arc& arc) const {
515 515
      --arc._id;
516 516
    }
517 517

	
518 518
    void first(Edge& arc) const {
519 519
      arc._id = arcs.size() / 2 - 1;
520 520
    }
521 521

	
522 522
    void next(Edge& arc) const {
523 523
      --arc._id;
524 524
    }
525 525

	
526 526
    void firstOut(Arc &arc, const Node& v) const {
527 527
      arc._id = nodes[v._id].first_out;
528 528
    }
529 529
    void nextOut(Arc &arc) const {
530 530
      arc._id = arcs[arc._id].next_out;
531 531
    }
532 532

	
533 533
    void firstIn(Arc &arc, const Node& v) const {
534 534
      arc._id = ((nodes[v._id].first_out) ^ 1);
535 535
      if (arc._id == -2) arc._id = -1;
536 536
    }
537 537
    void nextIn(Arc &arc) const {
538 538
      arc._id = ((arcs[arc._id ^ 1].next_out) ^ 1);
539 539
      if (arc._id == -2) arc._id = -1;
540 540
    }
541 541

	
542 542
    void firstInc(Edge &arc, bool& d, const Node& v) const {
543 543
      int de = nodes[v._id].first_out;
544 544
      if (de != -1) {
545 545
        arc._id = de / 2;
546 546
        d = ((de & 1) == 1);
547 547
      } else {
548 548
        arc._id = -1;
549 549
        d = true;
550 550
      }
551 551
    }
552 552
    void nextInc(Edge &arc, bool& d) const {
553 553
      int de = (arcs[(arc._id * 2) | (d ? 1 : 0)].next_out);
554 554
      if (de != -1) {
555 555
        arc._id = de / 2;
556 556
        d = ((de & 1) == 1);
557 557
      } else {
558 558
        arc._id = -1;
559 559
        d = true;
560 560
      }
561 561
    }
562 562

	
563 563
    static int id(Node v) { return v._id; }
564 564
    static int id(Arc e) { return e._id; }
565 565
    static int id(Edge e) { return e._id; }
566 566

	
567 567
    static Node nodeFromId(int id) { return Node(id);}
568 568
    static Arc arcFromId(int id) { return Arc(id);}
569 569
    static Edge edgeFromId(int id) { return Edge(id);}
570 570

	
571 571
    bool valid(Node n) const {
572 572
      return n._id >= 0 && n._id < static_cast<int>(nodes.size());
573 573
    }
574 574
    bool valid(Arc a) const {
575 575
      return a._id >= 0 && a._id < static_cast<int>(arcs.size());
576 576
    }
577 577
    bool valid(Edge e) const {
578 578
      return e._id >= 0 && 2 * e._id < static_cast<int>(arcs.size());
579 579
    }
580 580

	
581 581
    Node addNode() {
582 582
      int n = nodes.size();
583 583
      nodes.push_back(NodeT());
584 584
      nodes[n].first_out = -1;
585 585

	
586 586
      return Node(n);
587 587
    }
588 588

	
589 589
    Edge addEdge(Node u, Node v) {
590 590
      int n = arcs.size();
591 591
      arcs.push_back(ArcT());
592 592
      arcs.push_back(ArcT());
593 593

	
594 594
      arcs[n].target = u._id;
595 595
      arcs[n | 1].target = v._id;
596 596

	
597 597
      arcs[n].next_out = nodes[v._id].first_out;
598 598
      nodes[v._id].first_out = n;
599 599

	
600 600
      arcs[n | 1].next_out = nodes[u._id].first_out;
601 601
      nodes[u._id].first_out = (n | 1);
602 602

	
603 603
      return Edge(n / 2);
604 604
    }
605 605

	
606 606
    void clear() {
607 607
      arcs.clear();
608 608
      nodes.clear();
609 609
    }
610 610

	
611 611
  };
612 612

	
613 613
  typedef GraphExtender<SmartGraphBase> ExtendedSmartGraphBase;
614 614

	
615 615
  /// \ingroup graphs
616 616
  ///
617 617
  /// \brief A smart undirected graph class.
618 618
  ///
619 619
  /// This is a simple and fast graph implementation.
620 620
  /// It is also quite memory efficient, but at the price
621 621
  /// that <b> it does support only limited (only stack-like)
622 622
  /// node and arc deletions</b>.
623 623
  /// Except from this it conforms to
624 624
  /// the \ref concepts::Graph "Graph concept".
625 625
  ///
626 626
  /// It also has an
627 627
  /// important extra feature that
628 628
  /// its maps are real \ref concepts::ReferenceMap "reference map"s.
629 629
  ///
630 630
  /// \sa concepts::Graph.
631 631
  ///
632 632
  class SmartGraph : public ExtendedSmartGraphBase {
633 633
  private:
634 634

	
635 635
    ///SmartGraph is \e not copy constructible. Use GraphCopy() instead.
636 636

	
637 637
    ///SmartGraph is \e not copy constructible. Use GraphCopy() instead.
638 638
    ///
639 639
    SmartGraph(const SmartGraph &) : ExtendedSmartGraphBase() {};
640 640

	
641 641
    ///\brief Assignment of SmartGraph to another one is \e not allowed.
642 642
    ///Use GraphCopy() instead.
643 643

	
644 644
    ///Assignment of SmartGraph to another one is \e not allowed.
645 645
    ///Use GraphCopy() instead.
646 646
    void operator=(const SmartGraph &) {}
647 647

	
648 648
  public:
649 649

	
650 650
    typedef ExtendedSmartGraphBase Parent;
651 651

	
652 652
    /// Constructor
653 653

	
654 654
    /// Constructor.
655 655
    ///
656 656
    SmartGraph() {}
657 657

	
658 658
    ///Add a new node to the graph.
659 659

	
660 660
    /// \return the new node.
661 661
    ///
662 662
    Node addNode() { return Parent::addNode(); }
663 663

	
664 664
    ///Add a new edge to the graph.
665 665

	
666 666
    ///Add a new edge to the graph with node \c s
667 667
    ///and \c t.
668 668
    ///\return the new edge.
669 669
    Edge addEdge(const Node& s, const Node& t) {
670 670
      return Parent::addEdge(s, t);
671 671
    }
672 672

	
673 673
    /// \brief Node validity check
674 674
    ///
675 675
    /// This function gives back true if the given node is valid,
676 676
    /// ie. it is a real node of the graph.
677 677
    ///
678 678
    /// \warning A removed node (using Snapshot) could become valid again
679 679
    /// when new nodes are added to the graph.
680 680
    bool valid(Node n) const { return Parent::valid(n); }
681 681

	
682 682
    /// \brief Arc validity check
683 683
    ///
684 684
    /// This function gives back true if the given arc is valid,
685 685
    /// ie. it is a real arc of the graph.
686 686
    ///
687 687
    /// \warning A removed arc (using Snapshot) could become valid again
688 688
    /// when new edges are added to the graph.
689 689
    bool valid(Arc a) const { return Parent::valid(a); }
690 690

	
691 691
    /// \brief Edge validity check
692 692
    ///
693 693
    /// This function gives back true if the given edge is valid,
694 694
    /// ie. it is a real edge of the graph.
695 695
    ///
696 696
    /// \warning A removed edge (using Snapshot) could become valid again
697 697
    /// when new edges are added to the graph.
698 698
    bool valid(Edge e) const { return Parent::valid(e); }
699 699

	
700 700
    ///Clear the graph.
701 701

	
702 702
    ///Erase all the nodes and edges from the graph.
703 703
    ///
704 704
    void clear() {
705 705
      Parent::clear();
706 706
    }
707 707

	
708 708
  public:
709 709

	
710 710
    class Snapshot;
711 711

	
712 712
  protected:
713 713

	
714 714
    void saveSnapshot(Snapshot &s)
715 715
    {
716 716
      s._graph = this;
717 717
      s.node_num = nodes.size();
718 718
      s.arc_num = arcs.size();
719 719
    }
720 720

	
721 721
    void restoreSnapshot(const Snapshot &s)
722 722
    {
723 723
      while(s.arc_num<arcs.size()) {
724 724
        int n=arcs.size()-1;
725 725
        Edge arc=edgeFromId(n/2);
726 726
        Parent::notifier(Edge()).erase(arc);
727 727
        std::vector<Arc> dir;
728 728
        dir.push_back(arcFromId(n));
729 729
        dir.push_back(arcFromId(n-1));
730 730
        Parent::notifier(Arc()).erase(dir);
731 731
        nodes[arcs[n].target].first_out=arcs[n].next_out;
732 732
        nodes[arcs[n-1].target].first_out=arcs[n-1].next_out;
733 733
        arcs.pop_back();
734 734
        arcs.pop_back();
735 735
      }
736 736
      while(s.node_num<nodes.size()) {
737 737
        int n=nodes.size()-1;
738 738
        Node node = nodeFromId(n);
739 739
        Parent::notifier(Node()).erase(node);
740 740
        nodes.pop_back();
741 741
      }
742 742
    }
743 743

	
744 744
  public:
745 745

	
746 746
    ///Class to make a snapshot of the digraph and to restrore to it later.
747 747

	
748 748
    ///Class to make a snapshot of the digraph and to restrore to it later.
749 749
    ///
750 750
    ///The newly added nodes and arcs can be removed using the
751 751
    ///restore() function.
752 752
    ///
753 753
    ///\note After you restore a state, you cannot restore
754 754
    ///a later state, in other word you cannot add again the arcs deleted
755 755
    ///by restore() using another one Snapshot instance.
756 756
    ///
757 757
    ///\warning If you do not use correctly the snapshot that can cause
758 758
    ///either broken program, invalid state of the digraph, valid but
759 759
    ///not the restored digraph or no change. Because the runtime performance
760 760
    ///the validity of the snapshot is not stored.
761 761
    class Snapshot
762 762
    {
763 763
      SmartGraph *_graph;
764 764
    protected:
765 765
      friend class SmartGraph;
766 766
      unsigned int node_num;
767 767
      unsigned int arc_num;
768 768
    public:
769 769
      ///Default constructor.
770 770

	
771 771
      ///Default constructor.
772 772
      ///To actually make a snapshot you must call save().
773 773
      ///
774 774
      Snapshot() : _graph(0) {}
775 775
      ///Constructor that immediately makes a snapshot
776 776

	
777 777
      ///This constructor immediately makes a snapshot of the digraph.
778
      ///\param g The digraph we make a snapshot of.
778
      ///\param graph The digraph we make a snapshot of.
779 779
      Snapshot(SmartGraph &graph) {
780 780
        graph.saveSnapshot(*this);
781 781
      }
782 782

	
783 783
      ///Make a snapshot.
784 784

	
785 785
      ///Make a snapshot of the graph.
786 786
      ///
787 787
      ///This function can be called more than once. In case of a repeated
788 788
      ///call, the previous snapshot gets lost.
789
      ///\param g The digraph we make the snapshot of.
789
      ///\param graph The digraph we make the snapshot of.
790 790
      void save(SmartGraph &graph)
791 791
      {
792 792
        graph.saveSnapshot(*this);
793 793
      }
794 794

	
795 795
      ///Undo the changes until a snapshot.
796 796

	
797 797
      ///Undo the changes until a snapshot created by save().
798 798
      ///
799 799
      ///\note After you restored a state, you cannot restore
800 800
      ///a later state, in other word you cannot add again the arcs deleted
801 801
      ///by restore().
802 802
      void restore()
803 803
      {
804 804
        _graph->restoreSnapshot(*this);
805 805
      }
806 806
    };
807 807
  };
808 808

	
809 809
} //namespace lemon
810 810

	
811 811

	
812 812
#endif //LEMON_SMART_GRAPH_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
#ifndef LEMON_TIME_MEASURE_H
20 20
#define LEMON_TIME_MEASURE_H
21 21

	
22 22
///\ingroup timecount
23 23
///\file
24 24
///\brief Tools for measuring cpu usage
25 25

	
26 26
#ifdef WIN32
27 27
#define WIN32_LEAN_AND_MEAN
28 28
#define NOMINMAX
29 29
#include <windows.h>
30 30
#include <cmath>
31 31
#else
32 32
#include <sys/times.h>
33 33
#include <sys/time.h>
34 34
#endif
35 35

	
36 36
#include <string>
37 37
#include <fstream>
38 38
#include <iostream>
39 39

	
40 40
namespace lemon {
41 41

	
42 42
  /// \addtogroup timecount
43 43
  /// @{
44 44

	
45 45
  /// A class to store (cpu)time instances.
46 46

	
47 47
  /// This class stores five time values.
48 48
  /// - a real time
49 49
  /// - a user cpu time
50 50
  /// - a system cpu time
51 51
  /// - a user cpu time of children
52 52
  /// - a system cpu time of children
53 53
  ///
54 54
  /// TimeStamp's can be added to or substracted from each other and
55 55
  /// they can be pushed to a stream.
56 56
  ///
57 57
  /// In most cases, perhaps the \ref Timer or the \ref TimeReport
58 58
  /// class is what you want to use instead.
59 59

	
60 60
  class TimeStamp
61 61
  {
62 62
    double utime;
63 63
    double stime;
64 64
    double cutime;
65 65
    double cstime;
66 66
    double rtime;
67 67

	
68 68
    void _reset() {
69 69
      utime = stime = cutime = cstime = rtime = 0;
70 70
    }
71 71

	
72 72
  public:
73 73

	
74 74
    ///Read the current time values of the process
75 75
    void stamp()
76 76
    {
77 77
#ifndef WIN32
78 78
      timeval tv;
79 79
      gettimeofday(&tv, 0);
80 80
      rtime=tv.tv_sec+double(tv.tv_usec)/1e6;
81 81

	
82 82
      tms ts;
83 83
      double tck=sysconf(_SC_CLK_TCK);
84 84
      times(&ts);
85 85
      utime=ts.tms_utime/tck;
86 86
      stime=ts.tms_stime/tck;
87 87
      cutime=ts.tms_cutime/tck;
88 88
      cstime=ts.tms_cstime/tck;
89 89
#else
90 90
      static const double ch = 4294967296.0e-7;
91 91
      static const double cl = 1.0e-7;
92 92

	
93 93
      FILETIME system;
94 94
      GetSystemTimeAsFileTime(&system);
95 95
      rtime = ch * system.dwHighDateTime + cl * system.dwLowDateTime;
96 96

	
97 97
      FILETIME create, exit, kernel, user;
98 98
      if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
99 99
        utime = ch * user.dwHighDateTime + cl * user.dwLowDateTime;
100 100
        stime = ch * kernel.dwHighDateTime + cl * kernel.dwLowDateTime;
101 101
        cutime = 0;
102 102
        cstime = 0;
103 103
      } else {
104 104
        rtime = 0;
105 105
        utime = 0;
106 106
        stime = 0;
107 107
        cutime = 0;
108 108
        cstime = 0;
109 109
      }
110 110
#endif
111 111
    }
112 112

	
113 113
    /// Constructor initializing with zero
114 114
    TimeStamp()
115 115
    { _reset(); }
116 116
    ///Constructor initializing with the current time values of the process
117 117
    TimeStamp(void *) { stamp();}
118 118

	
119 119
    ///Set every time value to zero
120 120
    TimeStamp &reset() {_reset();return *this;}
121 121

	
122 122
    ///\e
123 123
    TimeStamp &operator+=(const TimeStamp &b)
124 124
    {
125 125
      utime+=b.utime;
126 126
      stime+=b.stime;
127 127
      cutime+=b.cutime;
128 128
      cstime+=b.cstime;
129 129
      rtime+=b.rtime;
130 130
      return *this;
131 131
    }
132 132
    ///\e
133 133
    TimeStamp operator+(const TimeStamp &b) const
134 134
    {
135 135
      TimeStamp t(*this);
136 136
      return t+=b;
137 137
    }
138 138
    ///\e
139 139
    TimeStamp &operator-=(const TimeStamp &b)
140 140
    {
141 141
      utime-=b.utime;
142 142
      stime-=b.stime;
143 143
      cutime-=b.cutime;
144 144
      cstime-=b.cstime;
145 145
      rtime-=b.rtime;
146 146
      return *this;
147 147
    }
148 148
    ///\e
149 149
    TimeStamp operator-(const TimeStamp &b) const
150 150
    {
151 151
      TimeStamp t(*this);
152 152
      return t-=b;
153 153
    }
154 154
    ///\e
155 155
    TimeStamp &operator*=(double b)
156 156
    {
157 157
      utime*=b;
158 158
      stime*=b;
159 159
      cutime*=b;
160 160
      cstime*=b;
161 161
      rtime*=b;
162 162
      return *this;
163 163
    }
164 164
    ///\e
165 165
    TimeStamp operator*(double b) const
166 166
    {
167 167
      TimeStamp t(*this);
168 168
      return t*=b;
169 169
    }
170 170
    friend TimeStamp operator*(double b,const TimeStamp &t);
171 171
    ///\e
172 172
    TimeStamp &operator/=(double b)
173 173
    {
174 174
      utime/=b;
175 175
      stime/=b;
176 176
      cutime/=b;
177 177
      cstime/=b;
178 178
      rtime/=b;
179 179
      return *this;
180 180
    }
181 181
    ///\e
182 182
    TimeStamp operator/(double b) const
183 183
    {
184 184
      TimeStamp t(*this);
185 185
      return t/=b;
186 186
    }
187 187
    ///The time ellapsed since the last call of stamp()
188 188
    TimeStamp ellapsed() const
189 189
    {
190 190
      TimeStamp t(NULL);
191 191
      return t-*this;
192 192
    }
193 193

	
194 194
    friend std::ostream& operator<<(std::ostream& os,const TimeStamp &t);
195 195

	
196 196
    ///Gives back the user time of the process
197 197
    double userTime() const
198 198
    {
199 199
      return utime;
200 200
    }
201 201
    ///Gives back the system time of the process
202 202
    double systemTime() const
203 203
    {
204 204
      return stime;
205 205
    }
206 206
    ///Gives back the user time of the process' children
207 207

	
208 208
    ///\note On <tt>WIN32</tt> platform this value is not calculated.
209 209
    ///
210 210
    double cUserTime() const
211 211
    {
212 212
      return cutime;
213 213
    }
214 214
    ///Gives back the user time of the process' children
215 215

	
216 216
    ///\note On <tt>WIN32</tt> platform this value is not calculated.
217 217
    ///
218 218
    double cSystemTime() const
219 219
    {
220 220
      return cstime;
221 221
    }
222 222
    ///Gives back the real time
223 223
    double realTime() const {return rtime;}
224 224
  };
225 225

	
226 226
  TimeStamp operator*(double b,const TimeStamp &t)
227 227
  {
228 228
    return t*b;
229 229
  }
230 230

	
231 231
  ///Prints the time counters
232 232

	
233 233
  ///Prints the time counters in the following form:
234 234
  ///
235 235
  /// <tt>u: XX.XXs s: XX.XXs cu: XX.XXs cs: XX.XXs real: XX.XXs</tt>
236 236
  ///
237 237
  /// where the values are the
238 238
  /// \li \c u: user cpu time,
239 239
  /// \li \c s: system cpu time,
240 240
  /// \li \c cu: user cpu time of children,
241 241
  /// \li \c cs: system cpu time of children,
242 242
  /// \li \c real: real time.
243 243
  /// \relates TimeStamp
244 244
  /// \note On <tt>WIN32</tt> platform the cummulative values are not
245 245
  /// calculated.
246 246
  inline std::ostream& operator<<(std::ostream& os,const TimeStamp &t)
247 247
  {
248 248
    os << "u: " << t.userTime() <<
249 249
      "s, s: " << t.systemTime() <<
250 250
      "s, cu: " << t.cUserTime() <<
251 251
      "s, cs: " << t.cSystemTime() <<
252 252
      "s, real: " << t.realTime() << "s";
253 253
    return os;
254 254
  }
255 255

	
256 256
  ///Class for measuring the cpu time and real time usage of the process
257 257

	
258 258
  ///Class for measuring the cpu time and real time usage of the process.
259 259
  ///It is quite easy-to-use, here is a short example.
260 260
  ///\code
261 261
  /// #include<lemon/time_measure.h>
262 262
  /// #include<iostream>
263 263
  ///
264 264
  /// int main()
265 265
  /// {
266 266
  ///
267 267
  ///   ...
268 268
  ///
269 269
  ///   Timer t;
270 270
  ///   doSomething();
271 271
  ///   std::cout << t << '\n';
272 272
  ///   t.restart();
273 273
  ///   doSomethingElse();
274 274
  ///   std::cout << t << '\n';
275 275
  ///
276 276
  ///   ...
277 277
  ///
278 278
  /// }
279 279
  ///\endcode
280 280
  ///
281 281
  ///The \ref Timer can also be \ref stop() "stopped" and
282 282
  ///\ref start() "started" again, so it is possible to compute collected
283 283
  ///running times.
284 284
  ///
285 285
  ///\warning Depending on the operation system and its actual configuration
286 286
  ///the time counters have a certain (10ms on a typical Linux system)
287 287
  ///granularity.
288 288
  ///Therefore this tool is not appropriate to measure very short times.
289 289
  ///Also, if you start and stop the timer very frequently, it could lead to
290 290
  ///distorted results.
291 291
  ///
292 292
  ///\note If you want to measure the running time of the execution of a certain
293 293
  ///function, consider the usage of \ref TimeReport instead.
294 294
  ///
295 295
  ///\sa TimeReport
296 296
  class Timer
297 297
  {
298 298
    int _running; //Timer is running iff _running>0; (_running>=0 always holds)
299 299
    TimeStamp start_time; //This is the relativ start-time if the timer
300 300
                          //is _running, the collected _running time otherwise.
301 301

	
302 302
    void _reset() {if(_running) start_time.stamp(); else start_time.reset();}
303 303

	
304 304
  public:
305 305
    ///Constructor.
306 306

	
307 307
    ///\param run indicates whether or not the timer starts immediately.
308 308
    ///
309 309
    Timer(bool run=true) :_running(run) {_reset();}
310 310

	
311 311
    ///\name Control the state of the timer
312 312
    ///Basically a Timer can be either running or stopped,
313 313
    ///but it provides a bit finer control on the execution.
314
    ///The \ref Timer also counts the number of \ref start()
315
    ///executions, and is stops only after the same amount (or more)
316
    ///\ref stop() "stop()"s. This can be useful e.g. to compute
317
    ///the running time
314
    ///The \ref lemon::Timer "Timer" also counts the number of 
315
    ///\ref lemon::Timer::start() "start()" executions, and it stops 
316
    ///only after the same amount (or more) \ref lemon::Timer::stop()
317
    ///"stop()"s. This can be useful e.g. to compute the running time
318 318
    ///of recursive functions.
319
    ///
320 319

	
321 320
    ///@{
322 321

	
323 322
    ///Reset and stop the time counters
324 323

	
325 324
    ///This function resets and stops the time counters
326 325
    ///\sa restart()
327 326
    void reset()
328 327
    {
329 328
      _running=0;
330 329
      _reset();
331 330
    }
332 331

	
333 332
    ///Start the time counters
334 333

	
335 334
    ///This function starts the time counters.
336 335
    ///
337 336
    ///If the timer is started more than ones, it will remain running
338 337
    ///until the same amount of \ref stop() is called.
339 338
    ///\sa stop()
340 339
    void start()
341 340
    {
342 341
      if(_running) _running++;
343 342
      else {
344 343
        _running=1;
345 344
        TimeStamp t;
346 345
        t.stamp();
347 346
        start_time=t-start_time;
348 347
      }
349 348
    }
350 349

	
351 350

	
352 351
    ///Stop the time counters
353 352

	
354 353
    ///This function stops the time counters. If start() was executed more than
355 354
    ///once, then the same number of stop() execution is necessary the really
356 355
    ///stop the timer.
357 356
    ///
358 357
    ///\sa halt()
359 358
    ///\sa start()
360 359
    ///\sa restart()
361 360
    ///\sa reset()
362 361

	
363 362
    void stop()
364 363
    {
365 364
      if(_running && !--_running) {
366 365
        TimeStamp t;
367 366
        t.stamp();
368 367
        start_time=t-start_time;
369 368
      }
370 369
    }
371 370

	
372 371
    ///Halt (i.e stop immediately) the time counters
373 372

	
374 373
    ///This function stops immediately the time counters, i.e. <tt>t.halt()</tt>
375 374
    ///is a faster
376 375
    ///equivalent of the following.
377 376
    ///\code
378 377
    ///  while(t.running()) t.stop()
379 378
    ///\endcode
380 379
    ///
381 380
    ///
382 381
    ///\sa stop()
383 382
    ///\sa restart()
384 383
    ///\sa reset()
385 384

	
386 385
    void halt()
387 386
    {
388 387
      if(_running) {
389 388
        _running=0;
390 389
        TimeStamp t;
391 390
        t.stamp();
392 391
        start_time=t-start_time;
393 392
      }
394 393
    }
395 394

	
396 395
    ///Returns the running state of the timer
397 396

	
398 397
    ///This function returns the number of stop() exections that is
399 398
    ///necessary to really stop the timer.
400 399
    ///For example the timer
401 400
    ///is running if and only if the return value is \c true
402 401
    ///(i.e. greater than
403 402
    ///zero).
404 403
    int running()  { return _running; }
405 404

	
406 405

	
407 406
    ///Restart the time counters
408 407

	
409 408
    ///This function is a shorthand for
410 409
    ///a reset() and a start() calls.
411 410
    ///
412 411
    void restart()
413 412
    {
414 413
      reset();
415 414
      start();
416 415
    }
417 416

	
418 417
    ///@}
419 418

	
420 419
    ///\name Query Functions for the ellapsed time
421 420

	
422 421
    ///@{
423 422

	
424 423
    ///Gives back the ellapsed user time of the process
425 424
    double userTime() const
426 425
    {
427 426
      return operator TimeStamp().userTime();
428 427
    }
429 428
    ///Gives back the ellapsed system time of the process
430 429
    double systemTime() const
431 430
    {
432 431
      return operator TimeStamp().systemTime();
433 432
    }
434 433
    ///Gives back the ellapsed user time of the process' children
435 434

	
436 435
    ///\note On <tt>WIN32</tt> platform this value is not calculated.
437 436
    ///
438 437
    double cUserTime() const
439 438
    {
440 439
      return operator TimeStamp().cUserTime();
441 440
    }
442 441
    ///Gives back the ellapsed user time of the process' children
443 442

	
444 443
    ///\note On <tt>WIN32</tt> platform this value is not calculated.
445 444
    ///
446 445
    double cSystemTime() const
447 446
    {
448 447
      return operator TimeStamp().cSystemTime();
449 448
    }
450 449
    ///Gives back the ellapsed real time
451 450
    double realTime() const
452 451
    {
453 452
      return operator TimeStamp().realTime();
454 453
    }
455 454
    ///Computes the ellapsed time
456 455

	
457 456
    ///This conversion computes the ellapsed time, therefore you can print
458 457
    ///the ellapsed time like this.
459 458
    ///\code
460 459
    ///  Timer t;
461 460
    ///  doSomething();
462 461
    ///  std::cout << t << '\n';
463 462
    ///\endcode
464 463
    operator TimeStamp () const
465 464
    {
466 465
      TimeStamp t;
467 466
      t.stamp();
468 467
      return _running?t-start_time:start_time;
469 468
    }
470 469

	
471 470

	
472 471
    ///@}
473 472
  };
474 473

	
475
  ///Same as \ref Timer but prints a report on destruction.
474
  ///Same as Timer but prints a report on destruction.
476 475

	
477 476
  ///Same as \ref Timer but prints a report on destruction.
478 477
  ///This example shows its usage.
479 478
  ///\code
480 479
  ///  void myAlg(ListGraph &g,int n)
481 480
  ///  {
482 481
  ///    TimeReport tr("Running time of myAlg: ");
483 482
  ///    ... //Here comes the algorithm
484 483
  ///  }
485 484
  ///\endcode
486 485
  ///
487 486
  ///\sa Timer
488 487
  ///\sa NoTimeReport
489 488
  class TimeReport : public Timer
490 489
  {
491 490
    std::string _title;
492 491
    std::ostream &_os;
493 492
  public:
494
    ///\e
493
    ///Constructor
495 494

	
495
    ///Constructor.
496 496
    ///\param title This text will be printed before the ellapsed time.
497 497
    ///\param os The stream to print the report to.
498 498
    ///\param run Sets whether the timer should start immediately.
499

	
500 499
    TimeReport(std::string title,std::ostream &os=std::cerr,bool run=true)
501 500
      : Timer(run), _title(title), _os(os){}
502
    ///\e Prints the ellapsed time on destruction.
501
    ///Destructor that prints the ellapsed time
503 502
    ~TimeReport()
504 503
    {
505 504
      _os << _title << *this << std::endl;
506 505
    }
507 506
  };
508 507

	
509
  ///'Do nothing' version of \ref TimeReport
508
  ///'Do nothing' version of TimeReport
510 509

	
511 510
  ///\sa TimeReport
512 511
  ///
513 512
  class NoTimeReport
514 513
  {
515 514
  public:
516 515
    ///\e
517 516
    NoTimeReport(std::string,std::ostream &,bool) {}
518 517
    ///\e
519 518
    NoTimeReport(std::string,std::ostream &) {}
520 519
    ///\e
521 520
    NoTimeReport(std::string) {}
522 521
    ///\e Do nothing.
523 522
    ~NoTimeReport() {}
524 523

	
525 524
    operator TimeStamp () const { return TimeStamp(); }
526 525
    void reset() {}
527 526
    void start() {}
528 527
    void stop() {}
529 528
    void halt() {}
530 529
    int running() { return 0; }
531 530
    void restart() {}
532 531
    double userTime() const { return 0; }
533 532
    double systemTime() const { return 0; }
534 533
    double cUserTime() const { return 0; }
535 534
    double cSystemTime() const { return 0; }
536 535
    double realTime() const { return 0; }
537 536
  };
538 537

	
539 538
  ///Tool to measure the running time more exactly.
540 539

	
541 540
  ///This function calls \c f several times and returns the average
542 541
  ///running time. The number of the executions will be choosen in such a way
543 542
  ///that the full real running time will be roughly between \c min_time
544 543
  ///and <tt>2*min_time</tt>.
545 544
  ///\param f the function object to be measured.
546 545
  ///\param min_time the minimum total running time.
547 546
  ///\retval num if it is not \c NULL, then the actual
548 547
  ///        number of execution of \c f will be written into <tt>*num</tt>.
549 548
  ///\retval full_time if it is not \c NULL, then the actual
550 549
  ///        total running time will be written into <tt>*full_time</tt>.
551 550
  ///\return The average running time of \c f.
552 551

	
553 552
  template<class F>
554 553
  TimeStamp runningTimeTest(F f,double min_time=10,unsigned int *num = NULL,
555 554
                            TimeStamp *full_time=NULL)
556 555
  {
557 556
    TimeStamp full;
558 557
    unsigned int total=0;
559 558
    Timer t;
560 559
    for(unsigned int tn=1;tn <= 1U<<31 && full.realTime()<=min_time; tn*=2) {
561 560
      for(;total<tn;total++) f();
562 561
      full=t;
563 562
    }
564 563
    if(num) *num=total;
565 564
    if(full_time) *full_time=full;
566 565
    return full/total;
567 566
  }
568 567

	
569 568
  /// @}
570 569

	
571 570

	
572 571
} //namespace lemon
573 572

	
574 573
#endif //LEMON_TIME_MEASURE_H
0 comments (0 inline)