gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Small doc fixes in several files (#331)
0 21 0
default
21 files changed:
↑ Collapse diff ↑
Ignore white space 12884901888 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-2009
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
\page min_cost_flow Minimum Cost Flow Problem
23 23

	
24 24
\section mcf_def Definition (GEQ form)
25 25

	
26 26
The \e minimum \e cost \e flow \e problem is to find a feasible flow of
27 27
minimum total cost from a set of supply nodes to a set of demand nodes
28 28
in a network with capacity constraints (lower and upper bounds)
29 29
and arc costs.
30 30

	
31 31
Formally, let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{R}\f$,
32 32
\f$upper: A\rightarrow\mathbf{R}\cup\{+\infty\}\f$ denote the lower and
33 33
upper bounds for the flow values on the arcs, for which
34 34
\f$lower(uv) \leq upper(uv)\f$ must hold for all \f$uv\in A\f$,
35 35
\f$cost: A\rightarrow\mathbf{R}\f$ denotes the cost per unit flow
36 36
on the arcs and \f$sup: V\rightarrow\mathbf{R}\f$ denotes the
37 37
signed supply values of the nodes.
38 38
If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
39 39
supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
40 40
\f$-sup(u)\f$ demand.
41 41
A minimum cost flow is an \f$f: A\rightarrow\mathbf{R}\f$ solution
42 42
of the following optimization problem.
43 43

	
44 44
\f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
45 45
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
46 46
    sup(u) \quad \forall u\in V \f]
47 47
\f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
48 48

	
49 49
The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
50 50
zero or negative in order to have a feasible solution (since the sum
51 51
of the expressions on the left-hand side of the inequalities is zero).
52 52
It means that the total demand must be greater or equal to the total
53 53
supply and all the supplies have to be carried out from the supply nodes,
54 54
but there could be demands that are not satisfied.
55 55
If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
56 56
constraints have to be satisfied with equality, i.e. all demands
57 57
have to be satisfied and all supplies have to be used.
58 58

	
59 59

	
60 60
\section mcf_algs Algorithms
61 61

	
62 62
LEMON contains several algorithms for solving this problem, for more
63 63
information see \ref min_cost_flow_algs "Minimum Cost Flow Algorithms".
64 64

	
65 65
A feasible solution for this problem can be found using \ref Circulation.
66 66

	
67 67

	
68 68
\section mcf_dual Dual Solution
69 69

	
70 70
The dual solution of the minimum cost flow problem is represented by
71 71
node potentials \f$\pi: V\rightarrow\mathbf{R}\f$.
72 72
An \f$f: A\rightarrow\mathbf{R}\f$ primal feasible solution is optimal
73 73
if and only if for some \f$\pi: V\rightarrow\mathbf{R}\f$ node potentials
74 74
the following \e complementary \e slackness optimality conditions hold.
75 75

	
76 76
 - For all \f$uv\in A\f$ arcs:
77 77
   - if \f$cost^\pi(uv)>0\f$, then \f$f(uv)=lower(uv)\f$;
78 78
   - if \f$lower(uv)<f(uv)<upper(uv)\f$, then \f$cost^\pi(uv)=0\f$;
79 79
   - if \f$cost^\pi(uv)<0\f$, then \f$f(uv)=upper(uv)\f$.
80 80
 - For all \f$u\in V\f$ nodes:
81
   - \f$\pi(u)<=0\f$;
81
   - \f$\pi(u)\leq 0\f$;
82 82
   - if \f$\sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \neq sup(u)\f$,
83 83
     then \f$\pi(u)=0\f$.
84 84
 
85 85
Here \f$cost^\pi(uv)\f$ denotes the \e reduced \e cost of the arc
86 86
\f$uv\in A\f$ with respect to the potential function \f$\pi\f$, i.e.
87 87
\f[ cost^\pi(uv) = cost(uv) + \pi(u) - \pi(v).\f]
88 88

	
89 89
All algorithms provide dual solution (node potentials), as well,
90 90
if an optimal flow is found.
91 91

	
92 92

	
93 93
\section mcf_eq Equality Form
94 94

	
95 95
The above \ref mcf_def "definition" is actually more general than the
96 96
usual formulation of the minimum cost flow problem, in which strict
97 97
equalities are required in the supply/demand contraints.
98 98

	
99 99
\f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
100 100
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) =
101 101
    sup(u) \quad \forall u\in V \f]
102 102
\f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
103 103

	
104 104
However if the sum of the supply values is zero, then these two problems
105 105
are equivalent.
106 106
The \ref min_cost_flow_algs "algorithms" in LEMON support the general
107 107
form, so if you need the equality form, you have to ensure this additional
108 108
contraint manually.
109 109

	
110 110

	
111 111
\section mcf_leq Opposite Inequalites (LEQ Form)
112 112

	
113 113
Another possible definition of the minimum cost flow problem is
114 114
when there are <em>"less or equal"</em> (LEQ) supply/demand constraints,
115 115
instead of the <em>"greater or equal"</em> (GEQ) constraints.
116 116

	
117 117
\f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
118 118
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
119 119
    sup(u) \quad \forall u\in V \f]
120 120
\f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
121 121

	
122 122
It means that the total demand must be less or equal to the 
123 123
total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
124 124
positive) and all the demands have to be satisfied, but there
125 125
could be supplies that are not carried out from the supply
126 126
nodes.
127 127
The equality form is also a special case of this form, of course.
128 128

	
129 129
You could easily transform this case to the \ref mcf_def "GEQ form"
130 130
of the problem by reversing the direction of the arcs and taking the
131 131
negative of the supply values (e.g. using \ref ReverseDigraph and
132 132
\ref NegMap adaptors).
133 133
However \ref NetworkSimplex algorithm also supports this form directly
134 134
for the sake of convenience.
135 135

	
136 136
Note that the optimality conditions for this supply constraint type are
137 137
slightly differ from the conditions that are discussed for the GEQ form,
138 138
namely the potentials have to be non-negative instead of non-positive.
139 139
An \f$f: A\rightarrow\mathbf{R}\f$ feasible solution of this problem
140 140
is optimal if and only if for some \f$\pi: V\rightarrow\mathbf{R}\f$
141 141
node potentials the following conditions hold.
142 142

	
143 143
 - For all \f$uv\in A\f$ arcs:
144 144
   - if \f$cost^\pi(uv)>0\f$, then \f$f(uv)=lower(uv)\f$;
145 145
   - if \f$lower(uv)<f(uv)<upper(uv)\f$, then \f$cost^\pi(uv)=0\f$;
146 146
   - if \f$cost^\pi(uv)<0\f$, then \f$f(uv)=upper(uv)\f$.
147 147
 - For all \f$u\in V\f$ nodes:
148
   - \f$\pi(u)>=0\f$;
148
   - \f$\pi(u)\geq 0\f$;
149 149
   - if \f$\sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \neq sup(u)\f$,
150 150
     then \f$\pi(u)=0\f$.
151 151

	
152 152
*/
153 153
}
Ignore white space 6 line context
1 1
/* -*- C++ -*-
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_BELLMAN_FORD_H
20 20
#define LEMON_BELLMAN_FORD_H
21 21

	
22 22
/// \ingroup shortest_path
23 23
/// \file
24 24
/// \brief Bellman-Ford algorithm.
25 25

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

	
32 32
#include <limits>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default OperationTraits for the BellmanFord algorithm class.
37 37
  ///  
38 38
  /// This operation traits class defines all computational operations
39 39
  /// and constants that are used in the Bellman-Ford algorithm.
40 40
  /// The default implementation is based on the \c numeric_limits class.
41 41
  /// If the numeric type does not have infinity value, then the maximum
42 42
  /// value is used as extremal infinity value.
43 43
  template <
44 44
    typename V, 
45 45
    bool has_inf = std::numeric_limits<V>::has_infinity>
46 46
  struct BellmanFordDefaultOperationTraits {
47 47
    /// \e
48 48
    typedef V Value;
49 49
    /// \brief Gives back the zero value of the type.
50 50
    static Value zero() {
51 51
      return static_cast<Value>(0);
52 52
    }
53 53
    /// \brief Gives back the positive infinity value of the type.
54 54
    static Value infinity() {
55 55
      return std::numeric_limits<Value>::infinity();
56 56
    }
57 57
    /// \brief Gives back the sum of the given two elements.
58 58
    static Value plus(const Value& left, const Value& right) {
59 59
      return left + right;
60 60
    }
61 61
    /// \brief Gives back \c true only if the first value is less than
62 62
    /// the second.
63 63
    static bool less(const Value& left, const Value& right) {
64 64
      return left < right;
65 65
    }
66 66
  };
67 67

	
68 68
  template <typename V>
69 69
  struct BellmanFordDefaultOperationTraits<V, false> {
70 70
    typedef V Value;
71 71
    static Value zero() {
72 72
      return static_cast<Value>(0);
73 73
    }
74 74
    static Value infinity() {
75 75
      return std::numeric_limits<Value>::max();
76 76
    }
77 77
    static Value plus(const Value& left, const Value& right) {
78 78
      if (left == infinity() || right == infinity()) return infinity();
79 79
      return left + right;
80 80
    }
81 81
    static bool less(const Value& left, const Value& right) {
82 82
      return left < right;
83 83
    }
84 84
  };
85 85
  
86 86
  /// \brief Default traits class of BellmanFord class.
87 87
  ///
88 88
  /// Default traits class of BellmanFord class.
89 89
  /// \param GR The type of the digraph.
90 90
  /// \param LEN The type of the length map.
91 91
  template<typename GR, typename LEN>
92 92
  struct BellmanFordDefaultTraits {
93 93
    /// The type of the digraph the algorithm runs on. 
94 94
    typedef GR Digraph;
95 95

	
96 96
    /// \brief The type of the map that stores the arc lengths.
97 97
    ///
98 98
    /// The type of the map that stores the arc lengths.
99 99
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
100 100
    typedef LEN LengthMap;
101 101

	
102 102
    /// The type of the arc lengths.
103 103
    typedef typename LEN::Value Value;
104 104

	
105 105
    /// \brief Operation traits for Bellman-Ford algorithm.
106 106
    ///
107 107
    /// It defines the used operations and the infinity value for the
108 108
    /// given \c Value type.
109 109
    /// \see BellmanFordDefaultOperationTraits
110 110
    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
111 111
 
112 112
    /// \brief The type of the map that stores the last arcs of the 
113 113
    /// shortest paths.
114 114
    /// 
115 115
    /// The type of the map that stores the last
116 116
    /// arcs of the shortest paths.
117 117
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
118 118
    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
119 119

	
120 120
    /// \brief Instantiates a \c PredMap.
121 121
    /// 
122 122
    /// This function instantiates a \ref PredMap. 
123 123
    /// \param g is the digraph to which we would like to define the
124 124
    /// \ref PredMap.
125 125
    static PredMap *createPredMap(const GR& g) {
126 126
      return new PredMap(g);
127 127
    }
128 128

	
129 129
    /// \brief The type of the map that stores the distances of the nodes.
130 130
    ///
131 131
    /// The type of the map that stores the distances of the nodes.
132 132
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
133 133
    typedef typename GR::template NodeMap<typename LEN::Value> DistMap;
134 134

	
135 135
    /// \brief Instantiates a \c DistMap.
136 136
    ///
137 137
    /// This function instantiates a \ref DistMap. 
138 138
    /// \param g is the digraph to which we would like to define the 
139 139
    /// \ref DistMap.
140 140
    static DistMap *createDistMap(const GR& g) {
141 141
      return new DistMap(g);
142 142
    }
143 143

	
144 144
  };
145 145
  
146 146
  /// \brief %BellmanFord algorithm class.
147 147
  ///
148 148
  /// \ingroup shortest_path
149 149
  /// This class provides an efficient implementation of the Bellman-Ford 
150 150
  /// algorithm. The maximum time complexity of the algorithm is
151 151
  /// <tt>O(ne)</tt>.
152 152
  ///
153 153
  /// The Bellman-Ford algorithm solves the single-source shortest path
154 154
  /// problem when the arcs can have negative lengths, but the digraph
155 155
  /// should not contain directed cycles with negative total length.
156 156
  /// If all arc costs are non-negative, consider to use the Dijkstra
157 157
  /// algorithm instead, since it is more efficient.
158 158
  ///
159 159
  /// The arc lengths are passed to the algorithm using a
160 160
  /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any 
161 161
  /// kind of length. The type of the length values is determined by the
162 162
  /// \ref concepts::ReadMap::Value "Value" type of the length map.
163 163
  ///
164 164
  /// There is also a \ref bellmanFord() "function-type interface" for the
165 165
  /// Bellman-Ford algorithm, which is convenient in the simplier cases and
166 166
  /// it can be used easier.
167 167
  ///
168 168
  /// \tparam GR The type of the digraph the algorithm runs on.
169 169
  /// The default type is \ref ListDigraph.
170 170
  /// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
171 171
  /// the lengths of the arcs. The default map type is
172 172
  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
173 173
#ifdef DOXYGEN
174 174
  template <typename GR, typename LEN, typename TR>
175 175
#else
176 176
  template <typename GR=ListDigraph,
177 177
            typename LEN=typename GR::template ArcMap<int>,
178 178
            typename TR=BellmanFordDefaultTraits<GR,LEN> >
179 179
#endif
180 180
  class BellmanFord {
181 181
  public:
182 182

	
183 183
    ///The type of the underlying digraph.
184 184
    typedef typename TR::Digraph Digraph;
185 185
    
186 186
    /// \brief The type of the arc lengths.
187 187
    typedef typename TR::LengthMap::Value Value;
188 188
    /// \brief The type of the map that stores the arc lengths.
189 189
    typedef typename TR::LengthMap LengthMap;
190 190
    /// \brief The type of the map that stores the last
191 191
    /// arcs of the shortest paths.
192 192
    typedef typename TR::PredMap PredMap;
193 193
    /// \brief The type of the map that stores the distances of the nodes.
194 194
    typedef typename TR::DistMap DistMap;
195 195
    /// The type of the paths.
196 196
    typedef PredMapPath<Digraph, PredMap> Path;
197 197
    ///\brief The \ref BellmanFordDefaultOperationTraits
198 198
    /// "operation traits class" of the algorithm.
199 199
    typedef typename TR::OperationTraits OperationTraits;
200 200

	
201 201
    ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
202 202
    typedef TR Traits;
203 203

	
204 204
  private:
205 205

	
206 206
    typedef typename Digraph::Node Node;
207 207
    typedef typename Digraph::NodeIt NodeIt;
208 208
    typedef typename Digraph::Arc Arc;
209 209
    typedef typename Digraph::OutArcIt OutArcIt;
210 210

	
211 211
    // Pointer to the underlying digraph.
212 212
    const Digraph *_gr;
213 213
    // Pointer to the length map
214 214
    const LengthMap *_length;
215 215
    // Pointer to the map of predecessors arcs.
216 216
    PredMap *_pred;
217 217
    // Indicates if _pred is locally allocated (true) or not.
218 218
    bool _local_pred;
219 219
    // Pointer to the map of distances.
220 220
    DistMap *_dist;
221 221
    // Indicates if _dist is locally allocated (true) or not.
222 222
    bool _local_dist;
223 223

	
224 224
    typedef typename Digraph::template NodeMap<bool> MaskMap;
225 225
    MaskMap *_mask;
226 226

	
227 227
    std::vector<Node> _process;
228 228

	
229 229
    // Creates the maps if necessary.
230 230
    void create_maps() {
231 231
      if(!_pred) {
232 232
	_local_pred = true;
233 233
	_pred = Traits::createPredMap(*_gr);
234 234
      }
235 235
      if(!_dist) {
236 236
	_local_dist = true;
237 237
	_dist = Traits::createDistMap(*_gr);
238 238
      }
239 239
      _mask = new MaskMap(*_gr, false);
240 240
    }
241 241
    
242 242
  public :
243 243
 
244 244
    typedef BellmanFord Create;
245 245

	
246 246
    /// \name Named Template Parameters
247 247

	
248 248
    ///@{
249 249

	
250 250
    template <class T>
251 251
    struct SetPredMapTraits : public Traits {
252 252
      typedef T PredMap;
253 253
      static PredMap *createPredMap(const Digraph&) {
254 254
        LEMON_ASSERT(false, "PredMap is not initialized");
255 255
        return 0; // ignore warnings
256 256
      }
257 257
    };
258 258

	
259 259
    /// \brief \ref named-templ-param "Named parameter" for setting
260 260
    /// \c PredMap type.
261 261
    ///
262 262
    /// \ref named-templ-param "Named parameter" for setting
263 263
    /// \c PredMap type.
264 264
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
265 265
    template <class T>
266 266
    struct SetPredMap 
267 267
      : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
268 268
      typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
269 269
    };
270 270
    
271 271
    template <class T>
272 272
    struct SetDistMapTraits : public Traits {
273 273
      typedef T DistMap;
274 274
      static DistMap *createDistMap(const Digraph&) {
275 275
        LEMON_ASSERT(false, "DistMap is not initialized");
276 276
        return 0; // ignore warnings
277 277
      }
278 278
    };
279 279

	
280 280
    /// \brief \ref named-templ-param "Named parameter" for setting
281 281
    /// \c DistMap type.
282 282
    ///
283 283
    /// \ref named-templ-param "Named parameter" for setting
284 284
    /// \c DistMap type.
285 285
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
286 286
    template <class T>
287 287
    struct SetDistMap 
288 288
      : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
289 289
      typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
290 290
    };
291 291

	
292 292
    template <class T>
293 293
    struct SetOperationTraitsTraits : public Traits {
294 294
      typedef T OperationTraits;
295 295
    };
296 296
    
297 297
    /// \brief \ref named-templ-param "Named parameter" for setting 
298 298
    /// \c OperationTraits type.
299 299
    ///
300 300
    /// \ref named-templ-param "Named parameter" for setting
301 301
    /// \c OperationTraits type.
302
    /// For more information see \ref BellmanFordDefaultOperationTraits.
302
    /// For more information, see \ref BellmanFordDefaultOperationTraits.
303 303
    template <class T>
304 304
    struct SetOperationTraits
305 305
      : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
306 306
      typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
307 307
      Create;
308 308
    };
309 309
    
310 310
    ///@}
311 311

	
312 312
  protected:
313 313
    
314 314
    BellmanFord() {}
315 315

	
316 316
  public:      
317 317
    
318 318
    /// \brief Constructor.
319 319
    ///
320 320
    /// Constructor.
321 321
    /// \param g The digraph the algorithm runs on.
322 322
    /// \param length The length map used by the algorithm.
323 323
    BellmanFord(const Digraph& g, const LengthMap& length) :
324 324
      _gr(&g), _length(&length),
325 325
      _pred(0), _local_pred(false),
326 326
      _dist(0), _local_dist(false), _mask(0) {}
327 327
    
328 328
    ///Destructor.
329 329
    ~BellmanFord() {
330 330
      if(_local_pred) delete _pred;
331 331
      if(_local_dist) delete _dist;
332 332
      if(_mask) delete _mask;
333 333
    }
334 334

	
335 335
    /// \brief Sets the length map.
336 336
    ///
337 337
    /// Sets the length map.
338 338
    /// \return <tt>(*this)</tt>
339 339
    BellmanFord &lengthMap(const LengthMap &map) {
340 340
      _length = &map;
341 341
      return *this;
342 342
    }
343 343

	
344 344
    /// \brief Sets the map that stores the predecessor arcs.
345 345
    ///
346 346
    /// Sets the map that stores the predecessor arcs.
347 347
    /// If you don't use this function before calling \ref run()
348 348
    /// or \ref init(), an instance will be allocated automatically.
349 349
    /// The destructor deallocates this automatically allocated map,
350 350
    /// of course.
351 351
    /// \return <tt>(*this)</tt>
352 352
    BellmanFord &predMap(PredMap &map) {
353 353
      if(_local_pred) {
354 354
	delete _pred;
355 355
	_local_pred=false;
356 356
      }
357 357
      _pred = &map;
358 358
      return *this;
359 359
    }
360 360

	
361 361
    /// \brief Sets the map that stores the distances of the nodes.
362 362
    ///
363 363
    /// Sets the map that stores the distances of the nodes calculated
364 364
    /// by the algorithm.
365 365
    /// If you don't use this function before calling \ref run()
366 366
    /// or \ref init(), an instance will be allocated automatically.
367 367
    /// The destructor deallocates this automatically allocated map,
368 368
    /// of course.
369 369
    /// \return <tt>(*this)</tt>
370 370
    BellmanFord &distMap(DistMap &map) {
371 371
      if(_local_dist) {
372 372
	delete _dist;
373 373
	_local_dist=false;
374 374
      }
375 375
      _dist = &map;
376 376
      return *this;
377 377
    }
378 378

	
379 379
    /// \name Execution Control
380 380
    /// The simplest way to execute the Bellman-Ford algorithm is to use
381 381
    /// one of the member functions called \ref run().\n
382 382
    /// If you need better control on the execution, you have to call
383 383
    /// \ref init() first, then you can add several source nodes
384 384
    /// with \ref addSource(). Finally the actual path computation can be
385 385
    /// performed with \ref start(), \ref checkedStart() or
386 386
    /// \ref limitedStart().
387 387

	
388 388
    ///@{
389 389

	
390 390
    /// \brief Initializes the internal data structures.
391 391
    /// 
392 392
    /// Initializes the internal data structures. The optional parameter
393 393
    /// is the initial distance of each node.
394 394
    void init(const Value value = OperationTraits::infinity()) {
395 395
      create_maps();
396 396
      for (NodeIt it(*_gr); it != INVALID; ++it) {
397 397
	_pred->set(it, INVALID);
398 398
	_dist->set(it, value);
399 399
      }
400 400
      _process.clear();
401 401
      if (OperationTraits::less(value, OperationTraits::infinity())) {
402 402
	for (NodeIt it(*_gr); it != INVALID; ++it) {
403 403
	  _process.push_back(it);
404 404
	  _mask->set(it, true);
405 405
	}
406 406
      }
407 407
    }
408 408
    
409 409
    /// \brief Adds a new source node.
410 410
    ///
411 411
    /// This function adds a new source node. The optional second parameter
412 412
    /// is the initial distance of the node.
413 413
    void addSource(Node source, Value dst = OperationTraits::zero()) {
414 414
      _dist->set(source, dst);
415 415
      if (!(*_mask)[source]) {
416 416
	_process.push_back(source);
417 417
	_mask->set(source, true);
418 418
      }
419 419
    }
420 420

	
421 421
    /// \brief Executes one round from the Bellman-Ford algorithm.
422 422
    ///
423 423
    /// If the algoritm calculated the distances in the previous round
424 424
    /// exactly for the paths of at most \c k arcs, then this function
425 425
    /// will calculate the distances exactly for the paths of at most
426 426
    /// <tt>k+1</tt> arcs. Performing \c k iterations using this function
427 427
    /// calculates the shortest path distances exactly for the paths
428 428
    /// consisting of at most \c k arcs.
429 429
    ///
430 430
    /// \warning The paths with limited arc number cannot be retrieved
431 431
    /// easily with \ref path() or \ref predArc() functions. If you also
432 432
    /// need the shortest paths and not only the distances, you should
433 433
    /// store the \ref predMap() "predecessor map" after each iteration
434 434
    /// and build the path manually.
435 435
    ///
436 436
    /// \return \c true when the algorithm have not found more shorter
437 437
    /// paths.
438 438
    ///
439 439
    /// \see ActiveIt
440 440
    bool processNextRound() {
441 441
      for (int i = 0; i < int(_process.size()); ++i) {
442 442
	_mask->set(_process[i], false);
443 443
      }
444 444
      std::vector<Node> nextProcess;
445 445
      std::vector<Value> values(_process.size());
446 446
      for (int i = 0; i < int(_process.size()); ++i) {
447 447
	values[i] = (*_dist)[_process[i]];
448 448
      }
449 449
      for (int i = 0; i < int(_process.size()); ++i) {
450 450
	for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
451 451
	  Node target = _gr->target(it);
452 452
	  Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
453 453
	  if (OperationTraits::less(relaxed, (*_dist)[target])) {
454 454
	    _pred->set(target, it);
455 455
	    _dist->set(target, relaxed);
456 456
	    if (!(*_mask)[target]) {
457 457
	      _mask->set(target, true);
458 458
	      nextProcess.push_back(target);
459 459
	    }
460 460
	  }	  
461 461
	}
462 462
      }
463 463
      _process.swap(nextProcess);
464 464
      return _process.empty();
465 465
    }
466 466

	
467 467
    /// \brief Executes one weak round from the Bellman-Ford algorithm.
468 468
    ///
469 469
    /// If the algorithm calculated the distances in the previous round
470 470
    /// at least for the paths of at most \c k arcs, then this function
471 471
    /// will calculate the distances at least for the paths of at most
472 472
    /// <tt>k+1</tt> arcs.
473 473
    /// This function does not make it possible to calculate the shortest
474 474
    /// path distances exactly for paths consisting of at most \c k arcs,
475 475
    /// this is why it is called weak round.
476 476
    ///
477 477
    /// \return \c true when the algorithm have not found more shorter
478 478
    /// paths.
479 479
    ///
480 480
    /// \see ActiveIt
481 481
    bool processNextWeakRound() {
482 482
      for (int i = 0; i < int(_process.size()); ++i) {
483 483
	_mask->set(_process[i], false);
484 484
      }
485 485
      std::vector<Node> nextProcess;
486 486
      for (int i = 0; i < int(_process.size()); ++i) {
487 487
	for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
488 488
	  Node target = _gr->target(it);
489 489
	  Value relaxed = 
490 490
	    OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
491 491
	  if (OperationTraits::less(relaxed, (*_dist)[target])) {
492 492
	    _pred->set(target, it);
493 493
	    _dist->set(target, relaxed);
494 494
	    if (!(*_mask)[target]) {
495 495
	      _mask->set(target, true);
496 496
	      nextProcess.push_back(target);
497 497
	    }
498 498
	  }	  
499 499
	}
500 500
      }
501 501
      _process.swap(nextProcess);
502 502
      return _process.empty();
503 503
    }
504 504

	
505 505
    /// \brief Executes the algorithm.
506 506
    ///
507 507
    /// Executes the algorithm.
508 508
    ///
509 509
    /// This method runs the Bellman-Ford algorithm from the root node(s)
510 510
    /// in order to compute the shortest path to each node.
511 511
    ///
512 512
    /// The algorithm computes
513 513
    /// - the shortest path tree (forest),
514 514
    /// - the distance of each node from the root(s).
515 515
    ///
516 516
    /// \pre init() must be called and at least one root node should be
517 517
    /// added with addSource() before using this function.
518 518
    void start() {
519 519
      int num = countNodes(*_gr) - 1;
520 520
      for (int i = 0; i < num; ++i) {
521 521
	if (processNextWeakRound()) break;
522 522
      }
523 523
    }
524 524

	
525 525
    /// \brief Executes the algorithm and checks the negative cycles.
526 526
    ///
527 527
    /// Executes the algorithm and checks the negative cycles.
528 528
    ///
529 529
    /// This method runs the Bellman-Ford algorithm from the root node(s)
530 530
    /// in order to compute the shortest path to each node and also checks
531 531
    /// if the digraph contains cycles with negative total length.
532 532
    ///
533 533
    /// The algorithm computes 
534 534
    /// - the shortest path tree (forest),
535 535
    /// - the distance of each node from the root(s).
536 536
    /// 
537 537
    /// \return \c false if there is a negative cycle in the digraph.
538 538
    ///
539 539
    /// \pre init() must be called and at least one root node should be
540 540
    /// added with addSource() before using this function. 
541 541
    bool checkedStart() {
542 542
      int num = countNodes(*_gr);
543 543
      for (int i = 0; i < num; ++i) {
544 544
	if (processNextWeakRound()) return true;
545 545
      }
546 546
      return _process.empty();
547 547
    }
548 548

	
549 549
    /// \brief Executes the algorithm with arc number limit.
550 550
    ///
551 551
    /// Executes the algorithm with arc number limit.
552 552
    ///
553 553
    /// This method runs the Bellman-Ford algorithm from the root node(s)
554 554
    /// in order to compute the shortest path distance for each node
555 555
    /// using only the paths consisting of at most \c num arcs.
556 556
    ///
557 557
    /// The algorithm computes
558 558
    /// - the limited distance of each node from the root(s),
559 559
    /// - the predecessor arc for each node.
560 560
    ///
561 561
    /// \warning The paths with limited arc number cannot be retrieved
562 562
    /// easily with \ref path() or \ref predArc() functions. If you also
563 563
    /// need the shortest paths and not only the distances, you should
564 564
    /// store the \ref predMap() "predecessor map" after each iteration
565 565
    /// and build the path manually.
566 566
    ///
567 567
    /// \pre init() must be called and at least one root node should be
568 568
    /// added with addSource() before using this function. 
569 569
    void limitedStart(int num) {
570 570
      for (int i = 0; i < num; ++i) {
571 571
	if (processNextRound()) break;
572 572
      }
573 573
    }
574 574
    
575 575
    /// \brief Runs the algorithm from the given root node.
576 576
    ///    
577 577
    /// This method runs the Bellman-Ford algorithm from the given root
578 578
    /// node \c s in order to compute the shortest path to each node.
579 579
    ///
580 580
    /// The algorithm computes
581 581
    /// - the shortest path tree (forest),
582 582
    /// - the distance of each node from the root(s).
583 583
    ///
584 584
    /// \note bf.run(s) is just a shortcut of the following code.
585 585
    /// \code
586 586
    ///   bf.init();
587 587
    ///   bf.addSource(s);
588 588
    ///   bf.start();
589 589
    /// \endcode
590 590
    void run(Node s) {
591 591
      init();
592 592
      addSource(s);
593 593
      start();
594 594
    }
595 595
    
596 596
    /// \brief Runs the algorithm from the given root node with arc
597 597
    /// number limit.
598 598
    ///    
599 599
    /// This method runs the Bellman-Ford algorithm from the given root
600 600
    /// node \c s in order to compute the shortest path distance for each
601 601
    /// node using only the paths consisting of at most \c num arcs.
602 602
    ///
603 603
    /// The algorithm computes
604 604
    /// - the limited distance of each node from the root(s),
605 605
    /// - the predecessor arc for each node.
606 606
    ///
607 607
    /// \warning The paths with limited arc number cannot be retrieved
608 608
    /// easily with \ref path() or \ref predArc() functions. If you also
609 609
    /// need the shortest paths and not only the distances, you should
610 610
    /// store the \ref predMap() "predecessor map" after each iteration
611 611
    /// and build the path manually.
612 612
    ///
613 613
    /// \note bf.run(s, num) is just a shortcut of the following code.
614 614
    /// \code
615 615
    ///   bf.init();
616 616
    ///   bf.addSource(s);
617 617
    ///   bf.limitedStart(num);
618 618
    /// \endcode
619 619
    void run(Node s, int num) {
620 620
      init();
621 621
      addSource(s);
622 622
      limitedStart(num);
623 623
    }
624 624
    
625 625
    ///@}
626 626

	
627 627
    /// \brief LEMON iterator for getting the active nodes.
628 628
    ///
629 629
    /// This class provides a common style LEMON iterator that traverses
630 630
    /// the active nodes of the Bellman-Ford algorithm after the last
631 631
    /// phase. These nodes should be checked in the next phase to
632 632
    /// find augmenting arcs outgoing from them.
633 633
    class ActiveIt {
634 634
    public:
635 635

	
636 636
      /// \brief Constructor.
637 637
      ///
638 638
      /// Constructor for getting the active nodes of the given BellmanFord
639 639
      /// instance. 
640 640
      ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
641 641
      {
642 642
        _index = _algorithm->_process.size() - 1;
643 643
      }
644 644

	
645 645
      /// \brief Invalid constructor.
646 646
      ///
647 647
      /// Invalid constructor.
648 648
      ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
649 649

	
650 650
      /// \brief Conversion to \c Node.
651 651
      ///
652 652
      /// Conversion to \c Node.
653 653
      operator Node() const { 
654 654
        return _index >= 0 ? _algorithm->_process[_index] : INVALID;
655 655
      }
656 656

	
657 657
      /// \brief Increment operator.
658 658
      ///
659 659
      /// Increment operator.
660 660
      ActiveIt& operator++() {
661 661
        --_index;
662 662
        return *this; 
663 663
      }
664 664

	
665 665
      bool operator==(const ActiveIt& it) const { 
666 666
        return static_cast<Node>(*this) == static_cast<Node>(it); 
667 667
      }
668 668
      bool operator!=(const ActiveIt& it) const { 
669 669
        return static_cast<Node>(*this) != static_cast<Node>(it); 
670 670
      }
671 671
      bool operator<(const ActiveIt& it) const { 
672 672
        return static_cast<Node>(*this) < static_cast<Node>(it); 
673 673
      }
674 674
      
675 675
    private:
676 676
      const BellmanFord* _algorithm;
677 677
      int _index;
678 678
    };
679 679
    
680 680
    /// \name Query Functions
681 681
    /// The result of the Bellman-Ford algorithm can be obtained using these
682 682
    /// functions.\n
683 683
    /// Either \ref run() or \ref init() should be called before using them.
684 684
    
685 685
    ///@{
686 686

	
687 687
    /// \brief The shortest path to the given node.
688 688
    ///    
689 689
    /// Gives back the shortest path to the given node from the root(s).
690 690
    ///
691 691
    /// \warning \c t should be reached from the root(s).
692 692
    ///
693 693
    /// \pre Either \ref run() or \ref init() must be called before
694 694
    /// using this function.
695 695
    Path path(Node t) const
696 696
    {
697 697
      return Path(*_gr, *_pred, t);
698 698
    }
699 699
	  
700 700
    /// \brief The distance of the given node from the root(s).
701 701
    ///
702 702
    /// Returns the distance of the given node from the root(s).
703 703
    ///
704 704
    /// \warning If node \c v is not reached from the root(s), then
705 705
    /// the return value of this function is undefined.
706 706
    ///
707 707
    /// \pre Either \ref run() or \ref init() must be called before
708 708
    /// using this function.
709 709
    Value dist(Node v) const { return (*_dist)[v]; }
710 710

	
711 711
    /// \brief Returns the 'previous arc' of the shortest path tree for
712 712
    /// the given node.
713 713
    ///
714 714
    /// This function returns the 'previous arc' of the shortest path
715 715
    /// tree for node \c v, i.e. it returns the last arc of a
716 716
    /// shortest path from a root to \c v. It is \c INVALID if \c v
717 717
    /// is not reached from the root(s) or if \c v is a root.
718 718
    ///
719 719
    /// The shortest path tree used here is equal to the shortest path
720
    /// tree used in \ref predNode() and \predMap().
720
    /// tree used in \ref predNode() and \ref predMap().
721 721
    ///
722 722
    /// \pre Either \ref run() or \ref init() must be called before
723 723
    /// using this function.
724 724
    Arc predArc(Node v) const { return (*_pred)[v]; }
725 725

	
726 726
    /// \brief Returns the 'previous node' of the shortest path tree for
727 727
    /// the given node.
728 728
    ///
729 729
    /// This function returns the 'previous node' of the shortest path
730 730
    /// tree for node \c v, i.e. it returns the last but one node of
731 731
    /// a shortest path from a root to \c v. It is \c INVALID if \c v
732 732
    /// is not reached from the root(s) or if \c v is a root.
733 733
    ///
734 734
    /// The shortest path tree used here is equal to the shortest path
735
    /// tree used in \ref predArc() and \predMap().
735
    /// tree used in \ref predArc() and \ref predMap().
736 736
    ///
737 737
    /// \pre Either \ref run() or \ref init() must be called before
738 738
    /// using this function.
739 739
    Node predNode(Node v) const { 
740 740
      return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]); 
741 741
    }
742 742
    
743 743
    /// \brief Returns a const reference to the node map that stores the
744 744
    /// distances of the nodes.
745 745
    ///
746 746
    /// Returns a const reference to the node map that stores the distances
747 747
    /// of the nodes calculated by the algorithm.
748 748
    ///
749 749
    /// \pre Either \ref run() or \ref init() must be called before
750 750
    /// using this function.
751 751
    const DistMap &distMap() const { return *_dist;}
752 752
 
753 753
    /// \brief Returns a const reference to the node map that stores the
754 754
    /// predecessor arcs.
755 755
    ///
756 756
    /// Returns a const reference to the node map that stores the predecessor
757 757
    /// arcs, which form the shortest path tree (forest).
758 758
    ///
759 759
    /// \pre Either \ref run() or \ref init() must be called before
760 760
    /// using this function.
761 761
    const PredMap &predMap() const { return *_pred; }
762 762
 
763 763
    /// \brief Checks if a node is reached from the root(s).
764 764
    ///
765 765
    /// Returns \c true if \c v is reached from the root(s).
766 766
    ///
767 767
    /// \pre Either \ref run() or \ref init() must be called before
768 768
    /// using this function.
769 769
    bool reached(Node v) const {
770 770
      return (*_dist)[v] != OperationTraits::infinity();
771 771
    }
772 772

	
773 773
    /// \brief Gives back a negative cycle.
774 774
    ///    
775 775
    /// This function gives back a directed cycle with negative total
776 776
    /// length if the algorithm has already found one.
777 777
    /// Otherwise it gives back an empty path.
778 778
    lemon::Path<Digraph> negativeCycle() {
779 779
      typename Digraph::template NodeMap<int> state(*_gr, -1);
780 780
      lemon::Path<Digraph> cycle;
781 781
      for (int i = 0; i < int(_process.size()); ++i) {
782 782
        if (state[_process[i]] != -1) continue;
783 783
        for (Node v = _process[i]; (*_pred)[v] != INVALID;
784 784
             v = _gr->source((*_pred)[v])) {
785 785
          if (state[v] == i) {
786 786
            cycle.addFront((*_pred)[v]);
787 787
            for (Node u = _gr->source((*_pred)[v]); u != v;
788 788
                 u = _gr->source((*_pred)[u])) {
789 789
              cycle.addFront((*_pred)[u]);
790 790
            }
791 791
            return cycle;
792 792
          }
793 793
          else if (state[v] >= 0) {
794 794
            break;
795 795
          }
796 796
          state[v] = i;
797 797
        }
798 798
      }
799 799
      return cycle;
800 800
    }
801 801
    
802 802
    ///@}
803 803
  };
804 804
 
805 805
  /// \brief Default traits class of bellmanFord() function.
806 806
  ///
807 807
  /// Default traits class of bellmanFord() function.
808 808
  /// \tparam GR The type of the digraph.
809 809
  /// \tparam LEN The type of the length map.
810 810
  template <typename GR, typename LEN>
811 811
  struct BellmanFordWizardDefaultTraits {
812 812
    /// The type of the digraph the algorithm runs on. 
813 813
    typedef GR Digraph;
814 814

	
815 815
    /// \brief The type of the map that stores the arc lengths.
816 816
    ///
817 817
    /// The type of the map that stores the arc lengths.
818 818
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
819 819
    typedef LEN LengthMap;
820 820

	
821 821
    /// The type of the arc lengths.
822 822
    typedef typename LEN::Value Value;
823 823

	
824 824
    /// \brief Operation traits for Bellman-Ford algorithm.
825 825
    ///
826 826
    /// It defines the used operations and the infinity value for the
827 827
    /// given \c Value type.
828 828
    /// \see BellmanFordDefaultOperationTraits
829 829
    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
830 830

	
831 831
    /// \brief The type of the map that stores the last
832 832
    /// arcs of the shortest paths.
833 833
    /// 
834 834
    /// The type of the map that stores the last arcs of the shortest paths.
835 835
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
836 836
    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
837 837

	
838 838
    /// \brief Instantiates a \c PredMap.
839 839
    /// 
840 840
    /// This function instantiates a \ref PredMap.
841 841
    /// \param g is the digraph to which we would like to define the
842 842
    /// \ref PredMap.
843 843
    static PredMap *createPredMap(const GR &g) {
844 844
      return new PredMap(g);
845 845
    }
846 846

	
847 847
    /// \brief The type of the map that stores the distances of the nodes.
848 848
    ///
849 849
    /// The type of the map that stores the distances of the nodes.
850 850
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
851 851
    typedef typename GR::template NodeMap<Value> DistMap;
852 852

	
853 853
    /// \brief Instantiates a \c DistMap.
854 854
    ///
855 855
    /// This function instantiates a \ref DistMap. 
856 856
    /// \param g is the digraph to which we would like to define the
857 857
    /// \ref DistMap.
858 858
    static DistMap *createDistMap(const GR &g) {
859 859
      return new DistMap(g);
860 860
    }
861 861

	
862 862
    ///The type of the shortest paths.
863 863

	
864 864
    ///The type of the shortest paths.
865 865
    ///It must meet the \ref concepts::Path "Path" concept.
866 866
    typedef lemon::Path<Digraph> Path;
867 867
  };
868 868
  
869 869
  /// \brief Default traits class used by BellmanFordWizard.
870 870
  ///
871 871
  /// Default traits class used by BellmanFordWizard.
872 872
  /// \tparam GR The type of the digraph.
873 873
  /// \tparam LEN The type of the length map.
874 874
  template <typename GR, typename LEN>
875 875
  class BellmanFordWizardBase 
876 876
    : public BellmanFordWizardDefaultTraits<GR, LEN> {
877 877

	
878 878
    typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
879 879
  protected:
880 880
    // Type of the nodes in the digraph.
881 881
    typedef typename Base::Digraph::Node Node;
882 882

	
883 883
    // Pointer to the underlying digraph.
884 884
    void *_graph;
885 885
    // Pointer to the length map
886 886
    void *_length;
887 887
    // Pointer to the map of predecessors arcs.
888 888
    void *_pred;
889 889
    // Pointer to the map of distances.
890 890
    void *_dist;
891 891
    //Pointer to the shortest path to the target node.
892 892
    void *_path;
893 893
    //Pointer to the distance of the target node.
894 894
    void *_di;
895 895

	
896 896
    public:
897 897
    /// Constructor.
898 898
    
899 899
    /// This constructor does not require parameters, it initiates
900 900
    /// all of the attributes to default values \c 0.
901 901
    BellmanFordWizardBase() :
902 902
      _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
903 903

	
904 904
    /// Constructor.
905 905
    
906 906
    /// This constructor requires two parameters,
907 907
    /// others are initiated to \c 0.
908 908
    /// \param gr The digraph the algorithm runs on.
909 909
    /// \param len The length map.
910 910
    BellmanFordWizardBase(const GR& gr, 
911 911
			  const LEN& len) :
912 912
      _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))), 
913 913
      _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))), 
914 914
      _pred(0), _dist(0), _path(0), _di(0) {}
915 915

	
916 916
  };
917 917
  
918 918
  /// \brief Auxiliary class for the function-type interface of the
919 919
  /// \ref BellmanFord "Bellman-Ford" algorithm.
920 920
  ///
921 921
  /// This auxiliary class is created to implement the
922 922
  /// \ref bellmanFord() "function-type interface" of the
923 923
  /// \ref BellmanFord "Bellman-Ford" algorithm.
924 924
  /// It does not have own \ref run() method, it uses the
925 925
  /// functions and features of the plain \ref BellmanFord.
926 926
  ///
927 927
  /// This class should only be used through the \ref bellmanFord()
928 928
  /// function, which makes it easier to use the algorithm.
929 929
  template<class TR>
930 930
  class BellmanFordWizard : public TR {
931 931
    typedef TR Base;
932 932

	
933 933
    typedef typename TR::Digraph Digraph;
934 934

	
935 935
    typedef typename Digraph::Node Node;
936 936
    typedef typename Digraph::NodeIt NodeIt;
937 937
    typedef typename Digraph::Arc Arc;
938 938
    typedef typename Digraph::OutArcIt ArcIt;
939 939
    
940 940
    typedef typename TR::LengthMap LengthMap;
941 941
    typedef typename LengthMap::Value Value;
942 942
    typedef typename TR::PredMap PredMap;
943 943
    typedef typename TR::DistMap DistMap;
944 944
    typedef typename TR::Path Path;
945 945

	
946 946
  public:
947 947
    /// Constructor.
948 948
    BellmanFordWizard() : TR() {}
949 949

	
950 950
    /// \brief Constructor that requires parameters.
951 951
    ///
952 952
    /// Constructor that requires parameters.
953 953
    /// These parameters will be the default values for the traits class.
954 954
    /// \param gr The digraph the algorithm runs on.
955 955
    /// \param len The length map.
956 956
    BellmanFordWizard(const Digraph& gr, const LengthMap& len) 
957 957
      : TR(gr, len) {}
958 958

	
959 959
    /// \brief Copy constructor
960 960
    BellmanFordWizard(const TR &b) : TR(b) {}
961 961

	
962 962
    ~BellmanFordWizard() {}
963 963

	
964 964
    /// \brief Runs the Bellman-Ford algorithm from the given source node.
965 965
    ///    
966 966
    /// This method runs the Bellman-Ford algorithm from the given source
967 967
    /// node in order to compute the shortest path to each node.
968 968
    void run(Node s) {
969 969
      BellmanFord<Digraph,LengthMap,TR> 
970 970
	bf(*reinterpret_cast<const Digraph*>(Base::_graph), 
971 971
           *reinterpret_cast<const LengthMap*>(Base::_length));
972 972
      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
973 973
      if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
974 974
      bf.run(s);
975 975
    }
976 976

	
977 977
    /// \brief Runs the Bellman-Ford algorithm to find the shortest path
978 978
    /// between \c s and \c t.
979 979
    ///
980 980
    /// This method runs the Bellman-Ford algorithm from node \c s
981 981
    /// in order to compute the shortest path to node \c t.
982 982
    /// Actually, it computes the shortest path to each node, but using
983 983
    /// this function you can retrieve the distance and the shortest path
984 984
    /// for a single target node easier.
985 985
    ///
986 986
    /// \return \c true if \c t is reachable form \c s.
987 987
    bool run(Node s, Node t) {
988 988
      BellmanFord<Digraph,LengthMap,TR>
989 989
        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
990 990
           *reinterpret_cast<const LengthMap*>(Base::_length));
991 991
      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
992 992
      if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
993 993
      bf.run(s);
994 994
      if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
995 995
      if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
996 996
      return bf.reached(t);
997 997
    }
998 998

	
999 999
    template<class T>
1000 1000
    struct SetPredMapBase : public Base {
1001 1001
      typedef T PredMap;
1002 1002
      static PredMap *createPredMap(const Digraph &) { return 0; };
1003 1003
      SetPredMapBase(const TR &b) : TR(b) {}
1004 1004
    };
1005 1005
    
1006 1006
    /// \brief \ref named-templ-param "Named parameter" for setting
1007 1007
    /// the predecessor map.
1008 1008
    ///
1009 1009
    /// \ref named-templ-param "Named parameter" for setting
1010 1010
    /// the map that stores the predecessor arcs of the nodes.
1011 1011
    template<class T>
1012 1012
    BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
1013 1013
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1014 1014
      return BellmanFordWizard<SetPredMapBase<T> >(*this);
1015 1015
    }
1016 1016
    
1017 1017
    template<class T>
1018 1018
    struct SetDistMapBase : public Base {
1019 1019
      typedef T DistMap;
1020 1020
      static DistMap *createDistMap(const Digraph &) { return 0; };
1021 1021
      SetDistMapBase(const TR &b) : TR(b) {}
1022 1022
    };
1023 1023
    
1024 1024
    /// \brief \ref named-templ-param "Named parameter" for setting
1025 1025
    /// the distance map.
1026 1026
    ///
1027 1027
    /// \ref named-templ-param "Named parameter" for setting
1028 1028
    /// the map that stores the distances of the nodes calculated
1029 1029
    /// by the algorithm.
1030 1030
    template<class T>
1031 1031
    BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
1032 1032
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1033 1033
      return BellmanFordWizard<SetDistMapBase<T> >(*this);
1034 1034
    }
1035 1035

	
1036 1036
    template<class T>
1037 1037
    struct SetPathBase : public Base {
1038 1038
      typedef T Path;
1039 1039
      SetPathBase(const TR &b) : TR(b) {}
1040 1040
    };
1041 1041

	
1042 1042
    /// \brief \ref named-func-param "Named parameter" for getting
1043 1043
    /// the shortest path to the target node.
1044 1044
    ///
1045 1045
    /// \ref named-func-param "Named parameter" for getting
1046 1046
    /// the shortest path to the target node.
1047 1047
    template<class T>
1048 1048
    BellmanFordWizard<SetPathBase<T> > path(const T &t)
1049 1049
    {
1050 1050
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1051 1051
      return BellmanFordWizard<SetPathBase<T> >(*this);
1052 1052
    }
1053 1053

	
1054 1054
    /// \brief \ref named-func-param "Named parameter" for getting
1055 1055
    /// the distance of the target node.
1056 1056
    ///
1057 1057
    /// \ref named-func-param "Named parameter" for getting
1058 1058
    /// the distance of the target node.
1059 1059
    BellmanFordWizard dist(const Value &d)
1060 1060
    {
1061 1061
      Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1062 1062
      return *this;
1063 1063
    }
1064 1064
    
1065 1065
  };
1066 1066
  
1067 1067
  /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
1068 1068
  /// algorithm.
1069 1069
  ///
1070 1070
  /// \ingroup shortest_path
1071 1071
  /// Function type interface for the \ref BellmanFord "Bellman-Ford"
1072 1072
  /// algorithm.
1073 1073
  ///
1074 1074
  /// This function also has several \ref named-templ-func-param 
1075 1075
  /// "named parameters", they are declared as the members of class 
1076 1076
  /// \ref BellmanFordWizard.
1077 1077
  /// The following examples show how to use these parameters.
1078 1078
  /// \code
1079 1079
  ///   // Compute shortest path from node s to each node
1080 1080
  ///   bellmanFord(g,length).predMap(preds).distMap(dists).run(s);
1081 1081
  ///
1082 1082
  ///   // Compute shortest path from s to t
1083 1083
  ///   bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t);
1084 1084
  /// \endcode
1085 1085
  /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
1086 1086
  /// to the end of the parameter list.
1087 1087
  /// \sa BellmanFordWizard
1088 1088
  /// \sa BellmanFord
1089 1089
  template<typename GR, typename LEN>
1090 1090
  BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
1091 1091
  bellmanFord(const GR& digraph,
1092 1092
	      const LEN& length)
1093 1093
  {
1094 1094
    return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
1095 1095
  }
1096 1096

	
1097 1097
} //END OF NAMESPACE LEMON
1098 1098

	
1099 1099
#endif
1100 1100

	
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-2009
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_BFS_H
20 20
#define LEMON_BFS_H
21 21

	
22 22
///\ingroup search
23 23
///\file
24 24
///\brief BFS 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/maps.h>
31 31
#include <lemon/path.h>
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  ///Default traits class of Bfs class.
36 36

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

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

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

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

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

	
70 70
    ///This function instantiates a \ref ProcessedMap.
71 71
    ///\param g is the digraph, to which
72 72
    ///we would like to define the \ref 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 conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
86 86
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
87 87
    ///Instantiates a \c ReachedMap.
88 88

	
89 89
    ///This function instantiates a \ref ReachedMap.
90 90
    ///\param g is the digraph, to which
91 91
    ///we would like to define the \ref 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 conform to the \ref concepts::WriteMap "WriteMap" concept.
101 101
    typedef typename Digraph::template NodeMap<int> DistMap;
102 102
    ///Instantiates a \c DistMap.
103 103

	
104 104
    ///This function instantiates a \ref DistMap.
105 105
    ///\param g is the digraph, to which we would like to define the
106 106
    ///\ref 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
  ///%BFS algorithm class.
114 114

	
115 115
  ///\ingroup search
116 116
  ///This class provides an efficient implementation of the %BFS algorithm.
117 117
  ///
118 118
  ///There is also a \ref bfs() "function-type interface" for the BFS
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 type is \ref ListDigraph.
124 124
#ifdef DOXYGEN
125 125
  template <typename GR,
126 126
            typename TR>
127 127
#else
128 128
  template <typename GR=ListDigraph,
129 129
            typename TR=BfsDefaultTraits<GR> >
130 130
#endif
131 131
  class Bfs {
132 132
  public:
133 133

	
134 134
    ///The type of the digraph the algorithm runs on.
135 135
    typedef typename TR::Digraph Digraph;
136 136

	
137 137
    ///\brief The type of the map that stores the predecessor arcs of the
138 138
    ///shortest paths.
139 139
    typedef typename TR::PredMap PredMap;
140 140
    ///The type of the map that stores the distances of the nodes.
141 141
    typedef typename TR::DistMap DistMap;
142 142
    ///The type of the map that indicates which nodes are reached.
143 143
    typedef typename TR::ReachedMap ReachedMap;
144 144
    ///The type of the map that indicates which nodes are processed.
145 145
    typedef typename TR::ProcessedMap ProcessedMap;
146 146
    ///The type of the paths.
147 147
    typedef PredMapPath<Digraph, PredMap> Path;
148 148

	
149 149
    ///The \ref BfsDefaultTraits "traits class" of the algorithm.
150 150
    typedef TR Traits;
151 151

	
152 152
  private:
153 153

	
154 154
    typedef typename Digraph::Node Node;
155 155
    typedef typename Digraph::NodeIt NodeIt;
156 156
    typedef typename Digraph::Arc Arc;
157 157
    typedef typename Digraph::OutArcIt OutArcIt;
158 158

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

	
178 178
    std::vector<typename Digraph::Node> _queue;
179 179
    int _queue_head,_queue_tail,_queue_next_dist;
180 180
    int _curr_dist;
181 181

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

	
203 203
  protected:
204 204

	
205 205
    Bfs() {}
206 206

	
207 207
  public:
208 208

	
209 209
    typedef Bfs Create;
210 210

	
211 211
    ///\name Named Template Parameters
212 212

	
213 213
    ///@{
214 214

	
215 215
    template <class T>
216 216
    struct SetPredMapTraits : public Traits {
217 217
      typedef T PredMap;
218 218
      static PredMap *createPredMap(const Digraph &)
219 219
      {
220 220
        LEMON_ASSERT(false, "PredMap is not initialized");
221 221
        return 0; // ignore warnings
222 222
      }
223 223
    };
224 224
    ///\brief \ref named-templ-param "Named parameter" for setting
225 225
    ///\c PredMap type.
226 226
    ///
227 227
    ///\ref named-templ-param "Named parameter" for setting
228 228
    ///\c PredMap type.
229 229
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
230 230
    template <class T>
231 231
    struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
232 232
      typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
233 233
    };
234 234

	
235 235
    template <class T>
236 236
    struct SetDistMapTraits : public Traits {
237 237
      typedef T DistMap;
238 238
      static DistMap *createDistMap(const Digraph &)
239 239
      {
240 240
        LEMON_ASSERT(false, "DistMap is not initialized");
241 241
        return 0; // ignore warnings
242 242
      }
243 243
    };
244 244
    ///\brief \ref named-templ-param "Named parameter" for setting
245 245
    ///\c DistMap type.
246 246
    ///
247 247
    ///\ref named-templ-param "Named parameter" for setting
248 248
    ///\c DistMap type.
249 249
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
250 250
    template <class T>
251 251
    struct SetDistMap : public Bfs< Digraph, SetDistMapTraits<T> > {
252 252
      typedef Bfs< Digraph, SetDistMapTraits<T> > Create;
253 253
    };
254 254

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

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

	
295 295
    struct SetStandardProcessedMapTraits : public Traits {
296 296
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
297 297
      static ProcessedMap *createProcessedMap(const Digraph &g)
298 298
      {
299 299
        return new ProcessedMap(g);
300 300
        return 0; // ignore warnings
301 301
      }
302 302
    };
303 303
    ///\brief \ref named-templ-param "Named parameter" for setting
304 304
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
305 305
    ///
306 306
    ///\ref named-templ-param "Named parameter" for setting
307 307
    ///\c 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 Bfs< Digraph, SetStandardProcessedMapTraits > {
311 311
      typedef Bfs< 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
    Bfs(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
    ~Bfs()
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(Node) "run()"
343 343
    ///or \ref init(), an instance will be allocated automatically.
344 344
    ///The destructor deallocates this automatically allocated map,
345 345
    ///of course.
346 346
    ///\return <tt> (*this) </tt>
347 347
    Bfs &predMap(PredMap &m)
348 348
    {
349 349
      if(local_pred) {
350 350
        delete _pred;
351 351
        local_pred=false;
352 352
      }
353 353
      _pred = &m;
354 354
      return *this;
355 355
    }
356 356

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

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

	
375 375
    ///Sets the map that indicates which nodes are processed.
376 376

	
377 377
    ///Sets the map that indicates which nodes are processed.
378 378
    ///If you don't use this function before calling \ref run(Node) "run()"
379 379
    ///or \ref init(), an instance will be allocated automatically.
380 380
    ///The destructor deallocates this automatically allocated map,
381 381
    ///of course.
382 382
    ///\return <tt> (*this) </tt>
383 383
    Bfs &processedMap(ProcessedMap &m)
384 384
    {
385 385
      if(local_processed) {
386 386
        delete _processed;
387 387
        local_processed=false;
388 388
      }
389 389
      _processed = &m;
390 390
      return *this;
391 391
    }
392 392

	
393 393
    ///Sets the map that stores the distances of the nodes.
394 394

	
395 395
    ///Sets the map that stores the distances of the nodes calculated by
396 396
    ///the algorithm.
397 397
    ///If you don't use this function before calling \ref run(Node) "run()"
398 398
    ///or \ref init(), an instance will be allocated automatically.
399 399
    ///The destructor deallocates this automatically allocated map,
400 400
    ///of course.
401 401
    ///\return <tt> (*this) </tt>
402 402
    Bfs &distMap(DistMap &m)
403 403
    {
404 404
      if(local_dist) {
405 405
        delete _dist;
406 406
        local_dist=false;
407 407
      }
408 408
      _dist = &m;
409 409
      return *this;
410 410
    }
411 411

	
412 412
  public:
413 413

	
414 414
    ///\name Execution Control
415 415
    ///The simplest way to execute the BFS algorithm is to use one of the
416 416
    ///member functions called \ref run(Node) "run()".\n
417 417
    ///If you need better control on the execution, you have to call
418 418
    ///\ref init() first, then you can add several source nodes with
419 419
    ///\ref addSource(). Finally the actual path computation can be
420 420
    ///performed with one of the \ref start() functions.
421 421

	
422 422
    ///@{
423 423

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

	
440 440
    ///Adds a new source node.
441 441

	
442 442
    ///Adds a new source node to the set of nodes to be processed.
443 443
    ///
444 444
    void addSource(Node s)
445 445
    {
446 446
      if(!(*_reached)[s])
447 447
        {
448 448
          _reached->set(s,true);
449 449
          _pred->set(s,INVALID);
450 450
          _dist->set(s,0);
451 451
          _queue[_queue_head++]=s;
452 452
          _queue_next_dist=_queue_head;
453 453
        }
454 454
    }
455 455

	
456 456
    ///Processes the next node.
457 457

	
458 458
    ///Processes the next node.
459 459
    ///
460 460
    ///\return The processed node.
461 461
    ///
462 462
    ///\pre The queue must not be empty.
463 463
    Node processNextNode()
464 464
    {
465 465
      if(_queue_tail==_queue_next_dist) {
466 466
        _curr_dist++;
467 467
        _queue_next_dist=_queue_head;
468 468
      }
469 469
      Node n=_queue[_queue_tail++];
470 470
      _processed->set(n,true);
471 471
      Node m;
472 472
      for(OutArcIt e(*G,n);e!=INVALID;++e)
473 473
        if(!(*_reached)[m=G->target(e)]) {
474 474
          _queue[_queue_head++]=m;
475 475
          _reached->set(m,true);
476 476
          _pred->set(m,e);
477 477
          _dist->set(m,_curr_dist);
478 478
        }
479 479
      return n;
480 480
    }
481 481

	
482 482
    ///Processes the next node.
483 483

	
484 484
    ///Processes the next node and checks if the given target node
485 485
    ///is reached. If the target node is reachable from the processed
486 486
    ///node, then the \c reach parameter will be set to \c true.
487 487
    ///
488 488
    ///\param target The target node.
489 489
    ///\retval reach Indicates if the target node is reached.
490 490
    ///It should be initially \c false.
491 491
    ///
492 492
    ///\return The processed node.
493 493
    ///
494 494
    ///\pre The queue must not be empty.
495 495
    Node processNextNode(Node target, bool& reach)
496 496
    {
497 497
      if(_queue_tail==_queue_next_dist) {
498 498
        _curr_dist++;
499 499
        _queue_next_dist=_queue_head;
500 500
      }
501 501
      Node n=_queue[_queue_tail++];
502 502
      _processed->set(n,true);
503 503
      Node m;
504 504
      for(OutArcIt e(*G,n);e!=INVALID;++e)
505 505
        if(!(*_reached)[m=G->target(e)]) {
506 506
          _queue[_queue_head++]=m;
507 507
          _reached->set(m,true);
508 508
          _pred->set(m,e);
509 509
          _dist->set(m,_curr_dist);
510 510
          reach = reach || (target == m);
511 511
        }
512 512
      return n;
513 513
    }
514 514

	
515 515
    ///Processes the next node.
516 516

	
517 517
    ///Processes the next node and checks if at least one of reached
518 518
    ///nodes has \c true value in the \c nm node map. If one node
519 519
    ///with \c true value is reachable from the processed node, then the
520 520
    ///\c rnode parameter will be set to the first of such nodes.
521 521
    ///
522 522
    ///\param nm A \c bool (or convertible) node map that indicates the
523 523
    ///possible targets.
524 524
    ///\retval rnode The reached target node.
525 525
    ///It should be initially \c INVALID.
526 526
    ///
527 527
    ///\return The processed node.
528 528
    ///
529 529
    ///\pre The queue must not be empty.
530 530
    template<class NM>
531 531
    Node processNextNode(const NM& nm, Node& rnode)
532 532
    {
533 533
      if(_queue_tail==_queue_next_dist) {
534 534
        _curr_dist++;
535 535
        _queue_next_dist=_queue_head;
536 536
      }
537 537
      Node n=_queue[_queue_tail++];
538 538
      _processed->set(n,true);
539 539
      Node m;
540 540
      for(OutArcIt e(*G,n);e!=INVALID;++e)
541 541
        if(!(*_reached)[m=G->target(e)]) {
542 542
          _queue[_queue_head++]=m;
543 543
          _reached->set(m,true);
544 544
          _pred->set(m,e);
545 545
          _dist->set(m,_curr_dist);
546 546
          if (nm[m] && rnode == INVALID) rnode = m;
547 547
        }
548 548
      return n;
549 549
    }
550 550

	
551 551
    ///The next node to be processed.
552 552

	
553 553
    ///Returns the next node to be processed or \c INVALID if the queue
554 554
    ///is empty.
555 555
    Node nextNode() const
556 556
    {
557 557
      return _queue_tail<_queue_head?_queue[_queue_tail]:INVALID;
558 558
    }
559 559

	
560 560
    ///Returns \c false if there are nodes to be processed.
561 561

	
562 562
    ///Returns \c false if there are nodes to be processed
563 563
    ///in the queue.
564 564
    bool emptyQueue() const { return _queue_tail==_queue_head; }
565 565

	
566 566
    ///Returns the number of the nodes to be processed.
567 567

	
568 568
    ///Returns the number of the nodes to be processed
569 569
    ///in the queue.
570 570
    int queueSize() const { return _queue_head-_queue_tail; }
571 571

	
572 572
    ///Executes the algorithm.
573 573

	
574 574
    ///Executes the algorithm.
575 575
    ///
576 576
    ///This method runs the %BFS algorithm from the root node(s)
577 577
    ///in order to compute the shortest path to each node.
578 578
    ///
579 579
    ///The algorithm computes
580 580
    ///- the shortest path tree (forest),
581 581
    ///- the distance of each node from the root(s).
582 582
    ///
583 583
    ///\pre init() must be called and at least one root node should be
584 584
    ///added with addSource() before using this function.
585 585
    ///
586 586
    ///\note <tt>b.start()</tt> is just a shortcut of the following code.
587 587
    ///\code
588 588
    ///  while ( !b.emptyQueue() ) {
589 589
    ///    b.processNextNode();
590 590
    ///  }
591 591
    ///\endcode
592 592
    void start()
593 593
    {
594 594
      while ( !emptyQueue() ) processNextNode();
595 595
    }
596 596

	
597 597
    ///Executes the algorithm until the given target node is reached.
598 598

	
599 599
    ///Executes the algorithm until the given target node is reached.
600 600
    ///
601 601
    ///This method runs the %BFS algorithm from the root node(s)
602 602
    ///in order to compute the shortest path to \c t.
603 603
    ///
604 604
    ///The algorithm computes
605 605
    ///- the shortest path to \c t,
606 606
    ///- the distance of \c t from the root(s).
607 607
    ///
608 608
    ///\pre init() must be called and at least one root node should be
609 609
    ///added with addSource() before using this function.
610 610
    ///
611 611
    ///\note <tt>b.start(t)</tt> is just a shortcut of the following code.
612 612
    ///\code
613 613
    ///  bool reach = false;
614 614
    ///  while ( !b.emptyQueue() && !reach ) {
615 615
    ///    b.processNextNode(t, reach);
616 616
    ///  }
617 617
    ///\endcode
618 618
    void start(Node t)
619 619
    {
620 620
      bool reach = false;
621 621
      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
622 622
    }
623 623

	
624 624
    ///Executes the algorithm until a condition is met.
625 625

	
626 626
    ///Executes the algorithm until a condition is met.
627 627
    ///
628 628
    ///This method runs the %BFS algorithm from the root node(s) in
629 629
    ///order to compute the shortest path to a node \c v with
630 630
    /// <tt>nm[v]</tt> true, if such a node can be found.
631 631
    ///
632 632
    ///\param nm A \c bool (or convertible) node map. The algorithm
633 633
    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
634 634
    ///
635 635
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
636 636
    ///\c INVALID if no such node was found.
637 637
    ///
638 638
    ///\pre init() must be called and at least one root node should be
639 639
    ///added with addSource() before using this function.
640 640
    ///
641 641
    ///\note <tt>b.start(nm)</tt> is just a shortcut of the following code.
642 642
    ///\code
643 643
    ///  Node rnode = INVALID;
644 644
    ///  while ( !b.emptyQueue() && rnode == INVALID ) {
645 645
    ///    b.processNextNode(nm, rnode);
646 646
    ///  }
647 647
    ///  return rnode;
648 648
    ///\endcode
649 649
    template<class NodeBoolMap>
650 650
    Node start(const NodeBoolMap &nm)
651 651
    {
652 652
      Node rnode = INVALID;
653 653
      while ( !emptyQueue() && rnode == INVALID ) {
654 654
        processNextNode(nm, rnode);
655 655
      }
656 656
      return rnode;
657 657
    }
658 658

	
659 659
    ///Runs the algorithm from the given source node.
660 660

	
661 661
    ///This method runs the %BFS algorithm from node \c s
662 662
    ///in order to compute the shortest path to each node.
663 663
    ///
664 664
    ///The algorithm computes
665 665
    ///- the shortest path tree,
666 666
    ///- the distance of each node from the root.
667 667
    ///
668 668
    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
669 669
    ///\code
670 670
    ///  b.init();
671 671
    ///  b.addSource(s);
672 672
    ///  b.start();
673 673
    ///\endcode
674 674
    void run(Node s) {
675 675
      init();
676 676
      addSource(s);
677 677
      start();
678 678
    }
679 679

	
680 680
    ///Finds the shortest path between \c s and \c t.
681 681

	
682 682
    ///This method runs the %BFS algorithm from node \c s
683 683
    ///in order to compute the shortest path to node \c t
684 684
    ///(it stops searching when \c t is processed).
685 685
    ///
686 686
    ///\return \c true if \c t is reachable form \c s.
687 687
    ///
688 688
    ///\note Apart from the return value, <tt>b.run(s,t)</tt> is just a
689 689
    ///shortcut of the following code.
690 690
    ///\code
691 691
    ///  b.init();
692 692
    ///  b.addSource(s);
693 693
    ///  b.start(t);
694 694
    ///\endcode
695 695
    bool run(Node s,Node t) {
696 696
      init();
697 697
      addSource(s);
698 698
      start(t);
699 699
      return reached(t);
700 700
    }
701 701

	
702 702
    ///Runs the algorithm to visit all nodes in the digraph.
703 703

	
704 704
    ///This method runs the %BFS algorithm in order to
705 705
    ///compute the shortest path to each node.
706 706
    ///
707 707
    ///The algorithm computes
708 708
    ///- the shortest path tree (forest),
709 709
    ///- the distance of each node from the root(s).
710 710
    ///
711 711
    ///\note <tt>b.run(s)</tt> is just a shortcut of the following code.
712 712
    ///\code
713 713
    ///  b.init();
714 714
    ///  for (NodeIt n(gr); n != INVALID; ++n) {
715 715
    ///    if (!b.reached(n)) {
716 716
    ///      b.addSource(n);
717 717
    ///      b.start();
718 718
    ///    }
719 719
    ///  }
720 720
    ///\endcode
721 721
    void run() {
722 722
      init();
723 723
      for (NodeIt n(*G); n != INVALID; ++n) {
724 724
        if (!reached(n)) {
725 725
          addSource(n);
726 726
          start();
727 727
        }
728 728
      }
729 729
    }
730 730

	
731 731
    ///@}
732 732

	
733 733
    ///\name Query Functions
734 734
    ///The results of the BFS algorithm can be obtained using these
735 735
    ///functions.\n
736 736
    ///Either \ref run(Node) "run()" or \ref start() should be called
737 737
    ///before using them.
738 738

	
739 739
    ///@{
740 740

	
741 741
    ///The shortest path to the given node.
742 742

	
743 743
    ///Returns the shortest path to the given node from the root(s).
744 744
    ///
745 745
    ///\warning \c t should be reached from the root(s).
746 746
    ///
747 747
    ///\pre Either \ref run(Node) "run()" or \ref init()
748 748
    ///must be called before using this function.
749 749
    Path path(Node t) const { return Path(*G, *_pred, t); }
750 750

	
751 751
    ///The distance of the given node from the root(s).
752 752

	
753 753
    ///Returns the distance of the given node from the root(s).
754 754
    ///
755 755
    ///\warning If node \c v is not reached from the root(s), then
756 756
    ///the return value of this function is undefined.
757 757
    ///
758 758
    ///\pre Either \ref run(Node) "run()" or \ref init()
759 759
    ///must be called before using this function.
760 760
    int dist(Node v) const { return (*_dist)[v]; }
761 761

	
762 762
    ///\brief Returns the 'previous arc' of the shortest path tree for
763 763
    ///the given node.
764 764
    ///
765 765
    ///This function returns the 'previous arc' of the shortest path
766 766
    ///tree for the node \c v, i.e. it returns the last arc of a
767 767
    ///shortest path from a root to \c v. It is \c INVALID if \c v
768 768
    ///is not reached from the root(s) or if \c v is a root.
769 769
    ///
770 770
    ///The shortest path tree used here is equal to the shortest path
771 771
    ///tree used in \ref predNode() and \ref predMap().
772 772
    ///
773 773
    ///\pre Either \ref run(Node) "run()" or \ref init()
774 774
    ///must be called before using this function.
775 775
    Arc predArc(Node v) const { return (*_pred)[v];}
776 776

	
777 777
    ///\brief Returns the 'previous node' of the shortest path tree for
778 778
    ///the given node.
779 779
    ///
780 780
    ///This function returns the 'previous node' of the shortest path
781 781
    ///tree for the node \c v, i.e. it returns the last but one node
782 782
    ///of a shortest path from a root to \c v. It is \c INVALID
783 783
    ///if \c v is not reached from the root(s) or if \c v is a root.
784 784
    ///
785 785
    ///The shortest path tree used here is equal to the shortest path
786 786
    ///tree used in \ref predArc() and \ref predMap().
787 787
    ///
788 788
    ///\pre Either \ref run(Node) "run()" or \ref init()
789 789
    ///must be called before using this function.
790 790
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
791 791
                                  G->source((*_pred)[v]); }
792 792

	
793 793
    ///\brief Returns a const reference to the node map that stores the
794 794
    /// distances of the nodes.
795 795
    ///
796 796
    ///Returns a const reference to the node map that stores the distances
797 797
    ///of the nodes calculated by the algorithm.
798 798
    ///
799 799
    ///\pre Either \ref run(Node) "run()" or \ref init()
800 800
    ///must be called before using this function.
801 801
    const DistMap &distMap() const { return *_dist;}
802 802

	
803 803
    ///\brief Returns a const reference to the node map that stores the
804 804
    ///predecessor arcs.
805 805
    ///
806 806
    ///Returns a const reference to the node map that stores the predecessor
807 807
    ///arcs, which form the shortest path tree (forest).
808 808
    ///
809 809
    ///\pre Either \ref run(Node) "run()" or \ref init()
810 810
    ///must be called before using this function.
811 811
    const PredMap &predMap() const { return *_pred;}
812 812

	
813 813
    ///Checks if the given node is reached from the root(s).
814 814

	
815 815
    ///Returns \c true if \c v is reached from the root(s).
816 816
    ///
817 817
    ///\pre Either \ref run(Node) "run()" or \ref init()
818 818
    ///must be called before using this function.
819 819
    bool reached(Node v) const { return (*_reached)[v]; }
820 820

	
821 821
    ///@}
822 822
  };
823 823

	
824 824
  ///Default traits class of bfs() function.
825 825

	
826 826
  ///Default traits class of bfs() function.
827 827
  ///\tparam GR Digraph type.
828 828
  template<class GR>
829 829
  struct BfsWizardDefaultTraits
830 830
  {
831 831
    ///The type of the digraph the algorithm runs on.
832 832
    typedef GR Digraph;
833 833

	
834 834
    ///\brief The type of the map that stores the predecessor
835 835
    ///arcs of the shortest paths.
836 836
    ///
837 837
    ///The type of the map that stores the predecessor
838 838
    ///arcs of the shortest paths.
839 839
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
840 840
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
841 841
    ///Instantiates a PredMap.
842 842

	
843 843
    ///This function instantiates a PredMap.
844 844
    ///\param g is the digraph, to which we would like to define the
845 845
    ///PredMap.
846 846
    static PredMap *createPredMap(const Digraph &g)
847 847
    {
848 848
      return new PredMap(g);
849 849
    }
850 850

	
851 851
    ///The type of the map that indicates which nodes are processed.
852 852

	
853 853
    ///The type of the map that indicates which nodes are processed.
854 854
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
855
    ///By default it is a NullMap.
855
    ///By default, it is a NullMap.
856 856
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
857 857
    ///Instantiates a ProcessedMap.
858 858

	
859 859
    ///This function instantiates a ProcessedMap.
860 860
    ///\param g is the digraph, to which
861 861
    ///we would like to define the ProcessedMap.
862 862
#ifdef DOXYGEN
863 863
    static ProcessedMap *createProcessedMap(const Digraph &g)
864 864
#else
865 865
    static ProcessedMap *createProcessedMap(const Digraph &)
866 866
#endif
867 867
    {
868 868
      return new ProcessedMap();
869 869
    }
870 870

	
871 871
    ///The type of the map that indicates which nodes are reached.
872 872

	
873 873
    ///The type of the map that indicates which nodes are reached.
874 874
    ///It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
875 875
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
876 876
    ///Instantiates a ReachedMap.
877 877

	
878 878
    ///This function instantiates a ReachedMap.
879 879
    ///\param g is the digraph, to which
880 880
    ///we would like to define the ReachedMap.
881 881
    static ReachedMap *createReachedMap(const Digraph &g)
882 882
    {
883 883
      return new ReachedMap(g);
884 884
    }
885 885

	
886 886
    ///The type of the map that stores the distances of the nodes.
887 887

	
888 888
    ///The type of the map that stores the distances of the nodes.
889 889
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
890 890
    typedef typename Digraph::template NodeMap<int> DistMap;
891 891
    ///Instantiates a DistMap.
892 892

	
893 893
    ///This function instantiates a DistMap.
894 894
    ///\param g is the digraph, to which we would like to define
895 895
    ///the DistMap
896 896
    static DistMap *createDistMap(const Digraph &g)
897 897
    {
898 898
      return new DistMap(g);
899 899
    }
900 900

	
901 901
    ///The type of the shortest paths.
902 902

	
903 903
    ///The type of the shortest paths.
904 904
    ///It must conform to the \ref concepts::Path "Path" concept.
905 905
    typedef lemon::Path<Digraph> Path;
906 906
  };
907 907

	
908 908
  /// Default traits class used by BfsWizard
909 909

	
910 910
  /// Default traits class used by BfsWizard.
911 911
  /// \tparam GR The type of the digraph.
912 912
  template<class GR>
913 913
  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
914 914
  {
915 915

	
916 916
    typedef BfsWizardDefaultTraits<GR> Base;
917 917
  protected:
918 918
    //The type of the nodes in the digraph.
919 919
    typedef typename Base::Digraph::Node Node;
920 920

	
921 921
    //Pointer to the digraph the algorithm runs on.
922 922
    void *_g;
923 923
    //Pointer to the map of reached nodes.
924 924
    void *_reached;
925 925
    //Pointer to the map of processed nodes.
926 926
    void *_processed;
927 927
    //Pointer to the map of predecessors arcs.
928 928
    void *_pred;
929 929
    //Pointer to the map of distances.
930 930
    void *_dist;
931 931
    //Pointer to the shortest path to the target node.
932 932
    void *_path;
933 933
    //Pointer to the distance of the target node.
934 934
    int *_di;
935 935

	
936 936
    public:
937 937
    /// Constructor.
938 938

	
939 939
    /// This constructor does not require parameters, it initiates
940 940
    /// all of the attributes to \c 0.
941 941
    BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
942 942
                      _dist(0), _path(0), _di(0) {}
943 943

	
944 944
    /// Constructor.
945 945

	
946 946
    /// This constructor requires one parameter,
947 947
    /// others are initiated to \c 0.
948 948
    /// \param g The digraph the algorithm runs on.
949 949
    BfsWizardBase(const GR &g) :
950 950
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
951 951
      _reached(0), _processed(0), _pred(0), _dist(0),  _path(0), _di(0) {}
952 952

	
953 953
  };
954 954

	
955 955
  /// Auxiliary class for the function-type interface of BFS algorithm.
956 956

	
957 957
  /// This auxiliary class is created to implement the
958 958
  /// \ref bfs() "function-type interface" of \ref Bfs algorithm.
959 959
  /// It does not have own \ref run(Node) "run()" method, it uses the
960 960
  /// functions and features of the plain \ref Bfs.
961 961
  ///
962 962
  /// This class should only be used through the \ref bfs() function,
963 963
  /// which makes it easier to use the algorithm.
964 964
  template<class TR>
965 965
  class BfsWizard : public TR
966 966
  {
967 967
    typedef TR Base;
968 968

	
969 969
    typedef typename TR::Digraph Digraph;
970 970

	
971 971
    typedef typename Digraph::Node Node;
972 972
    typedef typename Digraph::NodeIt NodeIt;
973 973
    typedef typename Digraph::Arc Arc;
974 974
    typedef typename Digraph::OutArcIt OutArcIt;
975 975

	
976 976
    typedef typename TR::PredMap PredMap;
977 977
    typedef typename TR::DistMap DistMap;
978 978
    typedef typename TR::ReachedMap ReachedMap;
979 979
    typedef typename TR::ProcessedMap ProcessedMap;
980 980
    typedef typename TR::Path Path;
981 981

	
982 982
  public:
983 983

	
984 984
    /// Constructor.
985 985
    BfsWizard() : TR() {}
986 986

	
987 987
    /// Constructor that requires parameters.
988 988

	
989 989
    /// Constructor that requires parameters.
990 990
    /// These parameters will be the default values for the traits class.
991 991
    /// \param g The digraph the algorithm runs on.
992 992
    BfsWizard(const Digraph &g) :
993 993
      TR(g) {}
994 994

	
995 995
    ///Copy constructor
996 996
    BfsWizard(const TR &b) : TR(b) {}
997 997

	
998 998
    ~BfsWizard() {}
999 999

	
1000 1000
    ///Runs BFS algorithm from the given source node.
1001 1001

	
1002 1002
    ///This method runs BFS algorithm from node \c s
1003 1003
    ///in order to compute the shortest path to each node.
1004 1004
    void run(Node s)
1005 1005
    {
1006 1006
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1007 1007
      if (Base::_pred)
1008 1008
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1009 1009
      if (Base::_dist)
1010 1010
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1011 1011
      if (Base::_reached)
1012 1012
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1013 1013
      if (Base::_processed)
1014 1014
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1015 1015
      if (s!=INVALID)
1016 1016
        alg.run(s);
1017 1017
      else
1018 1018
        alg.run();
1019 1019
    }
1020 1020

	
1021 1021
    ///Finds the shortest path between \c s and \c t.
1022 1022

	
1023 1023
    ///This method runs BFS algorithm from node \c s
1024 1024
    ///in order to compute the shortest path to node \c t
1025 1025
    ///(it stops searching when \c t is processed).
1026 1026
    ///
1027 1027
    ///\return \c true if \c t is reachable form \c s.
1028 1028
    bool run(Node s, Node t)
1029 1029
    {
1030 1030
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
1031 1031
      if (Base::_pred)
1032 1032
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1033 1033
      if (Base::_dist)
1034 1034
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1035 1035
      if (Base::_reached)
1036 1036
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
1037 1037
      if (Base::_processed)
1038 1038
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1039 1039
      alg.run(s,t);
1040 1040
      if (Base::_path)
1041 1041
        *reinterpret_cast<Path*>(Base::_path) = alg.path(t);
1042 1042
      if (Base::_di)
1043 1043
        *Base::_di = alg.dist(t);
1044 1044
      return alg.reached(t);
1045 1045
    }
1046 1046

	
1047 1047
    ///Runs BFS algorithm to visit all nodes in the digraph.
1048 1048

	
1049 1049
    ///This method runs BFS algorithm in order to compute
1050 1050
    ///the shortest path to each node.
1051 1051
    void run()
1052 1052
    {
1053 1053
      run(INVALID);
1054 1054
    }
1055 1055

	
1056 1056
    template<class T>
1057 1057
    struct SetPredMapBase : public Base {
1058 1058
      typedef T PredMap;
1059 1059
      static PredMap *createPredMap(const Digraph &) { return 0; };
1060 1060
      SetPredMapBase(const TR &b) : TR(b) {}
1061 1061
    };
1062 1062

	
1063 1063
    ///\brief \ref named-templ-param "Named parameter" for setting
1064 1064
    ///the predecessor map.
1065 1065
    ///
1066 1066
    ///\ref named-templ-param "Named parameter" function for setting
1067 1067
    ///the map that stores the predecessor arcs of the nodes.
1068 1068
    template<class T>
1069 1069
    BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1070 1070
    {
1071 1071
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1072 1072
      return BfsWizard<SetPredMapBase<T> >(*this);
1073 1073
    }
1074 1074

	
1075 1075
    template<class T>
1076 1076
    struct SetReachedMapBase : public Base {
1077 1077
      typedef T ReachedMap;
1078 1078
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1079 1079
      SetReachedMapBase(const TR &b) : TR(b) {}
1080 1080
    };
1081 1081

	
1082 1082
    ///\brief \ref named-templ-param "Named parameter" for setting
1083 1083
    ///the reached map.
1084 1084
    ///
1085 1085
    ///\ref named-templ-param "Named parameter" function for setting
1086 1086
    ///the map that indicates which nodes are reached.
1087 1087
    template<class T>
1088 1088
    BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1089 1089
    {
1090 1090
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1091 1091
      return BfsWizard<SetReachedMapBase<T> >(*this);
1092 1092
    }
1093 1093

	
1094 1094
    template<class T>
1095 1095
    struct SetDistMapBase : public Base {
1096 1096
      typedef T DistMap;
1097 1097
      static DistMap *createDistMap(const Digraph &) { return 0; };
1098 1098
      SetDistMapBase(const TR &b) : TR(b) {}
1099 1099
    };
1100 1100

	
1101 1101
    ///\brief \ref named-templ-param "Named parameter" for setting
1102 1102
    ///the distance map.
1103 1103
    ///
1104 1104
    ///\ref named-templ-param "Named parameter" function for setting
1105 1105
    ///the map that stores the distances of the nodes calculated
1106 1106
    ///by the algorithm.
1107 1107
    template<class T>
1108 1108
    BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1109 1109
    {
1110 1110
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1111 1111
      return BfsWizard<SetDistMapBase<T> >(*this);
1112 1112
    }
1113 1113

	
1114 1114
    template<class T>
1115 1115
    struct SetProcessedMapBase : public Base {
1116 1116
      typedef T ProcessedMap;
1117 1117
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1118 1118
      SetProcessedMapBase(const TR &b) : TR(b) {}
1119 1119
    };
1120 1120

	
1121 1121
    ///\brief \ref named-func-param "Named parameter" for setting
1122 1122
    ///the processed map.
1123 1123
    ///
1124 1124
    ///\ref named-templ-param "Named parameter" function for setting
1125 1125
    ///the map that indicates which nodes are processed.
1126 1126
    template<class T>
1127 1127
    BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1128 1128
    {
1129 1129
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1130 1130
      return BfsWizard<SetProcessedMapBase<T> >(*this);
1131 1131
    }
1132 1132

	
1133 1133
    template<class T>
1134 1134
    struct SetPathBase : public Base {
1135 1135
      typedef T Path;
1136 1136
      SetPathBase(const TR &b) : TR(b) {}
1137 1137
    };
1138 1138
    ///\brief \ref named-func-param "Named parameter"
1139 1139
    ///for getting the shortest path to the target node.
1140 1140
    ///
1141 1141
    ///\ref named-func-param "Named parameter"
1142 1142
    ///for getting the shortest path to the target node.
1143 1143
    template<class T>
1144 1144
    BfsWizard<SetPathBase<T> > path(const T &t)
1145 1145
    {
1146 1146
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1147 1147
      return BfsWizard<SetPathBase<T> >(*this);
1148 1148
    }
1149 1149

	
1150 1150
    ///\brief \ref named-func-param "Named parameter"
1151 1151
    ///for getting the distance of the target node.
1152 1152
    ///
1153 1153
    ///\ref named-func-param "Named parameter"
1154 1154
    ///for getting the distance of the target node.
1155 1155
    BfsWizard dist(const int &d)
1156 1156
    {
1157 1157
      Base::_di=const_cast<int*>(&d);
1158 1158
      return *this;
1159 1159
    }
1160 1160

	
1161 1161
  };
1162 1162

	
1163 1163
  ///Function-type interface for BFS algorithm.
1164 1164

	
1165 1165
  /// \ingroup search
1166 1166
  ///Function-type interface for BFS algorithm.
1167 1167
  ///
1168 1168
  ///This function also has several \ref named-func-param "named parameters",
1169 1169
  ///they are declared as the members of class \ref BfsWizard.
1170 1170
  ///The following examples show how to use these parameters.
1171 1171
  ///\code
1172 1172
  ///  // Compute shortest path from node s to each node
1173 1173
  ///  bfs(g).predMap(preds).distMap(dists).run(s);
1174 1174
  ///
1175 1175
  ///  // Compute shortest path from s to t
1176 1176
  ///  bool reached = bfs(g).path(p).dist(d).run(s,t);
1177 1177
  ///\endcode
1178 1178
  ///\warning Don't forget to put the \ref BfsWizard::run(Node) "run()"
1179 1179
  ///to the end of the parameter list.
1180 1180
  ///\sa BfsWizard
1181 1181
  ///\sa Bfs
1182 1182
  template<class GR>
1183 1183
  BfsWizard<BfsWizardBase<GR> >
1184 1184
  bfs(const GR &digraph)
1185 1185
  {
1186 1186
    return BfsWizard<BfsWizardBase<GR> >(digraph);
1187 1187
  }
1188 1188

	
1189 1189
#ifdef DOXYGEN
1190 1190
  /// \brief Visitor class for BFS.
1191 1191
  ///
1192 1192
  /// This class defines the interface of the BfsVisit events, and
1193 1193
  /// it could be the base of a real visitor class.
1194 1194
  template <typename GR>
1195 1195
  struct BfsVisitor {
1196 1196
    typedef GR Digraph;
1197 1197
    typedef typename Digraph::Arc Arc;
1198 1198
    typedef typename Digraph::Node Node;
1199 1199
    /// \brief Called for the source node(s) of the BFS.
1200 1200
    ///
1201 1201
    /// This function is called for the source node(s) of the BFS.
1202 1202
    void start(const Node& node) {}
1203 1203
    /// \brief Called when a node is reached first time.
1204 1204
    ///
1205 1205
    /// This function is called when a node is reached first time.
1206 1206
    void reach(const Node& node) {}
1207 1207
    /// \brief Called when a node is processed.
1208 1208
    ///
1209 1209
    /// This function is called when a node is processed.
1210 1210
    void process(const Node& node) {}
1211 1211
    /// \brief Called when an arc reaches a new node.
1212 1212
    ///
1213 1213
    /// This function is called when the BFS finds an arc whose target node
1214 1214
    /// is not reached yet.
1215 1215
    void discover(const Arc& arc) {}
1216 1216
    /// \brief Called when an arc is examined but its target node is
1217 1217
    /// already discovered.
1218 1218
    ///
1219 1219
    /// This function is called when an arc is examined but its target node is
1220 1220
    /// already discovered.
1221 1221
    void examine(const Arc& arc) {}
1222 1222
  };
1223 1223
#else
1224 1224
  template <typename GR>
1225 1225
  struct BfsVisitor {
1226 1226
    typedef GR Digraph;
1227 1227
    typedef typename Digraph::Arc Arc;
1228 1228
    typedef typename Digraph::Node Node;
1229 1229
    void start(const Node&) {}
1230 1230
    void reach(const Node&) {}
1231 1231
    void process(const Node&) {}
1232 1232
    void discover(const Arc&) {}
1233 1233
    void examine(const Arc&) {}
1234 1234

	
1235 1235
    template <typename _Visitor>
1236 1236
    struct Constraints {
1237 1237
      void constraints() {
1238 1238
        Arc arc;
1239 1239
        Node node;
1240 1240
        visitor.start(node);
1241 1241
        visitor.reach(node);
1242 1242
        visitor.process(node);
1243 1243
        visitor.discover(arc);
1244 1244
        visitor.examine(arc);
1245 1245
      }
1246 1246
      _Visitor& visitor;
1247 1247
    };
1248 1248
  };
1249 1249
#endif
1250 1250

	
1251 1251
  /// \brief Default traits class of BfsVisit class.
1252 1252
  ///
1253 1253
  /// Default traits class of BfsVisit class.
1254 1254
  /// \tparam GR The type of the digraph the algorithm runs on.
1255 1255
  template<class GR>
1256 1256
  struct BfsVisitDefaultTraits {
1257 1257

	
1258 1258
    /// \brief The type of the digraph the algorithm runs on.
1259 1259
    typedef GR Digraph;
1260 1260

	
1261 1261
    /// \brief The type of the map that indicates which nodes are reached.
1262 1262
    ///
1263 1263
    /// The type of the map that indicates which nodes are reached.
1264 1264
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
1265 1265
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1266 1266

	
1267 1267
    /// \brief Instantiates a ReachedMap.
1268 1268
    ///
1269 1269
    /// This function instantiates a ReachedMap.
1270 1270
    /// \param digraph is the digraph, to which
1271 1271
    /// we would like to define the ReachedMap.
1272 1272
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1273 1273
      return new ReachedMap(digraph);
1274 1274
    }
1275 1275

	
1276 1276
  };
1277 1277

	
1278 1278
  /// \ingroup search
1279 1279
  ///
1280 1280
  /// \brief BFS algorithm class with visitor interface.
1281 1281
  ///
1282 1282
  /// This class provides an efficient implementation of the BFS algorithm
1283 1283
  /// with visitor interface.
1284 1284
  ///
1285 1285
  /// The BfsVisit class provides an alternative interface to the Bfs
1286 1286
  /// class. It works with callback mechanism, the BfsVisit object calls
1287 1287
  /// the member functions of the \c Visitor class on every BFS event.
1288 1288
  ///
1289 1289
  /// This interface of the BFS algorithm should be used in special cases
1290 1290
  /// when extra actions have to be performed in connection with certain
1291 1291
  /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1292 1292
  /// instead.
1293 1293
  ///
1294 1294
  /// \tparam GR The type of the digraph the algorithm runs on.
1295 1295
  /// The default type is \ref ListDigraph.
1296 1296
  /// The value of GR is not used directly by \ref BfsVisit,
1297 1297
  /// it is only passed to \ref BfsVisitDefaultTraits.
1298 1298
  /// \tparam VS The Visitor type that is used by the algorithm.
1299 1299
  /// \ref BfsVisitor "BfsVisitor<GR>" is an empty visitor, which
1300 1300
  /// does not observe the BFS events. If you want to observe the BFS
1301 1301
  /// events, you should implement your own visitor class.
1302 1302
  /// \tparam TR Traits class to set various data types used by the
1303 1303
  /// algorithm. The default traits class is
1304 1304
  /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<GR>".
1305 1305
  /// See \ref BfsVisitDefaultTraits for the documentation of
1306 1306
  /// a BFS visit traits class.
1307 1307
#ifdef DOXYGEN
1308 1308
  template <typename GR, typename VS, typename TR>
1309 1309
#else
1310 1310
  template <typename GR = ListDigraph,
1311 1311
            typename VS = BfsVisitor<GR>,
1312 1312
            typename TR = BfsVisitDefaultTraits<GR> >
1313 1313
#endif
1314 1314
  class BfsVisit {
1315 1315
  public:
1316 1316

	
1317 1317
    ///The traits class.
1318 1318
    typedef TR Traits;
1319 1319

	
1320 1320
    ///The type of the digraph the algorithm runs on.
1321 1321
    typedef typename Traits::Digraph Digraph;
1322 1322

	
1323 1323
    ///The visitor type used by the algorithm.
1324 1324
    typedef VS Visitor;
1325 1325

	
1326 1326
    ///The type of the map that indicates which nodes are reached.
1327 1327
    typedef typename Traits::ReachedMap ReachedMap;
1328 1328

	
1329 1329
  private:
1330 1330

	
1331 1331
    typedef typename Digraph::Node Node;
1332 1332
    typedef typename Digraph::NodeIt NodeIt;
1333 1333
    typedef typename Digraph::Arc Arc;
1334 1334
    typedef typename Digraph::OutArcIt OutArcIt;
1335 1335

	
1336 1336
    //Pointer to the underlying digraph.
1337 1337
    const Digraph *_digraph;
1338 1338
    //Pointer to the visitor object.
1339 1339
    Visitor *_visitor;
1340 1340
    //Pointer to the map of reached status of the nodes.
1341 1341
    ReachedMap *_reached;
1342 1342
    //Indicates if _reached is locally allocated (true) or not.
1343 1343
    bool local_reached;
1344 1344

	
1345 1345
    std::vector<typename Digraph::Node> _list;
1346 1346
    int _list_front, _list_back;
1347 1347

	
1348 1348
    //Creates the maps if necessary.
1349 1349
    void create_maps() {
1350 1350
      if(!_reached) {
1351 1351
        local_reached = true;
1352 1352
        _reached = Traits::createReachedMap(*_digraph);
1353 1353
      }
1354 1354
    }
1355 1355

	
1356 1356
  protected:
1357 1357

	
1358 1358
    BfsVisit() {}
1359 1359

	
1360 1360
  public:
1361 1361

	
1362 1362
    typedef BfsVisit Create;
1363 1363

	
1364 1364
    /// \name Named Template Parameters
1365 1365

	
1366 1366
    ///@{
1367 1367
    template <class T>
1368 1368
    struct SetReachedMapTraits : public Traits {
1369 1369
      typedef T ReachedMap;
1370 1370
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1371 1371
        LEMON_ASSERT(false, "ReachedMap is not initialized");
1372 1372
        return 0; // ignore warnings
1373 1373
      }
1374 1374
    };
1375 1375
    /// \brief \ref named-templ-param "Named parameter" for setting
1376 1376
    /// ReachedMap type.
1377 1377
    ///
1378 1378
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type.
1379 1379
    template <class T>
1380 1380
    struct SetReachedMap : public BfsVisit< Digraph, Visitor,
1381 1381
                                            SetReachedMapTraits<T> > {
1382 1382
      typedef BfsVisit< Digraph, Visitor, SetReachedMapTraits<T> > Create;
1383 1383
    };
1384 1384
    ///@}
1385 1385

	
1386 1386
  public:
1387 1387

	
1388 1388
    /// \brief Constructor.
1389 1389
    ///
1390 1390
    /// Constructor.
1391 1391
    ///
1392 1392
    /// \param digraph The digraph the algorithm runs on.
1393 1393
    /// \param visitor The visitor object of the algorithm.
1394 1394
    BfsVisit(const Digraph& digraph, Visitor& visitor)
1395 1395
      : _digraph(&digraph), _visitor(&visitor),
1396 1396
        _reached(0), local_reached(false) {}
1397 1397

	
1398 1398
    /// \brief Destructor.
1399 1399
    ~BfsVisit() {
1400 1400
      if(local_reached) delete _reached;
1401 1401
    }
1402 1402

	
1403 1403
    /// \brief Sets the map that indicates which nodes are reached.
1404 1404
    ///
1405 1405
    /// Sets the map that indicates which nodes are reached.
1406 1406
    /// If you don't use this function before calling \ref run(Node) "run()"
1407 1407
    /// or \ref init(), an instance will be allocated automatically.
1408 1408
    /// The destructor deallocates this automatically allocated map,
1409 1409
    /// of course.
1410 1410
    /// \return <tt> (*this) </tt>
1411 1411
    BfsVisit &reachedMap(ReachedMap &m) {
1412 1412
      if(local_reached) {
1413 1413
        delete _reached;
1414 1414
        local_reached = false;
1415 1415
      }
1416 1416
      _reached = &m;
1417 1417
      return *this;
1418 1418
    }
1419 1419

	
1420 1420
  public:
1421 1421

	
1422 1422
    /// \name Execution Control
1423 1423
    /// The simplest way to execute the BFS algorithm is to use one of the
1424 1424
    /// member functions called \ref run(Node) "run()".\n
1425 1425
    /// If you need better control on the execution, you have to call
1426 1426
    /// \ref init() first, then you can add several source nodes with
1427 1427
    /// \ref addSource(). Finally the actual path computation can be
1428 1428
    /// performed with one of the \ref start() functions.
1429 1429

	
1430 1430
    /// @{
1431 1431

	
1432 1432
    /// \brief Initializes the internal data structures.
1433 1433
    ///
1434 1434
    /// Initializes the internal data structures.
1435 1435
    void init() {
1436 1436
      create_maps();
1437 1437
      _list.resize(countNodes(*_digraph));
1438 1438
      _list_front = _list_back = -1;
1439 1439
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1440 1440
        _reached->set(u, false);
1441 1441
      }
1442 1442
    }
1443 1443

	
1444 1444
    /// \brief Adds a new source node.
1445 1445
    ///
1446 1446
    /// Adds a new source node to the set of nodes to be processed.
1447 1447
    void addSource(Node s) {
1448 1448
      if(!(*_reached)[s]) {
1449 1449
          _reached->set(s,true);
1450 1450
          _visitor->start(s);
1451 1451
          _visitor->reach(s);
1452 1452
          _list[++_list_back] = s;
1453 1453
        }
1454 1454
    }
1455 1455

	
1456 1456
    /// \brief Processes the next node.
1457 1457
    ///
1458 1458
    /// Processes the next node.
1459 1459
    ///
1460 1460
    /// \return The processed node.
1461 1461
    ///
1462 1462
    /// \pre The queue must not be empty.
1463 1463
    Node processNextNode() {
1464 1464
      Node n = _list[++_list_front];
1465 1465
      _visitor->process(n);
1466 1466
      Arc e;
1467 1467
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1468 1468
        Node m = _digraph->target(e);
1469 1469
        if (!(*_reached)[m]) {
1470 1470
          _visitor->discover(e);
1471 1471
          _visitor->reach(m);
1472 1472
          _reached->set(m, true);
1473 1473
          _list[++_list_back] = m;
1474 1474
        } else {
1475 1475
          _visitor->examine(e);
1476 1476
        }
1477 1477
      }
1478 1478
      return n;
1479 1479
    }
1480 1480

	
1481 1481
    /// \brief Processes the next node.
1482 1482
    ///
1483 1483
    /// Processes the next node and checks if the given target node
1484 1484
    /// is reached. If the target node is reachable from the processed
1485 1485
    /// node, then the \c reach parameter will be set to \c true.
1486 1486
    ///
1487 1487
    /// \param target The target node.
1488 1488
    /// \retval reach Indicates if the target node is reached.
1489 1489
    /// It should be initially \c false.
1490 1490
    ///
1491 1491
    /// \return The processed node.
1492 1492
    ///
1493 1493
    /// \pre The queue must not be empty.
1494 1494
    Node processNextNode(Node target, bool& reach) {
1495 1495
      Node n = _list[++_list_front];
1496 1496
      _visitor->process(n);
1497 1497
      Arc e;
1498 1498
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1499 1499
        Node m = _digraph->target(e);
1500 1500
        if (!(*_reached)[m]) {
1501 1501
          _visitor->discover(e);
1502 1502
          _visitor->reach(m);
1503 1503
          _reached->set(m, true);
1504 1504
          _list[++_list_back] = m;
1505 1505
          reach = reach || (target == m);
1506 1506
        } else {
1507 1507
          _visitor->examine(e);
1508 1508
        }
1509 1509
      }
1510 1510
      return n;
1511 1511
    }
1512 1512

	
1513 1513
    /// \brief Processes the next node.
1514 1514
    ///
1515 1515
    /// Processes the next node and checks if at least one of reached
1516 1516
    /// nodes has \c true value in the \c nm node map. If one node
1517 1517
    /// with \c true value is reachable from the processed node, then the
1518 1518
    /// \c rnode parameter will be set to the first of such nodes.
1519 1519
    ///
1520 1520
    /// \param nm A \c bool (or convertible) node map that indicates the
1521 1521
    /// possible targets.
1522 1522
    /// \retval rnode The reached target node.
1523 1523
    /// It should be initially \c INVALID.
1524 1524
    ///
1525 1525
    /// \return The processed node.
1526 1526
    ///
1527 1527
    /// \pre The queue must not be empty.
1528 1528
    template <typename NM>
1529 1529
    Node processNextNode(const NM& nm, Node& rnode) {
1530 1530
      Node n = _list[++_list_front];
1531 1531
      _visitor->process(n);
1532 1532
      Arc e;
1533 1533
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1534 1534
        Node m = _digraph->target(e);
1535 1535
        if (!(*_reached)[m]) {
1536 1536
          _visitor->discover(e);
1537 1537
          _visitor->reach(m);
1538 1538
          _reached->set(m, true);
1539 1539
          _list[++_list_back] = m;
1540 1540
          if (nm[m] && rnode == INVALID) rnode = m;
1541 1541
        } else {
1542 1542
          _visitor->examine(e);
1543 1543
        }
1544 1544
      }
1545 1545
      return n;
1546 1546
    }
1547 1547

	
1548 1548
    /// \brief The next node to be processed.
1549 1549
    ///
1550 1550
    /// Returns the next node to be processed or \c INVALID if the queue
1551 1551
    /// is empty.
1552 1552
    Node nextNode() const {
1553 1553
      return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1554 1554
    }
1555 1555

	
1556 1556
    /// \brief Returns \c false if there are nodes
1557 1557
    /// to be processed.
1558 1558
    ///
1559 1559
    /// Returns \c false if there are nodes
1560 1560
    /// to be processed in the queue.
1561 1561
    bool emptyQueue() const { return _list_front == _list_back; }
1562 1562

	
1563 1563
    /// \brief Returns the number of the nodes to be processed.
1564 1564
    ///
1565 1565
    /// Returns the number of the nodes to be processed in the queue.
1566 1566
    int queueSize() const { return _list_back - _list_front; }
1567 1567

	
1568 1568
    /// \brief Executes the algorithm.
1569 1569
    ///
1570 1570
    /// Executes the algorithm.
1571 1571
    ///
1572 1572
    /// This method runs the %BFS algorithm from the root node(s)
1573 1573
    /// in order to compute the shortest path to each node.
1574 1574
    ///
1575 1575
    /// The algorithm computes
1576 1576
    /// - the shortest path tree (forest),
1577 1577
    /// - the distance of each node from the root(s).
1578 1578
    ///
1579 1579
    /// \pre init() must be called and at least one root node should be added
1580 1580
    /// with addSource() before using this function.
1581 1581
    ///
1582 1582
    /// \note <tt>b.start()</tt> is just a shortcut of the following code.
1583 1583
    /// \code
1584 1584
    ///   while ( !b.emptyQueue() ) {
1585 1585
    ///     b.processNextNode();
1586 1586
    ///   }
1587 1587
    /// \endcode
1588 1588
    void start() {
1589 1589
      while ( !emptyQueue() ) processNextNode();
1590 1590
    }
1591 1591

	
1592 1592
    /// \brief Executes the algorithm until the given target node is reached.
1593 1593
    ///
1594 1594
    /// Executes the algorithm until the given target node is reached.
1595 1595
    ///
1596 1596
    /// This method runs the %BFS algorithm from the root node(s)
1597 1597
    /// in order to compute the shortest path to \c t.
1598 1598
    ///
1599 1599
    /// The algorithm computes
1600 1600
    /// - the shortest path to \c t,
1601 1601
    /// - the distance of \c t from the root(s).
1602 1602
    ///
1603 1603
    /// \pre init() must be called and at least one root node should be
1604 1604
    /// added with addSource() before using this function.
1605 1605
    ///
1606 1606
    /// \note <tt>b.start(t)</tt> is just a shortcut of the following code.
1607 1607
    /// \code
1608 1608
    ///   bool reach = false;
1609 1609
    ///   while ( !b.emptyQueue() && !reach ) {
1610 1610
    ///     b.processNextNode(t, reach);
1611 1611
    ///   }
1612 1612
    /// \endcode
1613 1613
    void start(Node t) {
1614 1614
      bool reach = false;
1615 1615
      while ( !emptyQueue() && !reach ) processNextNode(t, reach);
1616 1616
    }
1617 1617

	
1618 1618
    /// \brief Executes the algorithm until a condition is met.
1619 1619
    ///
1620 1620
    /// Executes the algorithm until a condition is met.
1621 1621
    ///
1622 1622
    /// This method runs the %BFS algorithm from the root node(s) in
1623 1623
    /// order to compute the shortest path to a node \c v with
1624 1624
    /// <tt>nm[v]</tt> true, if such a node can be found.
1625 1625
    ///
1626 1626
    /// \param nm must be a bool (or convertible) node map. The
1627 1627
    /// algorithm will stop when it reaches a node \c v with
1628 1628
    /// <tt>nm[v]</tt> true.
1629 1629
    ///
1630 1630
    /// \return The reached node \c v with <tt>nm[v]</tt> true or
1631 1631
    /// \c INVALID if no such node was found.
1632 1632
    ///
1633 1633
    /// \pre init() must be called and at least one root node should be
1634 1634
    /// added with addSource() before using this function.
1635 1635
    ///
1636 1636
    /// \note <tt>b.start(nm)</tt> is just a shortcut of the following code.
1637 1637
    /// \code
1638 1638
    ///   Node rnode = INVALID;
1639 1639
    ///   while ( !b.emptyQueue() && rnode == INVALID ) {
1640 1640
    ///     b.processNextNode(nm, rnode);
1641 1641
    ///   }
1642 1642
    ///   return rnode;
1643 1643
    /// \endcode
1644 1644
    template <typename NM>
1645 1645
    Node start(const NM &nm) {
1646 1646
      Node rnode = INVALID;
1647 1647
      while ( !emptyQueue() && rnode == INVALID ) {
1648 1648
        processNextNode(nm, rnode);
1649 1649
      }
1650 1650
      return rnode;
1651 1651
    }
1652 1652

	
1653 1653
    /// \brief Runs the algorithm from the given source node.
1654 1654
    ///
1655 1655
    /// This method runs the %BFS algorithm from node \c s
1656 1656
    /// in order to compute the shortest path to each node.
1657 1657
    ///
1658 1658
    /// The algorithm computes
1659 1659
    /// - the shortest path tree,
1660 1660
    /// - the distance of each node from the root.
1661 1661
    ///
1662 1662
    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1663 1663
    ///\code
1664 1664
    ///   b.init();
1665 1665
    ///   b.addSource(s);
1666 1666
    ///   b.start();
1667 1667
    ///\endcode
1668 1668
    void run(Node s) {
1669 1669
      init();
1670 1670
      addSource(s);
1671 1671
      start();
1672 1672
    }
1673 1673

	
1674 1674
    /// \brief Finds the shortest path between \c s and \c t.
1675 1675
    ///
1676 1676
    /// This method runs the %BFS algorithm from node \c s
1677 1677
    /// in order to compute the shortest path to node \c t
1678 1678
    /// (it stops searching when \c t is processed).
1679 1679
    ///
1680 1680
    /// \return \c true if \c t is reachable form \c s.
1681 1681
    ///
1682 1682
    /// \note Apart from the return value, <tt>b.run(s,t)</tt> is just a
1683 1683
    /// shortcut of the following code.
1684 1684
    ///\code
1685 1685
    ///   b.init();
1686 1686
    ///   b.addSource(s);
1687 1687
    ///   b.start(t);
1688 1688
    ///\endcode
1689 1689
    bool run(Node s,Node t) {
1690 1690
      init();
1691 1691
      addSource(s);
1692 1692
      start(t);
1693 1693
      return reached(t);
1694 1694
    }
1695 1695

	
1696 1696
    /// \brief Runs the algorithm to visit all nodes in the digraph.
1697 1697
    ///
1698 1698
    /// This method runs the %BFS algorithm in order to
1699 1699
    /// compute the shortest path to each node.
1700 1700
    ///
1701 1701
    /// The algorithm computes
1702 1702
    /// - the shortest path tree (forest),
1703 1703
    /// - the distance of each node from the root(s).
1704 1704
    ///
1705 1705
    /// \note <tt>b.run(s)</tt> is just a shortcut of the following code.
1706 1706
    ///\code
1707 1707
    ///  b.init();
1708 1708
    ///  for (NodeIt n(gr); n != INVALID; ++n) {
1709 1709
    ///    if (!b.reached(n)) {
1710 1710
    ///      b.addSource(n);
1711 1711
    ///      b.start();
1712 1712
    ///    }
1713 1713
    ///  }
1714 1714
    ///\endcode
1715 1715
    void run() {
1716 1716
      init();
1717 1717
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1718 1718
        if (!reached(it)) {
1719 1719
          addSource(it);
1720 1720
          start();
1721 1721
        }
1722 1722
      }
1723 1723
    }
1724 1724

	
1725 1725
    ///@}
1726 1726

	
1727 1727
    /// \name Query Functions
1728 1728
    /// The results of the BFS algorithm can be obtained using these
1729 1729
    /// functions.\n
1730 1730
    /// Either \ref run(Node) "run()" or \ref start() should be called
1731 1731
    /// before using them.
1732 1732

	
1733 1733
    ///@{
1734 1734

	
1735 1735
    /// \brief Checks if the given node is reached from the root(s).
1736 1736
    ///
1737 1737
    /// Returns \c true if \c v is reached from the root(s).
1738 1738
    ///
1739 1739
    /// \pre Either \ref run(Node) "run()" or \ref init()
1740 1740
    /// must be called before using this function.
1741 1741
    bool reached(Node v) const { return (*_reached)[v]; }
1742 1742

	
1743 1743
    ///@}
1744 1744

	
1745 1745
  };
1746 1746

	
1747 1747
} //END OF NAMESPACE LEMON
1748 1748

	
1749 1749
#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-2009
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_CIRCULATION_H
20 20
#define LEMON_CIRCULATION_H
21 21

	
22 22
#include <lemon/tolerance.h>
23 23
#include <lemon/elevator.h>
24 24
#include <limits>
25 25

	
26 26
///\ingroup max_flow
27 27
///\file
28 28
///\brief Push-relabel algorithm for finding a feasible circulation.
29 29
///
30 30
namespace lemon {
31 31

	
32 32
  /// \brief Default traits class of Circulation class.
33 33
  ///
34 34
  /// Default traits class of Circulation class.
35 35
  ///
36 36
  /// \tparam GR Type of the digraph the algorithm runs on.
37 37
  /// \tparam LM The type of the lower bound map.
38 38
  /// \tparam UM The type of the upper bound (capacity) map.
39 39
  /// \tparam SM The type of the supply map.
40 40
  template <typename GR, typename LM,
41 41
            typename UM, typename SM>
42 42
  struct CirculationDefaultTraits {
43 43

	
44 44
    /// \brief The type of the digraph the algorithm runs on.
45 45
    typedef GR Digraph;
46 46

	
47 47
    /// \brief The type of the lower bound map.
48 48
    ///
49 49
    /// The type of the map that stores the lower bounds on the arcs.
50 50
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
51 51
    typedef LM LowerMap;
52 52

	
53 53
    /// \brief The type of the upper bound (capacity) map.
54 54
    ///
55 55
    /// The type of the map that stores the upper bounds (capacities)
56 56
    /// on the arcs.
57 57
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
58 58
    typedef UM UpperMap;
59 59

	
60 60
    /// \brief The type of supply map.
61 61
    ///
62 62
    /// The type of the map that stores the signed supply values of the 
63 63
    /// nodes. 
64 64
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
65 65
    typedef SM SupplyMap;
66 66

	
67 67
    /// \brief The type of the flow and supply values.
68 68
    typedef typename SupplyMap::Value Value;
69 69

	
70 70
    /// \brief The type of the map that stores the flow values.
71 71
    ///
72 72
    /// The type of the map that stores the flow values.
73 73
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap"
74 74
    /// concept.
75 75
#ifdef DOXYGEN
76 76
    typedef GR::ArcMap<Value> FlowMap;
77 77
#else
78 78
    typedef typename Digraph::template ArcMap<Value> FlowMap;
79 79
#endif
80 80

	
81 81
    /// \brief Instantiates a FlowMap.
82 82
    ///
83 83
    /// This function instantiates a \ref FlowMap.
84 84
    /// \param digraph The digraph for which we would like to define
85 85
    /// the flow map.
86 86
    static FlowMap* createFlowMap(const Digraph& digraph) {
87 87
      return new FlowMap(digraph);
88 88
    }
89 89

	
90 90
    /// \brief The elevator type used by the algorithm.
91 91
    ///
92 92
    /// The elevator type used by the algorithm.
93 93
    ///
94 94
    /// \sa Elevator, LinkedElevator
95 95
#ifdef DOXYGEN
96 96
    typedef lemon::Elevator<GR, GR::Node> Elevator;
97 97
#else
98 98
    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
99 99
#endif
100 100

	
101 101
    /// \brief Instantiates an Elevator.
102 102
    ///
103 103
    /// This function instantiates an \ref Elevator.
104 104
    /// \param digraph The digraph for which we would like to define
105 105
    /// the elevator.
106 106
    /// \param max_level The maximum level of the elevator.
107 107
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
108 108
      return new Elevator(digraph, max_level);
109 109
    }
110 110

	
111 111
    /// \brief The tolerance used by the algorithm
112 112
    ///
113 113
    /// The tolerance used by the algorithm to handle inexact computation.
114 114
    typedef lemon::Tolerance<Value> Tolerance;
115 115

	
116 116
  };
117 117

	
118 118
  /**
119 119
     \brief Push-relabel algorithm for the network circulation problem.
120 120

	
121 121
     \ingroup max_flow
122 122
     This class implements a push-relabel algorithm for the \e network
123 123
     \e circulation problem.
124 124
     It is to find a feasible circulation when lower and upper bounds
125 125
     are given for the flow values on the arcs and lower bounds are
126 126
     given for the difference between the outgoing and incoming flow
127 127
     at the nodes.
128 128

	
129 129
     The exact formulation of this problem is the following.
130 130
     Let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{R}\f$
131 131
     \f$upper: A\rightarrow\mathbf{R}\cup\{\infty\}\f$ denote the lower and
132 132
     upper bounds on the arcs, for which \f$lower(uv) \leq upper(uv)\f$
133 133
     holds for all \f$uv\in A\f$, and \f$sup: V\rightarrow\mathbf{R}\f$
134 134
     denotes the signed supply values of the nodes.
135 135
     If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
136 136
     supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
137 137
     \f$-sup(u)\f$ demand.
138 138
     A feasible circulation is an \f$f: A\rightarrow\mathbf{R}\f$
139 139
     solution of the following problem.
140 140

	
141 141
     \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu)
142 142
     \geq sup(u) \quad \forall u\in V, \f]
143 143
     \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A. \f]
144 144
     
145 145
     The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
146 146
     zero or negative in order to have a feasible solution (since the sum
147 147
     of the expressions on the left-hand side of the inequalities is zero).
148 148
     It means that the total demand must be greater or equal to the total
149 149
     supply and all the supplies have to be carried out from the supply nodes,
150 150
     but there could be demands that are not satisfied.
151 151
     If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
152 152
     constraints have to be satisfied with equality, i.e. all demands
153 153
     have to be satisfied and all supplies have to be used.
154 154
     
155 155
     If you need the opposite inequalities in the supply/demand constraints
156 156
     (i.e. the total demand is less than the total supply and all the demands
157 157
     have to be satisfied while there could be supplies that are not used),
158 158
     then you could easily transform the problem to the above form by reversing
159 159
     the direction of the arcs and taking the negative of the supply values
160 160
     (e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
161 161

	
162 162
     This algorithm either calculates a feasible circulation, or provides
163 163
     a \ref barrier() "barrier", which prooves that a feasible soultion
164 164
     cannot exist.
165 165

	
166 166
     Note that this algorithm also provides a feasible solution for the
167 167
     \ref min_cost_flow "minimum cost flow problem".
168 168

	
169 169
     \tparam GR The type of the digraph the algorithm runs on.
170 170
     \tparam LM The type of the lower bound map. The default
171 171
     map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
172 172
     \tparam UM The type of the upper bound (capacity) map.
173 173
     The default map type is \c LM.
174 174
     \tparam SM The type of the supply map. The default map type is
175 175
     \ref concepts::Digraph::NodeMap "GR::NodeMap<UM::Value>".
176 176
  */
177 177
#ifdef DOXYGEN
178 178
template< typename GR,
179 179
          typename LM,
180 180
          typename UM,
181 181
          typename SM,
182 182
          typename TR >
183 183
#else
184 184
template< typename GR,
185 185
          typename LM = typename GR::template ArcMap<int>,
186 186
          typename UM = LM,
187 187
          typename SM = typename GR::template NodeMap<typename UM::Value>,
188 188
          typename TR = CirculationDefaultTraits<GR, LM, UM, SM> >
189 189
#endif
190 190
  class Circulation {
191 191
  public:
192 192

	
193 193
    ///The \ref CirculationDefaultTraits "traits class" of the algorithm.
194 194
    typedef TR Traits;
195 195
    ///The type of the digraph the algorithm runs on.
196 196
    typedef typename Traits::Digraph Digraph;
197 197
    ///The type of the flow and supply values.
198 198
    typedef typename Traits::Value Value;
199 199

	
200 200
    ///The type of the lower bound map.
201 201
    typedef typename Traits::LowerMap LowerMap;
202 202
    ///The type of the upper bound (capacity) map.
203 203
    typedef typename Traits::UpperMap UpperMap;
204 204
    ///The type of the supply map.
205 205
    typedef typename Traits::SupplyMap SupplyMap;
206 206
    ///The type of the flow map.
207 207
    typedef typename Traits::FlowMap FlowMap;
208 208

	
209 209
    ///The type of the elevator.
210 210
    typedef typename Traits::Elevator Elevator;
211 211
    ///The type of the tolerance.
212 212
    typedef typename Traits::Tolerance Tolerance;
213 213

	
214 214
  private:
215 215

	
216 216
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
217 217

	
218 218
    const Digraph &_g;
219 219
    int _node_num;
220 220

	
221 221
    const LowerMap *_lo;
222 222
    const UpperMap *_up;
223 223
    const SupplyMap *_supply;
224 224

	
225 225
    FlowMap *_flow;
226 226
    bool _local_flow;
227 227

	
228 228
    Elevator* _level;
229 229
    bool _local_level;
230 230

	
231 231
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
232 232
    ExcessMap* _excess;
233 233

	
234 234
    Tolerance _tol;
235 235
    int _el;
236 236

	
237 237
  public:
238 238

	
239 239
    typedef Circulation Create;
240 240

	
241 241
    ///\name Named Template Parameters
242 242

	
243 243
    ///@{
244 244

	
245 245
    template <typename T>
246 246
    struct SetFlowMapTraits : public Traits {
247 247
      typedef T FlowMap;
248 248
      static FlowMap *createFlowMap(const Digraph&) {
249 249
        LEMON_ASSERT(false, "FlowMap is not initialized");
250 250
        return 0; // ignore warnings
251 251
      }
252 252
    };
253 253

	
254 254
    /// \brief \ref named-templ-param "Named parameter" for setting
255 255
    /// FlowMap type
256 256
    ///
257 257
    /// \ref named-templ-param "Named parameter" for setting FlowMap
258 258
    /// type.
259 259
    template <typename T>
260 260
    struct SetFlowMap
261 261
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
262 262
                           SetFlowMapTraits<T> > {
263 263
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
264 264
                          SetFlowMapTraits<T> > Create;
265 265
    };
266 266

	
267 267
    template <typename T>
268 268
    struct SetElevatorTraits : public Traits {
269 269
      typedef T Elevator;
270 270
      static Elevator *createElevator(const Digraph&, int) {
271 271
        LEMON_ASSERT(false, "Elevator is not initialized");
272 272
        return 0; // ignore warnings
273 273
      }
274 274
    };
275 275

	
276 276
    /// \brief \ref named-templ-param "Named parameter" for setting
277 277
    /// Elevator type
278 278
    ///
279 279
    /// \ref named-templ-param "Named parameter" for setting Elevator
280 280
    /// type. If this named parameter is used, then an external
281 281
    /// elevator object must be passed to the algorithm using the
282 282
    /// \ref elevator(Elevator&) "elevator()" function before calling
283 283
    /// \ref run() or \ref init().
284 284
    /// \sa SetStandardElevator
285 285
    template <typename T>
286 286
    struct SetElevator
287 287
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
288 288
                           SetElevatorTraits<T> > {
289 289
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
290 290
                          SetElevatorTraits<T> > Create;
291 291
    };
292 292

	
293 293
    template <typename T>
294 294
    struct SetStandardElevatorTraits : public Traits {
295 295
      typedef T Elevator;
296 296
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
297 297
        return new Elevator(digraph, max_level);
298 298
      }
299 299
    };
300 300

	
301 301
    /// \brief \ref named-templ-param "Named parameter" for setting
302 302
    /// Elevator type with automatic allocation
303 303
    ///
304 304
    /// \ref named-templ-param "Named parameter" for setting Elevator
305 305
    /// type with automatic allocation.
306 306
    /// The Elevator should have standard constructor interface to be
307 307
    /// able to automatically created by the algorithm (i.e. the
308 308
    /// digraph and the maximum level should be passed to it).
309
    /// However an external elevator object could also be passed to the
309
    /// However, an external elevator object could also be passed to the
310 310
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
311 311
    /// before calling \ref run() or \ref init().
312 312
    /// \sa SetElevator
313 313
    template <typename T>
314 314
    struct SetStandardElevator
315 315
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
316 316
                       SetStandardElevatorTraits<T> > {
317 317
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
318 318
                      SetStandardElevatorTraits<T> > Create;
319 319
    };
320 320

	
321 321
    /// @}
322 322

	
323 323
  protected:
324 324

	
325 325
    Circulation() {}
326 326

	
327 327
  public:
328 328

	
329 329
    /// Constructor.
330 330

	
331 331
    /// The constructor of the class.
332 332
    ///
333 333
    /// \param graph The digraph the algorithm runs on.
334 334
    /// \param lower The lower bounds for the flow values on the arcs.
335 335
    /// \param upper The upper bounds (capacities) for the flow values 
336 336
    /// on the arcs.
337 337
    /// \param supply The signed supply values of the nodes.
338 338
    Circulation(const Digraph &graph, const LowerMap &lower,
339 339
                const UpperMap &upper, const SupplyMap &supply)
340 340
      : _g(graph), _lo(&lower), _up(&upper), _supply(&supply),
341 341
        _flow(NULL), _local_flow(false), _level(NULL), _local_level(false),
342 342
        _excess(NULL) {}
343 343

	
344 344
    /// Destructor.
345 345
    ~Circulation() {
346 346
      destroyStructures();
347 347
    }
348 348

	
349 349

	
350 350
  private:
351 351

	
352 352
    bool checkBoundMaps() {
353 353
      for (ArcIt e(_g);e!=INVALID;++e) {
354 354
        if (_tol.less((*_up)[e], (*_lo)[e])) return false;
355 355
      }
356 356
      return true;
357 357
    }
358 358

	
359 359
    void createStructures() {
360 360
      _node_num = _el = countNodes(_g);
361 361

	
362 362
      if (!_flow) {
363 363
        _flow = Traits::createFlowMap(_g);
364 364
        _local_flow = true;
365 365
      }
366 366
      if (!_level) {
367 367
        _level = Traits::createElevator(_g, _node_num);
368 368
        _local_level = true;
369 369
      }
370 370
      if (!_excess) {
371 371
        _excess = new ExcessMap(_g);
372 372
      }
373 373
    }
374 374

	
375 375
    void destroyStructures() {
376 376
      if (_local_flow) {
377 377
        delete _flow;
378 378
      }
379 379
      if (_local_level) {
380 380
        delete _level;
381 381
      }
382 382
      if (_excess) {
383 383
        delete _excess;
384 384
      }
385 385
    }
386 386

	
387 387
  public:
388 388

	
389 389
    /// Sets the lower bound map.
390 390

	
391 391
    /// Sets the lower bound map.
392 392
    /// \return <tt>(*this)</tt>
393 393
    Circulation& lowerMap(const LowerMap& map) {
394 394
      _lo = &map;
395 395
      return *this;
396 396
    }
397 397

	
398 398
    /// Sets the upper bound (capacity) map.
399 399

	
400 400
    /// Sets the upper bound (capacity) map.
401 401
    /// \return <tt>(*this)</tt>
402 402
    Circulation& upperMap(const UpperMap& map) {
403 403
      _up = &map;
404 404
      return *this;
405 405
    }
406 406

	
407 407
    /// Sets the supply map.
408 408

	
409 409
    /// Sets the supply map.
410 410
    /// \return <tt>(*this)</tt>
411 411
    Circulation& supplyMap(const SupplyMap& map) {
412 412
      _supply = &map;
413 413
      return *this;
414 414
    }
415 415

	
416 416
    /// \brief Sets the flow map.
417 417
    ///
418 418
    /// Sets the flow map.
419 419
    /// If you don't use this function before calling \ref run() or
420 420
    /// \ref init(), an instance will be allocated automatically.
421 421
    /// The destructor deallocates this automatically allocated map,
422 422
    /// of course.
423 423
    /// \return <tt>(*this)</tt>
424 424
    Circulation& flowMap(FlowMap& map) {
425 425
      if (_local_flow) {
426 426
        delete _flow;
427 427
        _local_flow = false;
428 428
      }
429 429
      _flow = &map;
430 430
      return *this;
431 431
    }
432 432

	
433 433
    /// \brief Sets the elevator used by algorithm.
434 434
    ///
435 435
    /// Sets the elevator used by algorithm.
436 436
    /// If you don't use this function before calling \ref run() or
437 437
    /// \ref init(), an instance will be allocated automatically.
438 438
    /// The destructor deallocates this automatically allocated elevator,
439 439
    /// of course.
440 440
    /// \return <tt>(*this)</tt>
441 441
    Circulation& elevator(Elevator& elevator) {
442 442
      if (_local_level) {
443 443
        delete _level;
444 444
        _local_level = false;
445 445
      }
446 446
      _level = &elevator;
447 447
      return *this;
448 448
    }
449 449

	
450 450
    /// \brief Returns a const reference to the elevator.
451 451
    ///
452 452
    /// Returns a const reference to the elevator.
453 453
    ///
454 454
    /// \pre Either \ref run() or \ref init() must be called before
455 455
    /// using this function.
456 456
    const Elevator& elevator() const {
457 457
      return *_level;
458 458
    }
459 459

	
460 460
    /// \brief Sets the tolerance used by the algorithm.
461 461
    ///
462 462
    /// Sets the tolerance object used by the algorithm.
463 463
    /// \return <tt>(*this)</tt>
464 464
    Circulation& tolerance(const Tolerance& tolerance) {
465 465
      _tol = tolerance;
466 466
      return *this;
467 467
    }
468 468

	
469 469
    /// \brief Returns a const reference to the tolerance.
470 470
    ///
471 471
    /// Returns a const reference to the tolerance object used by
472 472
    /// the algorithm.
473 473
    const Tolerance& tolerance() const {
474 474
      return _tol;
475 475
    }
476 476

	
477 477
    /// \name Execution Control
478 478
    /// The simplest way to execute the algorithm is to call \ref run().\n
479 479
    /// If you need better control on the initial solution or the execution,
480 480
    /// you have to call one of the \ref init() functions first, then
481 481
    /// the \ref start() function.
482 482

	
483 483
    ///@{
484 484

	
485 485
    /// Initializes the internal data structures.
486 486

	
487 487
    /// Initializes the internal data structures and sets all flow values
488 488
    /// to the lower bound.
489 489
    void init()
490 490
    {
491 491
      LEMON_DEBUG(checkBoundMaps(),
492 492
        "Upper bounds must be greater or equal to the lower bounds");
493 493

	
494 494
      createStructures();
495 495

	
496 496
      for(NodeIt n(_g);n!=INVALID;++n) {
497 497
        (*_excess)[n] = (*_supply)[n];
498 498
      }
499 499

	
500 500
      for (ArcIt e(_g);e!=INVALID;++e) {
501 501
        _flow->set(e, (*_lo)[e]);
502 502
        (*_excess)[_g.target(e)] += (*_flow)[e];
503 503
        (*_excess)[_g.source(e)] -= (*_flow)[e];
504 504
      }
505 505

	
506 506
      // global relabeling tested, but in general case it provides
507 507
      // worse performance for random digraphs
508 508
      _level->initStart();
509 509
      for(NodeIt n(_g);n!=INVALID;++n)
510 510
        _level->initAddItem(n);
511 511
      _level->initFinish();
512 512
      for(NodeIt n(_g);n!=INVALID;++n)
513 513
        if(_tol.positive((*_excess)[n]))
514 514
          _level->activate(n);
515 515
    }
516 516

	
517 517
    /// Initializes the internal data structures using a greedy approach.
518 518

	
519 519
    /// Initializes the internal data structures using a greedy approach
520 520
    /// to construct the initial solution.
521 521
    void greedyInit()
522 522
    {
523 523
      LEMON_DEBUG(checkBoundMaps(),
524 524
        "Upper bounds must be greater or equal to the lower bounds");
525 525

	
526 526
      createStructures();
527 527

	
528 528
      for(NodeIt n(_g);n!=INVALID;++n) {
529 529
        (*_excess)[n] = (*_supply)[n];
530 530
      }
531 531

	
532 532
      for (ArcIt e(_g);e!=INVALID;++e) {
533 533
        if (!_tol.less(-(*_excess)[_g.target(e)], (*_up)[e])) {
534 534
          _flow->set(e, (*_up)[e]);
535 535
          (*_excess)[_g.target(e)] += (*_up)[e];
536 536
          (*_excess)[_g.source(e)] -= (*_up)[e];
537 537
        } else if (_tol.less(-(*_excess)[_g.target(e)], (*_lo)[e])) {
538 538
          _flow->set(e, (*_lo)[e]);
539 539
          (*_excess)[_g.target(e)] += (*_lo)[e];
540 540
          (*_excess)[_g.source(e)] -= (*_lo)[e];
541 541
        } else {
542 542
          Value fc = -(*_excess)[_g.target(e)];
543 543
          _flow->set(e, fc);
544 544
          (*_excess)[_g.target(e)] = 0;
545 545
          (*_excess)[_g.source(e)] -= fc;
546 546
        }
547 547
      }
548 548

	
549 549
      _level->initStart();
550 550
      for(NodeIt n(_g);n!=INVALID;++n)
551 551
        _level->initAddItem(n);
552 552
      _level->initFinish();
553 553
      for(NodeIt n(_g);n!=INVALID;++n)
554 554
        if(_tol.positive((*_excess)[n]))
555 555
          _level->activate(n);
556 556
    }
557 557

	
558 558
    ///Executes the algorithm
559 559

	
560 560
    ///This function executes the algorithm.
561 561
    ///
562 562
    ///\return \c true if a feasible circulation is found.
563 563
    ///
564 564
    ///\sa barrier()
565 565
    ///\sa barrierMap()
566 566
    bool start()
567 567
    {
568 568

	
569 569
      Node act;
570 570
      Node bact=INVALID;
571 571
      Node last_activated=INVALID;
572 572
      while((act=_level->highestActive())!=INVALID) {
573 573
        int actlevel=(*_level)[act];
574 574
        int mlevel=_node_num;
575 575
        Value exc=(*_excess)[act];
576 576

	
577 577
        for(OutArcIt e(_g,act);e!=INVALID; ++e) {
578 578
          Node v = _g.target(e);
579 579
          Value fc=(*_up)[e]-(*_flow)[e];
580 580
          if(!_tol.positive(fc)) continue;
581 581
          if((*_level)[v]<actlevel) {
582 582
            if(!_tol.less(fc, exc)) {
583 583
              _flow->set(e, (*_flow)[e] + exc);
584 584
              (*_excess)[v] += exc;
585 585
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
586 586
                _level->activate(v);
587 587
              (*_excess)[act] = 0;
588 588
              _level->deactivate(act);
589 589
              goto next_l;
590 590
            }
591 591
            else {
592 592
              _flow->set(e, (*_up)[e]);
593 593
              (*_excess)[v] += fc;
594 594
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
595 595
                _level->activate(v);
596 596
              exc-=fc;
597 597
            }
598 598
          }
599 599
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
600 600
        }
601 601
        for(InArcIt e(_g,act);e!=INVALID; ++e) {
602 602
          Node v = _g.source(e);
603 603
          Value fc=(*_flow)[e]-(*_lo)[e];
604 604
          if(!_tol.positive(fc)) continue;
605 605
          if((*_level)[v]<actlevel) {
606 606
            if(!_tol.less(fc, exc)) {
607 607
              _flow->set(e, (*_flow)[e] - exc);
608 608
              (*_excess)[v] += exc;
609 609
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
610 610
                _level->activate(v);
611 611
              (*_excess)[act] = 0;
612 612
              _level->deactivate(act);
613 613
              goto next_l;
614 614
            }
615 615
            else {
616 616
              _flow->set(e, (*_lo)[e]);
617 617
              (*_excess)[v] += fc;
618 618
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
619 619
                _level->activate(v);
620 620
              exc-=fc;
621 621
            }
622 622
          }
623 623
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
624 624
        }
625 625

	
626 626
        (*_excess)[act] = exc;
627 627
        if(!_tol.positive(exc)) _level->deactivate(act);
628 628
        else if(mlevel==_node_num) {
629 629
          _level->liftHighestActiveToTop();
630 630
          _el = _node_num;
631 631
          return false;
632 632
        }
633 633
        else {
634 634
          _level->liftHighestActive(mlevel+1);
635 635
          if(_level->onLevel(actlevel)==0) {
636 636
            _el = actlevel;
637 637
            return false;
638 638
          }
639 639
        }
640 640
      next_l:
641 641
        ;
642 642
      }
643 643
      return true;
644 644
    }
645 645

	
646 646
    /// Runs the algorithm.
647 647

	
648 648
    /// This function runs the algorithm.
649 649
    ///
650 650
    /// \return \c true if a feasible circulation is found.
651 651
    ///
652 652
    /// \note Apart from the return value, c.run() is just a shortcut of
653 653
    /// the following code.
654 654
    /// \code
655 655
    ///   c.greedyInit();
656 656
    ///   c.start();
657 657
    /// \endcode
658 658
    bool run() {
659 659
      greedyInit();
660 660
      return start();
661 661
    }
662 662

	
663 663
    /// @}
664 664

	
665 665
    /// \name Query Functions
666 666
    /// The results of the circulation algorithm can be obtained using
667 667
    /// these functions.\n
668 668
    /// Either \ref run() or \ref start() should be called before
669 669
    /// using them.
670 670

	
671 671
    ///@{
672 672

	
673 673
    /// \brief Returns the flow value on the given arc.
674 674
    ///
675 675
    /// Returns the flow value on the given arc.
676 676
    ///
677 677
    /// \pre Either \ref run() or \ref init() must be called before
678 678
    /// using this function.
679 679
    Value flow(const Arc& arc) const {
680 680
      return (*_flow)[arc];
681 681
    }
682 682

	
683 683
    /// \brief Returns a const reference to the flow map.
684 684
    ///
685 685
    /// Returns a const reference to the arc map storing the found flow.
686 686
    ///
687 687
    /// \pre Either \ref run() or \ref init() must be called before
688 688
    /// using this function.
689 689
    const FlowMap& flowMap() const {
690 690
      return *_flow;
691 691
    }
692 692

	
693 693
    /**
694 694
       \brief Returns \c true if the given node is in a barrier.
695 695

	
696 696
       Barrier is a set \e B of nodes for which
697 697

	
698 698
       \f[ \sum_{uv\in A: u\in B} upper(uv) -
699 699
           \sum_{uv\in A: v\in B} lower(uv) < \sum_{v\in B} sup(v) \f]
700 700

	
701 701
       holds. The existence of a set with this property prooves that a
702 702
       feasible circualtion cannot exist.
703 703

	
704 704
       This function returns \c true if the given node is in the found
705 705
       barrier. If a feasible circulation is found, the function
706 706
       gives back \c false for every node.
707 707

	
708 708
       \pre Either \ref run() or \ref init() must be called before
709 709
       using this function.
710 710

	
711 711
       \sa barrierMap()
712 712
       \sa checkBarrier()
713 713
    */
714 714
    bool barrier(const Node& node) const
715 715
    {
716 716
      return (*_level)[node] >= _el;
717 717
    }
718 718

	
719 719
    /// \brief Gives back a barrier.
720 720
    ///
721 721
    /// This function sets \c bar to the characteristic vector of the
722 722
    /// found barrier. \c bar should be a \ref concepts::WriteMap "writable"
723 723
    /// node map with \c bool (or convertible) value type.
724 724
    ///
725 725
    /// If a feasible circulation is found, the function gives back an
726 726
    /// empty set, so \c bar[v] will be \c false for all nodes \c v.
727 727
    ///
728 728
    /// \note This function calls \ref barrier() for each node,
729 729
    /// so it runs in O(n) time.
730 730
    ///
731 731
    /// \pre Either \ref run() or \ref init() must be called before
732 732
    /// using this function.
733 733
    ///
734 734
    /// \sa barrier()
735 735
    /// \sa checkBarrier()
736 736
    template<class BarrierMap>
737 737
    void barrierMap(BarrierMap &bar) const
738 738
    {
739 739
      for(NodeIt n(_g);n!=INVALID;++n)
740 740
        bar.set(n, (*_level)[n] >= _el);
741 741
    }
742 742

	
743 743
    /// @}
744 744

	
745 745
    /// \name Checker Functions
746 746
    /// The feasibility of the results can be checked using
747 747
    /// these functions.\n
748 748
    /// Either \ref run() or \ref start() should be called before
749 749
    /// using them.
750 750

	
751 751
    ///@{
752 752

	
753 753
    ///Check if the found flow is a feasible circulation
754 754

	
755 755
    ///Check if the found flow is a feasible circulation,
756 756
    ///
757 757
    bool checkFlow() const {
758 758
      for(ArcIt e(_g);e!=INVALID;++e)
759 759
        if((*_flow)[e]<(*_lo)[e]||(*_flow)[e]>(*_up)[e]) return false;
760 760
      for(NodeIt n(_g);n!=INVALID;++n)
761 761
        {
762 762
          Value dif=-(*_supply)[n];
763 763
          for(InArcIt e(_g,n);e!=INVALID;++e) dif-=(*_flow)[e];
764 764
          for(OutArcIt e(_g,n);e!=INVALID;++e) dif+=(*_flow)[e];
765 765
          if(_tol.negative(dif)) return false;
766 766
        }
767 767
      return true;
768 768
    }
769 769

	
770 770
    ///Check whether or not the last execution provides a barrier
771 771

	
772 772
    ///Check whether or not the last execution provides a barrier.
773 773
    ///\sa barrier()
774 774
    ///\sa barrierMap()
775 775
    bool checkBarrier() const
776 776
    {
777 777
      Value delta=0;
778 778
      Value inf_cap = std::numeric_limits<Value>::has_infinity ?
779 779
        std::numeric_limits<Value>::infinity() :
780 780
        std::numeric_limits<Value>::max();
781 781
      for(NodeIt n(_g);n!=INVALID;++n)
782 782
        if(barrier(n))
783 783
          delta-=(*_supply)[n];
784 784
      for(ArcIt e(_g);e!=INVALID;++e)
785 785
        {
786 786
          Node s=_g.source(e);
787 787
          Node t=_g.target(e);
788 788
          if(barrier(s)&&!barrier(t)) {
789 789
            if (_tol.less(inf_cap - (*_up)[e], delta)) return false;
790 790
            delta+=(*_up)[e];
791 791
          }
792 792
          else if(barrier(t)&&!barrier(s)) delta-=(*_lo)[e];
793 793
        }
794 794
      return _tol.negative(delta);
795 795
    }
796 796

	
797 797
    /// @}
798 798

	
799 799
  };
800 800

	
801 801
}
802 802

	
803 803
#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-2009
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_CONCEPTS_DIGRAPH_H
20 20
#define LEMON_CONCEPTS_DIGRAPH_H
21 21

	
22 22
///\ingroup graph_concepts
23 23
///\file
24 24
///\brief The concept of directed graphs.
25 25

	
26 26
#include <lemon/core.h>
27 27
#include <lemon/concepts/maps.h>
28 28
#include <lemon/concept_check.h>
29 29
#include <lemon/concepts/graph_components.h>
30 30

	
31 31
namespace lemon {
32 32
  namespace concepts {
33 33

	
34 34
    /// \ingroup graph_concepts
35 35
    ///
36 36
    /// \brief Class describing the concept of directed graphs.
37 37
    ///
38 38
    /// This class describes the common interface of all directed
39 39
    /// graphs (digraphs).
40 40
    ///
41 41
    /// Like all concept classes, it only provides an interface
42 42
    /// without any sensible implementation. So any general algorithm for
43 43
    /// directed graphs should compile with this class, but it will not
44 44
    /// run properly, of course.
45 45
    /// An actual digraph implementation like \ref ListDigraph or
46 46
    /// \ref SmartDigraph may have additional functionality.
47 47
    ///
48 48
    /// \sa Graph
49 49
    class Digraph {
50 50
    private:
51 51
      /// Diraphs are \e not copy constructible. Use DigraphCopy instead.
52 52
      Digraph(const Digraph &) {}
53 53
      /// \brief Assignment of a digraph to another one is \e not allowed.
54 54
      /// Use DigraphCopy instead.
55 55
      void operator=(const Digraph &) {}
56 56

	
57 57
    public:
58 58
      /// Default constructor.
59 59
      Digraph() { }
60 60

	
61 61
      /// The node type of the digraph
62 62

	
63 63
      /// This class identifies a node of the digraph. It also serves
64 64
      /// as a base class of the node iterators,
65 65
      /// thus they convert to this type.
66 66
      class Node {
67 67
      public:
68 68
        /// Default constructor
69 69

	
70 70
        /// Default constructor.
71 71
        /// \warning It sets the object to an undefined value.
72 72
        Node() { }
73 73
        /// Copy constructor.
74 74

	
75 75
        /// Copy constructor.
76 76
        ///
77 77
        Node(const Node&) { }
78 78

	
79 79
        /// %Invalid constructor \& conversion.
80 80

	
81 81
        /// Initializes the object to be invalid.
82 82
        /// \sa Invalid for more details.
83 83
        Node(Invalid) { }
84 84
        /// Equality operator
85 85

	
86 86
        /// Equality operator.
87 87
        ///
88 88
        /// Two iterators are equal if and only if they point to the
89 89
        /// same object or both are \c INVALID.
90 90
        bool operator==(Node) const { return true; }
91 91

	
92 92
        /// Inequality operator
93 93

	
94 94
        /// Inequality operator.
95 95
        bool operator!=(Node) const { return true; }
96 96

	
97 97
        /// Artificial ordering operator.
98 98

	
99 99
        /// Artificial ordering operator.
100 100
        ///
101 101
        /// \note This operator only has to define some strict ordering of
102 102
        /// the nodes; this order has nothing to do with the iteration
103 103
        /// ordering of the nodes.
104 104
        bool operator<(Node) const { return false; }
105 105
      };
106 106

	
107 107
      /// Iterator class for the nodes.
108 108

	
109 109
      /// This iterator goes through each node of the digraph.
110
      /// Its usage is quite simple, for example you can count the number
110
      /// Its usage is quite simple, for example, you can count the number
111 111
      /// of nodes in a digraph \c g of type \c %Digraph like this:
112 112
      ///\code
113 113
      /// int count=0;
114 114
      /// for (Digraph::NodeIt n(g); n!=INVALID; ++n) ++count;
115 115
      ///\endcode
116 116
      class NodeIt : public Node {
117 117
      public:
118 118
        /// Default constructor
119 119

	
120 120
        /// Default constructor.
121 121
        /// \warning It sets the iterator to an undefined value.
122 122
        NodeIt() { }
123 123
        /// Copy constructor.
124 124

	
125 125
        /// Copy constructor.
126 126
        ///
127 127
        NodeIt(const NodeIt& n) : Node(n) { }
128 128
        /// %Invalid constructor \& conversion.
129 129

	
130 130
        /// Initializes the iterator to be invalid.
131 131
        /// \sa Invalid for more details.
132 132
        NodeIt(Invalid) { }
133 133
        /// Sets the iterator to the first node.
134 134

	
135 135
        /// Sets the iterator to the first node of the given digraph.
136 136
        ///
137 137
        explicit NodeIt(const Digraph&) { }
138 138
        /// Sets the iterator to the given node.
139 139

	
140 140
        /// Sets the iterator to the given node of the given digraph.
141 141
        ///
142 142
        NodeIt(const Digraph&, const Node&) { }
143 143
        /// Next node.
144 144

	
145 145
        /// Assign the iterator to the next node.
146 146
        ///
147 147
        NodeIt& operator++() { return *this; }
148 148
      };
149 149

	
150 150

	
151 151
      /// The arc type of the digraph
152 152

	
153 153
      /// This class identifies an arc of the digraph. It also serves
154 154
      /// as a base class of the arc iterators,
155 155
      /// thus they will convert to this type.
156 156
      class Arc {
157 157
      public:
158 158
        /// Default constructor
159 159

	
160 160
        /// Default constructor.
161 161
        /// \warning It sets the object to an undefined value.
162 162
        Arc() { }
163 163
        /// Copy constructor.
164 164

	
165 165
        /// Copy constructor.
166 166
        ///
167 167
        Arc(const Arc&) { }
168 168
        /// %Invalid constructor \& conversion.
169 169

	
170 170
        /// Initializes the object to be invalid.
171 171
        /// \sa Invalid for more details.
172 172
        Arc(Invalid) { }
173 173
        /// Equality operator
174 174

	
175 175
        /// Equality operator.
176 176
        ///
177 177
        /// Two iterators are equal if and only if they point to the
178 178
        /// same object or both are \c INVALID.
179 179
        bool operator==(Arc) const { return true; }
180 180
        /// Inequality operator
181 181

	
182 182
        /// Inequality operator.
183 183
        bool operator!=(Arc) const { return true; }
184 184

	
185 185
        /// Artificial ordering operator.
186 186

	
187 187
        /// Artificial ordering operator.
188 188
        ///
189 189
        /// \note This operator only has to define some strict ordering of
190 190
        /// the arcs; this order has nothing to do with the iteration
191 191
        /// ordering of the arcs.
192 192
        bool operator<(Arc) const { return false; }
193 193
      };
194 194

	
195 195
      /// Iterator class for the outgoing arcs of a node.
196 196

	
197 197
      /// This iterator goes trough the \e outgoing arcs of a certain node
198 198
      /// of a digraph.
199
      /// Its usage is quite simple, for example you can count the number
199
      /// Its usage is quite simple, for example, you can count the number
200 200
      /// of outgoing arcs of a node \c n
201 201
      /// in a digraph \c g of type \c %Digraph as follows.
202 202
      ///\code
203 203
      /// int count=0;
204 204
      /// for (Digraph::OutArcIt a(g, n); a!=INVALID; ++a) ++count;
205 205
      ///\endcode
206 206
      class OutArcIt : public Arc {
207 207
      public:
208 208
        /// Default constructor
209 209

	
210 210
        /// Default constructor.
211 211
        /// \warning It sets the iterator to an undefined value.
212 212
        OutArcIt() { }
213 213
        /// Copy constructor.
214 214

	
215 215
        /// Copy constructor.
216 216
        ///
217 217
        OutArcIt(const OutArcIt& e) : Arc(e) { }
218 218
        /// %Invalid constructor \& conversion.
219 219

	
220 220
        /// Initializes the iterator to be invalid.
221 221
        /// \sa Invalid for more details.
222 222
        OutArcIt(Invalid) { }
223 223
        /// Sets the iterator to the first outgoing arc.
224 224

	
225 225
        /// Sets the iterator to the first outgoing arc of the given node.
226 226
        ///
227 227
        OutArcIt(const Digraph&, const Node&) { }
228 228
        /// Sets the iterator to the given arc.
229 229

	
230 230
        /// Sets the iterator to the given arc of the given digraph.
231 231
        ///
232 232
        OutArcIt(const Digraph&, const Arc&) { }
233 233
        /// Next outgoing arc
234 234

	
235 235
        /// Assign the iterator to the next
236 236
        /// outgoing arc of the corresponding node.
237 237
        OutArcIt& operator++() { return *this; }
238 238
      };
239 239

	
240 240
      /// Iterator class for the incoming arcs of a node.
241 241

	
242 242
      /// This iterator goes trough the \e incoming arcs of a certain node
243 243
      /// of a digraph.
244
      /// Its usage is quite simple, for example you can count the number
244
      /// Its usage is quite simple, for example, you can count the number
245 245
      /// of incoming arcs of a node \c n
246 246
      /// in a digraph \c g of type \c %Digraph as follows.
247 247
      ///\code
248 248
      /// int count=0;
249 249
      /// for(Digraph::InArcIt a(g, n); a!=INVALID; ++a) ++count;
250 250
      ///\endcode
251 251
      class InArcIt : public Arc {
252 252
      public:
253 253
        /// Default constructor
254 254

	
255 255
        /// Default constructor.
256 256
        /// \warning It sets the iterator to an undefined value.
257 257
        InArcIt() { }
258 258
        /// Copy constructor.
259 259

	
260 260
        /// Copy constructor.
261 261
        ///
262 262
        InArcIt(const InArcIt& e) : Arc(e) { }
263 263
        /// %Invalid constructor \& conversion.
264 264

	
265 265
        /// Initializes the iterator to be invalid.
266 266
        /// \sa Invalid for more details.
267 267
        InArcIt(Invalid) { }
268 268
        /// Sets the iterator to the first incoming arc.
269 269

	
270 270
        /// Sets the iterator to the first incoming arc of the given node.
271 271
        ///
272 272
        InArcIt(const Digraph&, const Node&) { }
273 273
        /// Sets the iterator to the given arc.
274 274

	
275 275
        /// Sets the iterator to the given arc of the given digraph.
276 276
        ///
277 277
        InArcIt(const Digraph&, const Arc&) { }
278 278
        /// Next incoming arc
279 279

	
280 280
        /// Assign the iterator to the next
281 281
        /// incoming arc of the corresponding node.
282 282
        InArcIt& operator++() { return *this; }
283 283
      };
284 284

	
285 285
      /// Iterator class for the arcs.
286 286

	
287 287
      /// This iterator goes through each arc of the digraph.
288
      /// Its usage is quite simple, for example you can count the number
288
      /// Its usage is quite simple, for example, you can count the number
289 289
      /// of arcs in a digraph \c g of type \c %Digraph as follows:
290 290
      ///\code
291 291
      /// int count=0;
292 292
      /// for(Digraph::ArcIt a(g); a!=INVALID; ++a) ++count;
293 293
      ///\endcode
294 294
      class ArcIt : public Arc {
295 295
      public:
296 296
        /// Default constructor
297 297

	
298 298
        /// Default constructor.
299 299
        /// \warning It sets the iterator to an undefined value.
300 300
        ArcIt() { }
301 301
        /// Copy constructor.
302 302

	
303 303
        /// Copy constructor.
304 304
        ///
305 305
        ArcIt(const ArcIt& e) : Arc(e) { }
306 306
        /// %Invalid constructor \& conversion.
307 307

	
308 308
        /// Initializes the iterator to be invalid.
309 309
        /// \sa Invalid for more details.
310 310
        ArcIt(Invalid) { }
311 311
        /// Sets the iterator to the first arc.
312 312

	
313 313
        /// Sets the iterator to the first arc of the given digraph.
314 314
        ///
315 315
        explicit ArcIt(const Digraph& g) { ignore_unused_variable_warning(g); }
316 316
        /// Sets the iterator to the given arc.
317 317

	
318 318
        /// Sets the iterator to the given arc of the given digraph.
319 319
        ///
320 320
        ArcIt(const Digraph&, const Arc&) { }
321 321
        /// Next arc
322 322

	
323 323
        /// Assign the iterator to the next arc.
324 324
        ///
325 325
        ArcIt& operator++() { return *this; }
326 326
      };
327 327

	
328 328
      /// \brief The source node of the arc.
329 329
      ///
330 330
      /// Returns the source node of the given arc.
331 331
      Node source(Arc) const { return INVALID; }
332 332

	
333 333
      /// \brief The target node of the arc.
334 334
      ///
335 335
      /// Returns the target node of the given arc.
336 336
      Node target(Arc) const { return INVALID; }
337 337

	
338 338
      /// \brief The ID of the node.
339 339
      ///
340 340
      /// Returns the ID of the given node.
341 341
      int id(Node) const { return -1; }
342 342

	
343 343
      /// \brief The ID of the arc.
344 344
      ///
345 345
      /// Returns the ID of the given arc.
346 346
      int id(Arc) const { return -1; }
347 347

	
348 348
      /// \brief The node with the given ID.
349 349
      ///
350 350
      /// Returns the node with the given ID.
351 351
      /// \pre The argument should be a valid node ID in the digraph.
352 352
      Node nodeFromId(int) const { return INVALID; }
353 353

	
354 354
      /// \brief The arc with the given ID.
355 355
      ///
356 356
      /// Returns the arc with the given ID.
357 357
      /// \pre The argument should be a valid arc ID in the digraph.
358 358
      Arc arcFromId(int) const { return INVALID; }
359 359

	
360 360
      /// \brief An upper bound on the node IDs.
361 361
      ///
362 362
      /// Returns an upper bound on the node IDs.
363 363
      int maxNodeId() const { return -1; }
364 364

	
365 365
      /// \brief An upper bound on the arc IDs.
366 366
      ///
367 367
      /// Returns an upper bound on the arc IDs.
368 368
      int maxArcId() const { return -1; }
369 369

	
370 370
      void first(Node&) const {}
371 371
      void next(Node&) const {}
372 372

	
373 373
      void first(Arc&) const {}
374 374
      void next(Arc&) const {}
375 375

	
376 376

	
377 377
      void firstIn(Arc&, const Node&) const {}
378 378
      void nextIn(Arc&) const {}
379 379

	
380 380
      void firstOut(Arc&, const Node&) const {}
381 381
      void nextOut(Arc&) const {}
382 382

	
383 383
      // The second parameter is dummy.
384 384
      Node fromId(int, Node) const { return INVALID; }
385 385
      // The second parameter is dummy.
386 386
      Arc fromId(int, Arc) const { return INVALID; }
387 387

	
388 388
      // Dummy parameter.
389 389
      int maxId(Node) const { return -1; }
390 390
      // Dummy parameter.
391 391
      int maxId(Arc) const { return -1; }
392 392

	
393 393
      /// \brief The opposite node on the arc.
394 394
      ///
395 395
      /// Returns the opposite node on the given arc.
396 396
      Node oppositeNode(Node, Arc) const { return INVALID; }
397 397

	
398 398
      /// \brief The base node of the iterator.
399 399
      ///
400 400
      /// Returns the base node of the given outgoing arc iterator
401 401
      /// (i.e. the source node of the corresponding arc).
402 402
      Node baseNode(OutArcIt) const { return INVALID; }
403 403

	
404 404
      /// \brief The running node of the iterator.
405 405
      ///
406 406
      /// Returns the running node of the given outgoing arc iterator
407 407
      /// (i.e. the target node of the corresponding arc).
408 408
      Node runningNode(OutArcIt) const { return INVALID; }
409 409

	
410 410
      /// \brief The base node of the iterator.
411 411
      ///
412 412
      /// Returns the base node of the given incomming arc iterator
413 413
      /// (i.e. the target node of the corresponding arc).
414 414
      Node baseNode(InArcIt) const { return INVALID; }
415 415

	
416 416
      /// \brief The running node of the iterator.
417 417
      ///
418 418
      /// Returns the running node of the given incomming arc iterator
419 419
      /// (i.e. the source node of the corresponding arc).
420 420
      Node runningNode(InArcIt) const { return INVALID; }
421 421

	
422 422
      /// \brief Standard graph map type for the nodes.
423 423
      ///
424 424
      /// Standard graph map type for the nodes.
425 425
      /// It conforms to the ReferenceMap concept.
426 426
      template<class T>
427 427
      class NodeMap : public ReferenceMap<Node, T, T&, const T&> {
428 428
      public:
429 429

	
430 430
        /// Constructor
431 431
        explicit NodeMap(const Digraph&) { }
432 432
        /// Constructor with given initial value
433 433
        NodeMap(const Digraph&, T) { }
434 434

	
435 435
      private:
436 436
        ///Copy constructor
437 437
        NodeMap(const NodeMap& nm) : 
438 438
          ReferenceMap<Node, T, T&, const T&>(nm) { }
439 439
        ///Assignment operator
440 440
        template <typename CMap>
441 441
        NodeMap& operator=(const CMap&) {
442 442
          checkConcept<ReadMap<Node, T>, CMap>();
443 443
          return *this;
444 444
        }
445 445
      };
446 446

	
447 447
      /// \brief Standard graph map type for the arcs.
448 448
      ///
449 449
      /// Standard graph map type for the arcs.
450 450
      /// It conforms to the ReferenceMap concept.
451 451
      template<class T>
452 452
      class ArcMap : public ReferenceMap<Arc, T, T&, const T&> {
453 453
      public:
454 454

	
455 455
        /// Constructor
456 456
        explicit ArcMap(const Digraph&) { }
457 457
        /// Constructor with given initial value
458 458
        ArcMap(const Digraph&, T) { }
459 459

	
460 460
      private:
461 461
        ///Copy constructor
462 462
        ArcMap(const ArcMap& em) :
463 463
          ReferenceMap<Arc, T, T&, const T&>(em) { }
464 464
        ///Assignment operator
465 465
        template <typename CMap>
466 466
        ArcMap& operator=(const CMap&) {
467 467
          checkConcept<ReadMap<Arc, T>, CMap>();
468 468
          return *this;
469 469
        }
470 470
      };
471 471

	
472 472
      template <typename _Digraph>
473 473
      struct Constraints {
474 474
        void constraints() {
475 475
          checkConcept<BaseDigraphComponent, _Digraph>();
476 476
          checkConcept<IterableDigraphComponent<>, _Digraph>();
477 477
          checkConcept<IDableDigraphComponent<>, _Digraph>();
478 478
          checkConcept<MappableDigraphComponent<>, _Digraph>();
479 479
        }
480 480
      };
481 481

	
482 482
    };
483 483

	
484 484
  } //namespace concepts
485 485
} //namespace lemon
486 486

	
487 487

	
488 488

	
489 489
#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-2009
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 undirected graphs.
22 22

	
23 23
#ifndef LEMON_CONCEPTS_GRAPH_H
24 24
#define LEMON_CONCEPTS_GRAPH_H
25 25

	
26 26
#include <lemon/concepts/graph_components.h>
27 27
#include <lemon/concepts/maps.h>
28 28
#include <lemon/concept_check.h>
29 29
#include <lemon/core.h>
30 30

	
31 31
namespace lemon {
32 32
  namespace concepts {
33 33

	
34 34
    /// \ingroup graph_concepts
35 35
    ///
36 36
    /// \brief Class describing the concept of undirected graphs.
37 37
    ///
38 38
    /// This class describes the common interface of all undirected
39 39
    /// graphs.
40 40
    ///
41 41
    /// Like all concept classes, it only provides an interface
42 42
    /// without any sensible implementation. So any general algorithm for
43 43
    /// undirected graphs should compile with this class, but it will not
44 44
    /// run properly, of course.
45 45
    /// An actual graph implementation like \ref ListGraph or
46 46
    /// \ref SmartGraph may have additional functionality.    
47 47
    ///
48 48
    /// The undirected graphs also fulfill the concept of \ref Digraph
49 49
    /// "directed graphs", since each edge can also be regarded as two
50 50
    /// oppositely directed arcs.
51 51
    /// Undirected graphs provide an Edge type for the undirected edges and
52 52
    /// an Arc type for the directed arcs. The Arc type is convertible to
53 53
    /// Edge or inherited from it, i.e. the corresponding edge can be
54 54
    /// obtained from an arc.
55 55
    /// EdgeIt and EdgeMap classes can be used for the edges, while ArcIt
56 56
    /// and ArcMap classes can be used for the arcs (just like in digraphs).
57 57
    /// Both InArcIt and OutArcIt iterates on the same edges but with
58 58
    /// opposite direction. IncEdgeIt also iterates on the same edges
59 59
    /// as OutArcIt and InArcIt, but it is not convertible to Arc,
60 60
    /// only to Edge.
61 61
    ///
62 62
    /// In LEMON, each undirected edge has an inherent orientation.
63 63
    /// Thus it can defined if an arc is forward or backward oriented in
64 64
    /// an undirected graph with respect to this default oriantation of
65 65
    /// the represented edge.
66 66
    /// With the direction() and direct() functions the direction
67 67
    /// of an arc can be obtained and set, respectively.
68 68
    ///
69 69
    /// Only nodes and edges can be added to or removed from an undirected
70 70
    /// graph and the corresponding arcs are added or removed automatically.
71 71
    ///
72 72
    /// \sa Digraph
73 73
    class Graph {
74 74
    private:
75 75
      /// Graphs are \e not copy constructible. Use DigraphCopy instead.
76 76
      Graph(const Graph&) {}
77 77
      /// \brief Assignment of a graph to another one is \e not allowed.
78 78
      /// Use DigraphCopy instead.
79 79
      void operator=(const Graph&) {}
80 80

	
81 81
    public:
82 82
      /// Default constructor.
83 83
      Graph() {}
84 84

	
85 85
      /// \brief Undirected graphs should be tagged with \c UndirectedTag.
86 86
      ///
87 87
      /// Undirected graphs should be tagged with \c UndirectedTag.
88 88
      /// 
89 89
      /// This tag helps the \c enable_if technics to make compile time
90 90
      /// specializations for undirected graphs.
91 91
      typedef True UndirectedTag;
92 92

	
93 93
      /// The node type of the graph
94 94

	
95 95
      /// This class identifies a node of the graph. It also serves
96 96
      /// as a base class of the node iterators,
97 97
      /// thus they convert to this type.
98 98
      class Node {
99 99
      public:
100 100
        /// Default constructor
101 101

	
102 102
        /// Default constructor.
103 103
        /// \warning It sets the object to an undefined value.
104 104
        Node() { }
105 105
        /// Copy constructor.
106 106

	
107 107
        /// Copy constructor.
108 108
        ///
109 109
        Node(const Node&) { }
110 110

	
111 111
        /// %Invalid constructor \& conversion.
112 112

	
113 113
        /// Initializes the object to be invalid.
114 114
        /// \sa Invalid for more details.
115 115
        Node(Invalid) { }
116 116
        /// Equality operator
117 117

	
118 118
        /// Equality operator.
119 119
        ///
120 120
        /// Two iterators are equal if and only if they point to the
121 121
        /// same object or both are \c INVALID.
122 122
        bool operator==(Node) const { return true; }
123 123

	
124 124
        /// Inequality operator
125 125

	
126 126
        /// Inequality operator.
127 127
        bool operator!=(Node) const { return true; }
128 128

	
129 129
        /// Artificial ordering operator.
130 130

	
131 131
        /// Artificial ordering operator.
132 132
        ///
133 133
        /// \note This operator only has to define some strict ordering of
134 134
        /// the items; this order has nothing to do with the iteration
135 135
        /// ordering of the items.
136 136
        bool operator<(Node) const { return false; }
137 137

	
138 138
      };
139 139

	
140 140
      /// Iterator class for the nodes.
141 141

	
142 142
      /// This iterator goes through each node of the graph.
143
      /// Its usage is quite simple, for example you can count the number
143
      /// Its usage is quite simple, for example, you can count the number
144 144
      /// of nodes in a graph \c g of type \c %Graph like this:
145 145
      ///\code
146 146
      /// int count=0;
147 147
      /// for (Graph::NodeIt n(g); n!=INVALID; ++n) ++count;
148 148
      ///\endcode
149 149
      class NodeIt : public Node {
150 150
      public:
151 151
        /// Default constructor
152 152

	
153 153
        /// Default constructor.
154 154
        /// \warning It sets the iterator to an undefined value.
155 155
        NodeIt() { }
156 156
        /// Copy constructor.
157 157

	
158 158
        /// Copy constructor.
159 159
        ///
160 160
        NodeIt(const NodeIt& n) : Node(n) { }
161 161
        /// %Invalid constructor \& conversion.
162 162

	
163 163
        /// Initializes the iterator to be invalid.
164 164
        /// \sa Invalid for more details.
165 165
        NodeIt(Invalid) { }
166 166
        /// Sets the iterator to the first node.
167 167

	
168 168
        /// Sets the iterator to the first node of the given digraph.
169 169
        ///
170 170
        explicit NodeIt(const Graph&) { }
171 171
        /// Sets the iterator to the given node.
172 172

	
173 173
        /// Sets the iterator to the given node of the given digraph.
174 174
        ///
175 175
        NodeIt(const Graph&, const Node&) { }
176 176
        /// Next node.
177 177

	
178 178
        /// Assign the iterator to the next node.
179 179
        ///
180 180
        NodeIt& operator++() { return *this; }
181 181
      };
182 182

	
183 183

	
184 184
      /// The edge type of the graph
185 185

	
186 186
      /// This class identifies an edge of the graph. It also serves
187 187
      /// as a base class of the edge iterators,
188 188
      /// thus they will convert to this type.
189 189
      class Edge {
190 190
      public:
191 191
        /// Default constructor
192 192

	
193 193
        /// Default constructor.
194 194
        /// \warning It sets the object to an undefined value.
195 195
        Edge() { }
196 196
        /// Copy constructor.
197 197

	
198 198
        /// Copy constructor.
199 199
        ///
200 200
        Edge(const Edge&) { }
201 201
        /// %Invalid constructor \& conversion.
202 202

	
203 203
        /// Initializes the object to be invalid.
204 204
        /// \sa Invalid for more details.
205 205
        Edge(Invalid) { }
206 206
        /// Equality operator
207 207

	
208 208
        /// Equality operator.
209 209
        ///
210 210
        /// Two iterators are equal if and only if they point to the
211 211
        /// same object or both are \c INVALID.
212 212
        bool operator==(Edge) const { return true; }
213 213
        /// Inequality operator
214 214

	
215 215
        /// Inequality operator.
216 216
        bool operator!=(Edge) const { return true; }
217 217

	
218 218
        /// Artificial ordering operator.
219 219

	
220 220
        /// Artificial ordering operator.
221 221
        ///
222 222
        /// \note This operator only has to define some strict ordering of
223 223
        /// the edges; this order has nothing to do with the iteration
224 224
        /// ordering of the edges.
225 225
        bool operator<(Edge) const { return false; }
226 226
      };
227 227

	
228 228
      /// Iterator class for the edges.
229 229

	
230 230
      /// This iterator goes through each edge of the graph.
231
      /// Its usage is quite simple, for example you can count the number
231
      /// Its usage is quite simple, for example, you can count the number
232 232
      /// of edges in a graph \c g of type \c %Graph as follows:
233 233
      ///\code
234 234
      /// int count=0;
235 235
      /// for(Graph::EdgeIt e(g); e!=INVALID; ++e) ++count;
236 236
      ///\endcode
237 237
      class EdgeIt : public Edge {
238 238
      public:
239 239
        /// Default constructor
240 240

	
241 241
        /// Default constructor.
242 242
        /// \warning It sets the iterator to an undefined value.
243 243
        EdgeIt() { }
244 244
        /// Copy constructor.
245 245

	
246 246
        /// Copy constructor.
247 247
        ///
248 248
        EdgeIt(const EdgeIt& e) : Edge(e) { }
249 249
        /// %Invalid constructor \& conversion.
250 250

	
251 251
        /// Initializes the iterator to be invalid.
252 252
        /// \sa Invalid for more details.
253 253
        EdgeIt(Invalid) { }
254 254
        /// Sets the iterator to the first edge.
255 255

	
256 256
        /// Sets the iterator to the first edge of the given graph.
257 257
        ///
258 258
        explicit EdgeIt(const Graph&) { }
259 259
        /// Sets the iterator to the given edge.
260 260

	
261 261
        /// Sets the iterator to the given edge of the given graph.
262 262
        ///
263 263
        EdgeIt(const Graph&, const Edge&) { }
264 264
        /// Next edge
265 265

	
266 266
        /// Assign the iterator to the next edge.
267 267
        ///
268 268
        EdgeIt& operator++() { return *this; }
269 269
      };
270 270

	
271 271
      /// Iterator class for the incident edges of a node.
272 272

	
273 273
      /// This iterator goes trough the incident undirected edges
274 274
      /// of a certain node of a graph.
275
      /// Its usage is quite simple, for example you can compute the
275
      /// Its usage is quite simple, for example, you can compute the
276 276
      /// degree (i.e. the number of incident edges) of a node \c n
277 277
      /// in a graph \c g of type \c %Graph as follows.
278 278
      ///
279 279
      ///\code
280 280
      /// int count=0;
281 281
      /// for(Graph::IncEdgeIt e(g, n); e!=INVALID; ++e) ++count;
282 282
      ///\endcode
283 283
      ///
284 284
      /// \warning Loop edges will be iterated twice.
285 285
      class IncEdgeIt : public Edge {
286 286
      public:
287 287
        /// Default constructor
288 288

	
289 289
        /// Default constructor.
290 290
        /// \warning It sets the iterator to an undefined value.
291 291
        IncEdgeIt() { }
292 292
        /// Copy constructor.
293 293

	
294 294
        /// Copy constructor.
295 295
        ///
296 296
        IncEdgeIt(const IncEdgeIt& e) : Edge(e) { }
297 297
        /// %Invalid constructor \& conversion.
298 298

	
299 299
        /// Initializes the iterator to be invalid.
300 300
        /// \sa Invalid for more details.
301 301
        IncEdgeIt(Invalid) { }
302 302
        /// Sets the iterator to the first incident edge.
303 303

	
304 304
        /// Sets the iterator to the first incident edge of the given node.
305 305
        ///
306 306
        IncEdgeIt(const Graph&, const Node&) { }
307 307
        /// Sets the iterator to the given edge.
308 308

	
309 309
        /// Sets the iterator to the given edge of the given graph.
310 310
        ///
311 311
        IncEdgeIt(const Graph&, const Edge&) { }
312 312
        /// Next incident edge
313 313

	
314 314
        /// Assign the iterator to the next incident edge
315 315
        /// of the corresponding node.
316 316
        IncEdgeIt& operator++() { return *this; }
317 317
      };
318 318

	
319 319
      /// The arc type of the graph
320 320

	
321 321
      /// This class identifies a directed arc of the graph. It also serves
322 322
      /// as a base class of the arc iterators,
323 323
      /// thus they will convert to this type.
324 324
      class Arc {
325 325
      public:
326 326
        /// Default constructor
327 327

	
328 328
        /// Default constructor.
329 329
        /// \warning It sets the object to an undefined value.
330 330
        Arc() { }
331 331
        /// Copy constructor.
332 332

	
333 333
        /// Copy constructor.
334 334
        ///
335 335
        Arc(const Arc&) { }
336 336
        /// %Invalid constructor \& conversion.
337 337

	
338 338
        /// Initializes the object to be invalid.
339 339
        /// \sa Invalid for more details.
340 340
        Arc(Invalid) { }
341 341
        /// Equality operator
342 342

	
343 343
        /// Equality operator.
344 344
        ///
345 345
        /// Two iterators are equal if and only if they point to the
346 346
        /// same object or both are \c INVALID.
347 347
        bool operator==(Arc) const { return true; }
348 348
        /// Inequality operator
349 349

	
350 350
        /// Inequality operator.
351 351
        bool operator!=(Arc) const { return true; }
352 352

	
353 353
        /// Artificial ordering operator.
354 354

	
355 355
        /// Artificial ordering operator.
356 356
        ///
357 357
        /// \note This operator only has to define some strict ordering of
358 358
        /// the arcs; this order has nothing to do with the iteration
359 359
        /// ordering of the arcs.
360 360
        bool operator<(Arc) const { return false; }
361 361

	
362 362
        /// Converison to \c Edge
363 363
        
364 364
        /// Converison to \c Edge.
365 365
        ///
366 366
        operator Edge() const { return Edge(); }
367 367
      };
368 368

	
369 369
      /// Iterator class for the arcs.
370 370

	
371 371
      /// This iterator goes through each directed arc of the graph.
372
      /// Its usage is quite simple, for example you can count the number
372
      /// Its usage is quite simple, for example, you can count the number
373 373
      /// of arcs in a graph \c g of type \c %Graph as follows:
374 374
      ///\code
375 375
      /// int count=0;
376 376
      /// for(Graph::ArcIt a(g); a!=INVALID; ++a) ++count;
377 377
      ///\endcode
378 378
      class ArcIt : public Arc {
379 379
      public:
380 380
        /// Default constructor
381 381

	
382 382
        /// Default constructor.
383 383
        /// \warning It sets the iterator to an undefined value.
384 384
        ArcIt() { }
385 385
        /// Copy constructor.
386 386

	
387 387
        /// Copy constructor.
388 388
        ///
389 389
        ArcIt(const ArcIt& e) : Arc(e) { }
390 390
        /// %Invalid constructor \& conversion.
391 391

	
392 392
        /// Initializes the iterator to be invalid.
393 393
        /// \sa Invalid for more details.
394 394
        ArcIt(Invalid) { }
395 395
        /// Sets the iterator to the first arc.
396 396

	
397 397
        /// Sets the iterator to the first arc of the given graph.
398 398
        ///
399 399
        explicit ArcIt(const Graph &g) { ignore_unused_variable_warning(g); }
400 400
        /// Sets the iterator to the given arc.
401 401

	
402 402
        /// Sets the iterator to the given arc of the given graph.
403 403
        ///
404 404
        ArcIt(const Graph&, const Arc&) { }
405 405
        /// Next arc
406 406

	
407 407
        /// Assign the iterator to the next arc.
408 408
        ///
409 409
        ArcIt& operator++() { return *this; }
410 410
      };
411 411

	
412 412
      /// Iterator class for the outgoing arcs of a node.
413 413

	
414 414
      /// This iterator goes trough the \e outgoing directed arcs of a
415 415
      /// certain node of a graph.
416
      /// Its usage is quite simple, for example you can count the number
416
      /// Its usage is quite simple, for example, you can count the number
417 417
      /// of outgoing arcs of a node \c n
418 418
      /// in a graph \c g of type \c %Graph as follows.
419 419
      ///\code
420 420
      /// int count=0;
421 421
      /// for (Digraph::OutArcIt a(g, n); a!=INVALID; ++a) ++count;
422 422
      ///\endcode
423 423
      class OutArcIt : public Arc {
424 424
      public:
425 425
        /// Default constructor
426 426

	
427 427
        /// Default constructor.
428 428
        /// \warning It sets the iterator to an undefined value.
429 429
        OutArcIt() { }
430 430
        /// Copy constructor.
431 431

	
432 432
        /// Copy constructor.
433 433
        ///
434 434
        OutArcIt(const OutArcIt& e) : Arc(e) { }
435 435
        /// %Invalid constructor \& conversion.
436 436

	
437 437
        /// Initializes the iterator to be invalid.
438 438
        /// \sa Invalid for more details.
439 439
        OutArcIt(Invalid) { }
440 440
        /// Sets the iterator to the first outgoing arc.
441 441

	
442 442
        /// Sets the iterator to the first outgoing arc of the given node.
443 443
        ///
444 444
        OutArcIt(const Graph& n, const Node& g) {
445 445
          ignore_unused_variable_warning(n);
446 446
          ignore_unused_variable_warning(g);
447 447
        }
448 448
        /// Sets the iterator to the given arc.
449 449

	
450 450
        /// Sets the iterator to the given arc of the given graph.
451 451
        ///
452 452
        OutArcIt(const Graph&, const Arc&) { }
453 453
        /// Next outgoing arc
454 454

	
455 455
        /// Assign the iterator to the next
456 456
        /// outgoing arc of the corresponding node.
457 457
        OutArcIt& operator++() { return *this; }
458 458
      };
459 459

	
460 460
      /// Iterator class for the incoming arcs of a node.
461 461

	
462 462
      /// This iterator goes trough the \e incoming directed arcs of a
463 463
      /// certain node of a graph.
464
      /// Its usage is quite simple, for example you can count the number
464
      /// Its usage is quite simple, for example, you can count the number
465 465
      /// of incoming arcs of a node \c n
466 466
      /// in a graph \c g of type \c %Graph as follows.
467 467
      ///\code
468 468
      /// int count=0;
469 469
      /// for (Digraph::InArcIt a(g, n); a!=INVALID; ++a) ++count;
470 470
      ///\endcode
471 471
      class InArcIt : public Arc {
472 472
      public:
473 473
        /// Default constructor
474 474

	
475 475
        /// Default constructor.
476 476
        /// \warning It sets the iterator to an undefined value.
477 477
        InArcIt() { }
478 478
        /// Copy constructor.
479 479

	
480 480
        /// Copy constructor.
481 481
        ///
482 482
        InArcIt(const InArcIt& e) : Arc(e) { }
483 483
        /// %Invalid constructor \& conversion.
484 484

	
485 485
        /// Initializes the iterator to be invalid.
486 486
        /// \sa Invalid for more details.
487 487
        InArcIt(Invalid) { }
488 488
        /// Sets the iterator to the first incoming arc.
489 489

	
490 490
        /// Sets the iterator to the first incoming arc of the given node.
491 491
        ///
492 492
        InArcIt(const Graph& g, const Node& n) {
493 493
          ignore_unused_variable_warning(n);
494 494
          ignore_unused_variable_warning(g);
495 495
        }
496 496
        /// Sets the iterator to the given arc.
497 497

	
498 498
        /// Sets the iterator to the given arc of the given graph.
499 499
        ///
500 500
        InArcIt(const Graph&, const Arc&) { }
501 501
        /// Next incoming arc
502 502

	
503 503
        /// Assign the iterator to the next
504 504
        /// incoming arc of the corresponding node.
505 505
        InArcIt& operator++() { return *this; }
506 506
      };
507 507

	
508 508
      /// \brief Standard graph map type for the nodes.
509 509
      ///
510 510
      /// Standard graph map type for the nodes.
511 511
      /// It conforms to the ReferenceMap concept.
512 512
      template<class T>
513 513
      class NodeMap : public ReferenceMap<Node, T, T&, const T&>
514 514
      {
515 515
      public:
516 516

	
517 517
        /// Constructor
518 518
        explicit NodeMap(const Graph&) { }
519 519
        /// Constructor with given initial value
520 520
        NodeMap(const Graph&, T) { }
521 521

	
522 522
      private:
523 523
        ///Copy constructor
524 524
        NodeMap(const NodeMap& nm) :
525 525
          ReferenceMap<Node, T, T&, const T&>(nm) { }
526 526
        ///Assignment operator
527 527
        template <typename CMap>
528 528
        NodeMap& operator=(const CMap&) {
529 529
          checkConcept<ReadMap<Node, T>, CMap>();
530 530
          return *this;
531 531
        }
532 532
      };
533 533

	
534 534
      /// \brief Standard graph map type for the arcs.
535 535
      ///
536 536
      /// Standard graph map type for the arcs.
537 537
      /// It conforms to the ReferenceMap concept.
538 538
      template<class T>
539 539
      class ArcMap : public ReferenceMap<Arc, T, T&, const T&>
540 540
      {
541 541
      public:
542 542

	
543 543
        /// Constructor
544 544
        explicit ArcMap(const Graph&) { }
545 545
        /// Constructor with given initial value
546 546
        ArcMap(const Graph&, T) { }
547 547

	
548 548
      private:
549 549
        ///Copy constructor
550 550
        ArcMap(const ArcMap& em) :
551 551
          ReferenceMap<Arc, T, T&, const T&>(em) { }
552 552
        ///Assignment operator
553 553
        template <typename CMap>
554 554
        ArcMap& operator=(const CMap&) {
555 555
          checkConcept<ReadMap<Arc, T>, CMap>();
556 556
          return *this;
557 557
        }
558 558
      };
559 559

	
560 560
      /// \brief Standard graph map type for the edges.
561 561
      ///
562 562
      /// Standard graph map type for the edges.
563 563
      /// It conforms to the ReferenceMap concept.
564 564
      template<class T>
565 565
      class EdgeMap : public ReferenceMap<Edge, T, T&, const T&>
566 566
      {
567 567
      public:
568 568

	
569 569
        /// Constructor
570 570
        explicit EdgeMap(const Graph&) { }
571 571
        /// Constructor with given initial value
572 572
        EdgeMap(const Graph&, T) { }
573 573

	
574 574
      private:
575 575
        ///Copy constructor
576 576
        EdgeMap(const EdgeMap& em) :
577 577
          ReferenceMap<Edge, T, T&, const T&>(em) {}
578 578
        ///Assignment operator
579 579
        template <typename CMap>
580 580
        EdgeMap& operator=(const CMap&) {
581 581
          checkConcept<ReadMap<Edge, T>, CMap>();
582 582
          return *this;
583 583
        }
584 584
      };
585 585

	
586 586
      /// \brief The first node of the edge.
587 587
      ///
588 588
      /// Returns the first node of the given edge.
589 589
      ///
590
      /// Edges don't have source and target nodes, however methods
590
      /// Edges don't have source and target nodes, however, methods
591 591
      /// u() and v() are used to query the two end-nodes of an edge.
592 592
      /// The orientation of an edge that arises this way is called
593 593
      /// the inherent direction, it is used to define the default
594 594
      /// direction for the corresponding arcs.
595 595
      /// \sa v()
596 596
      /// \sa direction()
597 597
      Node u(Edge) const { return INVALID; }
598 598

	
599 599
      /// \brief The second node of the edge.
600 600
      ///
601 601
      /// Returns the second node of the given edge.
602 602
      ///
603
      /// Edges don't have source and target nodes, however methods
603
      /// Edges don't have source and target nodes, however, methods
604 604
      /// u() and v() are used to query the two end-nodes of an edge.
605 605
      /// The orientation of an edge that arises this way is called
606 606
      /// the inherent direction, it is used to define the default
607 607
      /// direction for the corresponding arcs.
608 608
      /// \sa u()
609 609
      /// \sa direction()
610 610
      Node v(Edge) const { return INVALID; }
611 611

	
612 612
      /// \brief The source node of the arc.
613 613
      ///
614 614
      /// Returns the source node of the given arc.
615 615
      Node source(Arc) const { return INVALID; }
616 616

	
617 617
      /// \brief The target node of the arc.
618 618
      ///
619 619
      /// Returns the target node of the given arc.
620 620
      Node target(Arc) const { return INVALID; }
621 621

	
622 622
      /// \brief The ID of the node.
623 623
      ///
624 624
      /// Returns the ID of the given node.
625 625
      int id(Node) const { return -1; }
626 626

	
627 627
      /// \brief The ID of the edge.
628 628
      ///
629 629
      /// Returns the ID of the given edge.
630 630
      int id(Edge) const { return -1; }
631 631

	
632 632
      /// \brief The ID of the arc.
633 633
      ///
634 634
      /// Returns the ID of the given arc.
635 635
      int id(Arc) const { return -1; }
636 636

	
637 637
      /// \brief The node with the given ID.
638 638
      ///
639 639
      /// Returns the node with the given ID.
640 640
      /// \pre The argument should be a valid node ID in the graph.
641 641
      Node nodeFromId(int) const { return INVALID; }
642 642

	
643 643
      /// \brief The edge with the given ID.
644 644
      ///
645 645
      /// Returns the edge with the given ID.
646 646
      /// \pre The argument should be a valid edge ID in the graph.
647 647
      Edge edgeFromId(int) const { return INVALID; }
648 648

	
649 649
      /// \brief The arc with the given ID.
650 650
      ///
651 651
      /// Returns the arc with the given ID.
652 652
      /// \pre The argument should be a valid arc ID in the graph.
653 653
      Arc arcFromId(int) const { return INVALID; }
654 654

	
655 655
      /// \brief An upper bound on the node IDs.
656 656
      ///
657 657
      /// Returns an upper bound on the node IDs.
658 658
      int maxNodeId() const { return -1; }
659 659

	
660 660
      /// \brief An upper bound on the edge IDs.
661 661
      ///
662 662
      /// Returns an upper bound on the edge IDs.
663 663
      int maxEdgeId() const { return -1; }
664 664

	
665 665
      /// \brief An upper bound on the arc IDs.
666 666
      ///
667 667
      /// Returns an upper bound on the arc IDs.
668 668
      int maxArcId() const { return -1; }
669 669

	
670 670
      /// \brief The direction of the arc.
671 671
      ///
672 672
      /// Returns \c true if the direction of the given arc is the same as
673 673
      /// the inherent orientation of the represented edge.
674 674
      bool direction(Arc) const { return true; }
675 675

	
676 676
      /// \brief Direct the edge.
677 677
      ///
678 678
      /// Direct the given edge. The returned arc
679 679
      /// represents the given edge and its direction comes
680 680
      /// from the bool parameter. If it is \c true, then the direction
681 681
      /// of the arc is the same as the inherent orientation of the edge.
682 682
      Arc direct(Edge, bool) const {
683 683
        return INVALID;
684 684
      }
685 685

	
686 686
      /// \brief Direct the edge.
687 687
      ///
688 688
      /// Direct the given edge. The returned arc represents the given
689 689
      /// edge and its source node is the given node.
690 690
      Arc direct(Edge, Node) const {
691 691
        return INVALID;
692 692
      }
693 693

	
694 694
      /// \brief The oppositely directed arc.
695 695
      ///
696 696
      /// Returns the oppositely directed arc representing the same edge.
697 697
      Arc oppositeArc(Arc) const { return INVALID; }
698 698

	
699 699
      /// \brief The opposite node on the edge.
700 700
      ///
701 701
      /// Returns the opposite node on the given edge.
702 702
      Node oppositeNode(Node, Edge) const { return INVALID; }
703 703

	
704 704
      void first(Node&) const {}
705 705
      void next(Node&) const {}
706 706

	
707 707
      void first(Edge&) const {}
708 708
      void next(Edge&) const {}
709 709

	
710 710
      void first(Arc&) const {}
711 711
      void next(Arc&) const {}
712 712

	
713 713
      void firstOut(Arc&, Node) const {}
714 714
      void nextOut(Arc&) const {}
715 715

	
716 716
      void firstIn(Arc&, Node) const {}
717 717
      void nextIn(Arc&) const {}
718 718

	
719 719
      void firstInc(Edge &, bool &, const Node &) const {}
720 720
      void nextInc(Edge &, bool &) const {}
721 721

	
722 722
      // The second parameter is dummy.
723 723
      Node fromId(int, Node) const { return INVALID; }
724 724
      // The second parameter is dummy.
725 725
      Edge fromId(int, Edge) const { return INVALID; }
726 726
      // The second parameter is dummy.
727 727
      Arc fromId(int, Arc) const { return INVALID; }
728 728

	
729 729
      // Dummy parameter.
730 730
      int maxId(Node) const { return -1; }
731 731
      // Dummy parameter.
732 732
      int maxId(Edge) const { return -1; }
733 733
      // Dummy parameter.
734 734
      int maxId(Arc) const { return -1; }
735 735

	
736 736
      /// \brief The base node of the iterator.
737 737
      ///
738 738
      /// Returns the base node of the given incident edge iterator.
739 739
      Node baseNode(IncEdgeIt) const { return INVALID; }
740 740

	
741 741
      /// \brief The running node of the iterator.
742 742
      ///
743 743
      /// Returns the running node of the given incident edge iterator.
744 744
      Node runningNode(IncEdgeIt) const { return INVALID; }
745 745

	
746 746
      /// \brief The base node of the iterator.
747 747
      ///
748 748
      /// Returns the base node of the given outgoing arc iterator
749 749
      /// (i.e. the source node of the corresponding arc).
750 750
      Node baseNode(OutArcIt) const { return INVALID; }
751 751

	
752 752
      /// \brief The running node of the iterator.
753 753
      ///
754 754
      /// Returns the running node of the given outgoing arc iterator
755 755
      /// (i.e. the target node of the corresponding arc).
756 756
      Node runningNode(OutArcIt) const { return INVALID; }
757 757

	
758 758
      /// \brief The base node of the iterator.
759 759
      ///
760 760
      /// Returns the base node of the given incomming arc iterator
761 761
      /// (i.e. the target node of the corresponding arc).
762 762
      Node baseNode(InArcIt) const { return INVALID; }
763 763

	
764 764
      /// \brief The running node of the iterator.
765 765
      ///
766 766
      /// Returns the running node of the given incomming arc iterator
767 767
      /// (i.e. the source node of the corresponding arc).
768 768
      Node runningNode(InArcIt) const { return INVALID; }
769 769

	
770 770
      template <typename _Graph>
771 771
      struct Constraints {
772 772
        void constraints() {
773 773
          checkConcept<BaseGraphComponent, _Graph>();
774 774
          checkConcept<IterableGraphComponent<>, _Graph>();
775 775
          checkConcept<IDableGraphComponent<>, _Graph>();
776 776
          checkConcept<MappableGraphComponent<>, _Graph>();
777 777
        }
778 778
      };
779 779

	
780 780
    };
781 781

	
782 782
  }
783 783

	
784 784
}
785 785

	
786 786
#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-2009
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
///\brief The concept of graph components.
21
///\brief The concepts of graph components.
22 22

	
23 23
#ifndef LEMON_CONCEPTS_GRAPH_COMPONENTS_H
24 24
#define LEMON_CONCEPTS_GRAPH_COMPONENTS_H
25 25

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

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

	
31 31
namespace lemon {
32 32
  namespace concepts {
33 33

	
34 34
    /// \brief Concept class for \c Node, \c Arc and \c Edge types.
35 35
    ///
36 36
    /// This class describes the concept of \c Node, \c Arc and \c Edge
37 37
    /// subtypes of digraph and graph types.
38 38
    ///
39 39
    /// \note This class is a template class so that we can use it to
40 40
    /// create graph skeleton classes. The reason for this is that \c Node
41 41
    /// and \c Arc (or \c Edge) types should \e not derive from the same 
42 42
    /// base class. For \c Node you should instantiate it with character
43 43
    /// \c 'n', for \c Arc with \c 'a' and for \c Edge with \c 'e'.
44 44
#ifndef DOXYGEN
45 45
    template <char sel = '0'>
46 46
#endif
47 47
    class GraphItem {
48 48
    public:
49 49
      /// \brief Default constructor.
50 50
      ///
51 51
      /// Default constructor.
52 52
      /// \warning The default constructor is not required to set
53 53
      /// the item to some well-defined value. So you should consider it
54 54
      /// as uninitialized.
55 55
      GraphItem() {}
56 56

	
57 57
      /// \brief Copy constructor.
58 58
      ///
59 59
      /// Copy constructor.
60 60
      GraphItem(const GraphItem &) {}
61 61

	
62 62
      /// \brief Constructor for conversion from \c INVALID.
63 63
      ///
64 64
      /// Constructor for conversion from \c INVALID.
65 65
      /// It initializes the item to be invalid.
66 66
      /// \sa Invalid for more details.
67 67
      GraphItem(Invalid) {}
68 68

	
69 69
      /// \brief Assignment operator.
70 70
      ///
71 71
      /// Assignment operator for the item.
72 72
      GraphItem& operator=(const GraphItem&) { return *this; }
73 73

	
74 74
      /// \brief Assignment operator for INVALID.
75 75
      ///
76 76
      /// This operator makes the item invalid.
77 77
      GraphItem& operator=(Invalid) { return *this; }
78 78

	
79 79
      /// \brief Equality operator.
80 80
      ///
81 81
      /// Equality operator.
82 82
      bool operator==(const GraphItem&) const { return false; }
83 83

	
84 84
      /// \brief Inequality operator.
85 85
      ///
86 86
      /// Inequality operator.
87 87
      bool operator!=(const GraphItem&) const { return false; }
88 88

	
89 89
      /// \brief Ordering operator.
90 90
      ///
91 91
      /// This operator defines an ordering of the items.
92 92
      /// It makes possible to use graph item types as key types in 
93 93
      /// associative containers (e.g. \c std::map).
94 94
      ///
95 95
      /// \note This operator only has to define some strict ordering of
96 96
      /// the items; this order has nothing to do with the iteration
97 97
      /// ordering of the items.
98 98
      bool operator<(const GraphItem&) const { return false; }
99 99

	
100 100
      template<typename _GraphItem>
101 101
      struct Constraints {
102 102
        void constraints() {
103 103
          _GraphItem i1;
104 104
          i1=INVALID;
105 105
          _GraphItem i2 = i1;
106 106
          _GraphItem i3 = INVALID;
107 107

	
108 108
          i1 = i2 = i3;
109 109

	
110 110
          bool b;
111 111
          b = (ia == ib) && (ia != ib);
112 112
          b = (ia == INVALID) && (ib != INVALID);
113 113
          b = (ia < ib);
114 114
        }
115 115

	
116 116
        const _GraphItem &ia;
117 117
        const _GraphItem &ib;
118 118
      };
119 119
    };
120 120

	
121 121
    /// \brief Base skeleton class for directed graphs.
122 122
    ///
123 123
    /// This class describes the base interface of directed graph types.
124 124
    /// All digraph %concepts have to conform to this class.
125 125
    /// It just provides types for nodes and arcs and functions 
126 126
    /// to get the source and the target nodes of arcs.
127 127
    class BaseDigraphComponent {
128 128
    public:
129 129

	
130 130
      typedef BaseDigraphComponent Digraph;
131 131

	
132 132
      /// \brief Node class of the digraph.
133 133
      ///
134 134
      /// This class represents the nodes of the digraph.
135 135
      typedef GraphItem<'n'> Node;
136 136

	
137 137
      /// \brief Arc class of the digraph.
138 138
      ///
139 139
      /// This class represents the arcs of the digraph.
140 140
      typedef GraphItem<'a'> Arc;
141 141

	
142 142
      /// \brief Return the source node of an arc.
143 143
      ///
144 144
      /// This function returns the source node of an arc.
145 145
      Node source(const Arc&) const { return INVALID; }
146 146

	
147 147
      /// \brief Return the target node of an arc.
148 148
      ///
149 149
      /// This function returns the target node of an arc.
150 150
      Node target(const Arc&) const { return INVALID; }
151 151

	
152 152
      /// \brief Return the opposite node on the given arc.
153 153
      ///
154 154
      /// This function returns the opposite node on the given arc.
155 155
      Node oppositeNode(const Node&, const Arc&) const {
156 156
        return INVALID;
157 157
      }
158 158

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

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

	
176 176
        const _Digraph& digraph;
177 177
      };
178 178
    };
179 179

	
180 180
    /// \brief Base skeleton class for undirected graphs.
181 181
    ///
182 182
    /// This class describes the base interface of undirected graph types.
183 183
    /// All graph %concepts have to conform to this class.
184 184
    /// It extends the interface of \ref BaseDigraphComponent with an
185 185
    /// \c Edge type and functions to get the end nodes of edges,
186 186
    /// to convert from arcs to edges and to get both direction of edges.
187 187
    class BaseGraphComponent : public BaseDigraphComponent {
188 188
    public:
189 189

	
190 190
      typedef BaseGraphComponent Graph;
191 191

	
192 192
      typedef BaseDigraphComponent::Node Node;
193 193
      typedef BaseDigraphComponent::Arc Arc;
194 194

	
195 195
      /// \brief Undirected edge class of the graph.
196 196
      ///
197 197
      /// This class represents the undirected edges of the graph.
198 198
      /// Undirected graphs can be used as directed graphs, each edge is
199 199
      /// represented by two opposite directed arcs.
200 200
      class Edge : public GraphItem<'e'> {
201 201
        typedef GraphItem<'e'> Parent;
202 202

	
203 203
      public:
204 204
        /// \brief Default constructor.
205 205
        ///
206 206
        /// Default constructor.
207 207
        /// \warning The default constructor is not required to set
208 208
        /// the item to some well-defined value. So you should consider it
209 209
        /// as uninitialized.
210 210
        Edge() {}
211 211

	
212 212
        /// \brief Copy constructor.
213 213
        ///
214 214
        /// Copy constructor.
215 215
        Edge(const Edge &) : Parent() {}
216 216

	
217 217
        /// \brief Constructor for conversion from \c INVALID.
218 218
        ///
219 219
        /// Constructor for conversion from \c INVALID.
220 220
        /// It initializes the item to be invalid.
221 221
        /// \sa Invalid for more details.
222 222
        Edge(Invalid) {}
223 223

	
224 224
        /// \brief Constructor for conversion from an arc.
225 225
        ///
226 226
        /// Constructor for conversion from an arc.
227 227
        /// Besides the core graph item functionality each arc should
228 228
        /// be convertible to the represented edge.
229 229
        Edge(const Arc&) {}
230 230
     };
231 231

	
232 232
      /// \brief Return one end node of an edge.
233 233
      ///
234 234
      /// This function returns one end node of an edge.
235 235
      Node u(const Edge&) const { return INVALID; }
236 236

	
237 237
      /// \brief Return the other end node of an edge.
238 238
      ///
239 239
      /// This function returns the other end node of an edge.
240 240
      Node v(const Edge&) const { return INVALID; }
241 241

	
242 242
      /// \brief Return a directed arc related to an edge.
243 243
      ///
244 244
      /// This function returns a directed arc from its direction and the
245 245
      /// represented edge.
246 246
      Arc direct(const Edge&, bool) const { return INVALID; }
247 247

	
248 248
      /// \brief Return a directed arc related to an edge.
249 249
      ///
250 250
      /// This function returns a directed arc from its source node and the
251 251
      /// represented edge.
252 252
      Arc direct(const Edge&, const Node&) const { return INVALID; }
253 253

	
254 254
      /// \brief Return the direction of the arc.
255 255
      ///
256 256
      /// Returns the direction of the arc. Each arc represents an
257 257
      /// edge with a direction. It gives back the
258 258
      /// direction.
259 259
      bool direction(const Arc&) const { return true; }
260 260

	
261 261
      /// \brief Return the opposite arc.
262 262
      ///
263 263
      /// This function returns the opposite arc, i.e. the arc representing
264 264
      /// the same edge and has opposite direction.
265 265
      Arc oppositeArc(const Arc&) const { return INVALID; }
266 266

	
267 267
      template <typename _Graph>
268 268
      struct Constraints {
269 269
        typedef typename _Graph::Node Node;
270 270
        typedef typename _Graph::Arc Arc;
271 271
        typedef typename _Graph::Edge Edge;
272 272

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

	
292 292
        const _Graph& graph;
293 293
      };
294 294

	
295 295
    };
296 296

	
297 297
    /// \brief Skeleton class for \e idable directed graphs.
298 298
    ///
299 299
    /// This class describes the interface of \e idable directed graphs.
300 300
    /// It extends \ref BaseDigraphComponent with the core ID functions.
301 301
    /// The ids of the items must be unique and immutable.
302 302
    /// This concept is part of the Digraph concept.
303 303
    template <typename BAS = BaseDigraphComponent>
304 304
    class IDableDigraphComponent : public BAS {
305 305
    public:
306 306

	
307 307
      typedef BAS Base;
308 308
      typedef typename Base::Node Node;
309 309
      typedef typename Base::Arc Arc;
310 310

	
311 311
      /// \brief Return a unique integer id for the given node.
312 312
      ///
313 313
      /// This function returns a unique integer id for the given node.
314 314
      int id(const Node&) const { return -1; }
315 315

	
316 316
      /// \brief Return the node by its unique id.
317 317
      ///
318 318
      /// This function returns the node by its unique id.
319 319
      /// If the digraph does not contain a node with the given id,
320 320
      /// then the result of the function is undefined.
321 321
      Node nodeFromId(int) const { return INVALID; }
322 322

	
323 323
      /// \brief Return a unique integer id for the given arc.
324 324
      ///
325 325
      /// This function returns a unique integer id for the given arc.
326 326
      int id(const Arc&) const { return -1; }
327 327

	
328 328
      /// \brief Return the arc by its unique id.
329 329
      ///
330 330
      /// This function returns the arc by its unique id.
331 331
      /// If the digraph does not contain an arc with the given id,
332 332
      /// then the result of the function is undefined.
333 333
      Arc arcFromId(int) const { return INVALID; }
334 334

	
335 335
      /// \brief Return an integer greater or equal to the maximum
336 336
      /// node id.
337 337
      ///
338 338
      /// This function returns an integer greater or equal to the
339 339
      /// maximum node id.
340 340
      int maxNodeId() const { return -1; }
341 341

	
342 342
      /// \brief Return an integer greater or equal to the maximum
343 343
      /// arc id.
344 344
      ///
345 345
      /// This function returns an integer greater or equal to the
346 346
      /// maximum arc id.
347 347
      int maxArcId() const { return -1; }
348 348

	
349 349
      template <typename _Digraph>
350 350
      struct Constraints {
351 351

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

	
365 365
          nid = digraph.maxNodeId();
366 366
          ignore_unused_variable_warning(nid);
367 367
          eid = digraph.maxArcId();
368 368
          ignore_unused_variable_warning(eid);
369 369
        }
370 370

	
371 371
        const _Digraph& digraph;
372 372
      };
373 373
    };
374 374

	
375 375
    /// \brief Skeleton class for \e idable undirected graphs.
376 376
    ///
377 377
    /// This class describes the interface of \e idable undirected
378 378
    /// graphs. It extends \ref IDableDigraphComponent with the core ID
379 379
    /// functions of undirected graphs.
380 380
    /// The ids of the items must be unique and immutable.
381 381
    /// This concept is part of the Graph concept.
382 382
    template <typename BAS = BaseGraphComponent>
383 383
    class IDableGraphComponent : public IDableDigraphComponent<BAS> {
384 384
    public:
385 385

	
386 386
      typedef BAS Base;
387 387
      typedef typename Base::Edge Edge;
388 388

	
389 389
      using IDableDigraphComponent<Base>::id;
390 390

	
391 391
      /// \brief Return a unique integer id for the given edge.
392 392
      ///
393 393
      /// This function returns a unique integer id for the given edge.
394 394
      int id(const Edge&) const { return -1; }
395 395

	
396 396
      /// \brief Return the edge by its unique id.
397 397
      ///
398 398
      /// This function returns the edge by its unique id.
399 399
      /// If the graph does not contain an edge with the given id,
400 400
      /// then the result of the function is undefined.
401 401
      Edge edgeFromId(int) const { return INVALID; }
402 402

	
403 403
      /// \brief Return an integer greater or equal to the maximum
404 404
      /// edge id.
405 405
      ///
406 406
      /// This function returns an integer greater or equal to the
407 407
      /// maximum edge id.
408 408
      int maxEdgeId() const { return -1; }
409 409

	
410 410
      template <typename _Graph>
411 411
      struct Constraints {
412 412

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

	
423 423
        const _Graph& graph;
424 424
      };
425 425
    };
426 426

	
427 427
    /// \brief Concept class for \c NodeIt, \c ArcIt and \c EdgeIt types.
428 428
    ///
429 429
    /// This class describes the concept of \c NodeIt, \c ArcIt and 
430 430
    /// \c EdgeIt subtypes of digraph and graph types.
431 431
    template <typename GR, typename Item>
432 432
    class GraphItemIt : public Item {
433 433
    public:
434 434
      /// \brief Default constructor.
435 435
      ///
436 436
      /// Default constructor.
437 437
      /// \warning The default constructor is not required to set
438 438
      /// the iterator to some well-defined value. So you should consider it
439 439
      /// as uninitialized.
440 440
      GraphItemIt() {}
441 441

	
442 442
      /// \brief Copy constructor.
443 443
      ///
444 444
      /// Copy constructor.
445 445
      GraphItemIt(const GraphItemIt& it) : Item(it) {}
446 446

	
447 447
      /// \brief Constructor that sets the iterator to the first item.
448 448
      ///
449 449
      /// Constructor that sets the iterator to the first item.
450 450
      explicit GraphItemIt(const GR&) {}
451 451

	
452 452
      /// \brief Constructor for conversion from \c INVALID.
453 453
      ///
454 454
      /// Constructor for conversion from \c INVALID.
455 455
      /// It initializes the iterator to be invalid.
456 456
      /// \sa Invalid for more details.
457 457
      GraphItemIt(Invalid) {}
458 458

	
459 459
      /// \brief Assignment operator.
460 460
      ///
461 461
      /// Assignment operator for the iterator.
462 462
      GraphItemIt& operator=(const GraphItemIt&) { return *this; }
463 463

	
464 464
      /// \brief Increment the iterator.
465 465
      ///
466 466
      /// This operator increments the iterator, i.e. assigns it to the
467 467
      /// next item.
468 468
      GraphItemIt& operator++() { return *this; }
469 469
 
470 470
      /// \brief Equality operator
471 471
      ///
472 472
      /// Equality operator.
473 473
      /// Two iterators are equal if and only if they point to the
474 474
      /// same object or both are invalid.
475 475
      bool operator==(const GraphItemIt&) const { return true;}
476 476

	
477 477
      /// \brief Inequality operator
478 478
      ///
479 479
      /// Inequality operator.
480 480
      /// Two iterators are equal if and only if they point to the
481 481
      /// same object or both are invalid.
482 482
      bool operator!=(const GraphItemIt&) const { return true;}
483 483

	
484 484
      template<typename _GraphItemIt>
485 485
      struct Constraints {
486 486
        void constraints() {
487 487
          checkConcept<GraphItem<>, _GraphItemIt>();
488 488
          _GraphItemIt it1(g);
489 489
          _GraphItemIt it2;
490 490
          _GraphItemIt it3 = it1;
491 491
          _GraphItemIt it4 = INVALID;
492 492

	
493 493
          it2 = ++it1;
494 494
          ++it2 = it1;
495 495
          ++(++it1);
496 496

	
497 497
          Item bi = it1;
498 498
          bi = it2;
499 499
        }
500 500
        const GR& g;
501 501
      };
502 502
    };
503 503

	
504 504
    /// \brief Concept class for \c InArcIt, \c OutArcIt and 
505 505
    /// \c IncEdgeIt types.
506 506
    ///
507 507
    /// This class describes the concept of \c InArcIt, \c OutArcIt 
508 508
    /// and \c IncEdgeIt subtypes of digraph and graph types.
509 509
    ///
510 510
    /// \note Since these iterator classes do not inherit from the same
511 511
    /// base class, there is an additional template parameter (selector)
512 512
    /// \c sel. For \c InArcIt you should instantiate it with character 
513 513
    /// \c 'i', for \c OutArcIt with \c 'o' and for \c IncEdgeIt with \c 'e'.
514 514
    template <typename GR,
515 515
              typename Item = typename GR::Arc,
516 516
              typename Base = typename GR::Node,
517 517
              char sel = '0'>
518 518
    class GraphIncIt : public Item {
519 519
    public:
520 520
      /// \brief Default constructor.
521 521
      ///
522 522
      /// Default constructor.
523 523
      /// \warning The default constructor is not required to set
524 524
      /// the iterator to some well-defined value. So you should consider it
525 525
      /// as uninitialized.
526 526
      GraphIncIt() {}
527 527

	
528 528
      /// \brief Copy constructor.
529 529
      ///
530 530
      /// Copy constructor.
531 531
      GraphIncIt(const GraphIncIt& it) : Item(it) {}
532 532

	
533 533
      /// \brief Constructor that sets the iterator to the first 
534 534
      /// incoming or outgoing arc.
535 535
      ///
536 536
      /// Constructor that sets the iterator to the first arc 
537 537
      /// incoming to or outgoing from the given node.
538 538
      explicit GraphIncIt(const GR&, const Base&) {}
539 539

	
540 540
      /// \brief Constructor for conversion from \c INVALID.
541 541
      ///
542 542
      /// Constructor for conversion from \c INVALID.
543 543
      /// It initializes the iterator to be invalid.
544 544
      /// \sa Invalid for more details.
545 545
      GraphIncIt(Invalid) {}
546 546

	
547 547
      /// \brief Assignment operator.
548 548
      ///
549 549
      /// Assignment operator for the iterator.
550 550
      GraphIncIt& operator=(const GraphIncIt&) { return *this; }
551 551

	
552 552
      /// \brief Increment the iterator.
553 553
      ///
554 554
      /// This operator increments the iterator, i.e. assigns it to the
555 555
      /// next arc incoming to or outgoing from the given node.
556 556
      GraphIncIt& operator++() { return *this; }
557 557

	
558 558
      /// \brief Equality operator
559 559
      ///
560 560
      /// Equality operator.
561 561
      /// Two iterators are equal if and only if they point to the
562 562
      /// same object or both are invalid.
563 563
      bool operator==(const GraphIncIt&) const { return true;}
564 564

	
565 565
      /// \brief Inequality operator
566 566
      ///
567 567
      /// Inequality operator.
568 568
      /// Two iterators are equal if and only if they point to the
569 569
      /// same object or both are invalid.
570 570
      bool operator!=(const GraphIncIt&) const { return true;}
571 571

	
572 572
      template <typename _GraphIncIt>
573 573
      struct Constraints {
574 574
        void constraints() {
575 575
          checkConcept<GraphItem<sel>, _GraphIncIt>();
576 576
          _GraphIncIt it1(graph, node);
577 577
          _GraphIncIt it2;
578 578
          _GraphIncIt it3 = it1;
579 579
          _GraphIncIt it4 = INVALID;
580 580

	
581 581
          it2 = ++it1;
582 582
          ++it2 = it1;
583 583
          ++(++it1);
584 584
          Item e = it1;
585 585
          e = it2;
586 586
        }
587 587
        const Base& node;
588 588
        const GR& graph;
589 589
      };
590 590
    };
591 591

	
592 592
    /// \brief Skeleton class for iterable directed graphs.
593 593
    ///
594 594
    /// This class describes the interface of iterable directed
595 595
    /// graphs. It extends \ref BaseDigraphComponent with the core
596 596
    /// iterable interface.
597 597
    /// This concept is part of the Digraph concept.
598 598
    template <typename BAS = BaseDigraphComponent>
599 599
    class IterableDigraphComponent : public BAS {
600 600

	
601 601
    public:
602 602

	
603 603
      typedef BAS Base;
604 604
      typedef typename Base::Node Node;
605 605
      typedef typename Base::Arc Arc;
606 606

	
607 607
      typedef IterableDigraphComponent Digraph;
608 608

	
609 609
      /// \name Base Iteration
610 610
      ///
611 611
      /// This interface provides functions for iteration on digraph items.
612 612
      ///
613 613
      /// @{
614 614

	
615 615
      /// \brief Return the first node.
616 616
      ///
617 617
      /// This function gives back the first node in the iteration order.
618 618
      void first(Node&) const {}
619 619

	
620 620
      /// \brief Return the next node.
621 621
      ///
622 622
      /// This function gives back the next node in the iteration order.
623 623
      void next(Node&) const {}
624 624

	
625 625
      /// \brief Return the first arc.
626 626
      ///
627 627
      /// This function gives back the first arc in the iteration order.
628 628
      void first(Arc&) const {}
629 629

	
630 630
      /// \brief Return the next arc.
631 631
      ///
632 632
      /// This function gives back the next arc in the iteration order.
633 633
      void next(Arc&) const {}
634 634

	
635 635
      /// \brief Return the first arc incomming to the given node.
636 636
      ///
637 637
      /// This function gives back the first arc incomming to the
638 638
      /// given node.
639 639
      void firstIn(Arc&, const Node&) const {}
640 640

	
641 641
      /// \brief Return the next arc incomming to the given node.
642 642
      ///
643 643
      /// This function gives back the next arc incomming to the
644 644
      /// given node.
645 645
      void nextIn(Arc&) const {}
646 646

	
647 647
      /// \brief Return the first arc outgoing form the given node.
648 648
      ///
649 649
      /// This function gives back the first arc outgoing form the
650 650
      /// given node.
651 651
      void firstOut(Arc&, const Node&) const {}
652 652

	
653 653
      /// \brief Return the next arc outgoing form the given node.
654 654
      ///
655 655
      /// This function gives back the next arc outgoing form the
656 656
      /// given node.
657 657
      void nextOut(Arc&) const {}
658 658

	
659 659
      /// @}
660 660

	
661 661
      /// \name Class Based Iteration
662 662
      ///
663 663
      /// This interface provides iterator classes for digraph items.
664 664
      ///
665 665
      /// @{
666 666

	
667 667
      /// \brief This iterator goes through each node.
668 668
      ///
669 669
      /// This iterator goes through each node.
670 670
      ///
671 671
      typedef GraphItemIt<Digraph, Node> NodeIt;
672 672

	
673 673
      /// \brief This iterator goes through each arc.
674 674
      ///
675 675
      /// This iterator goes through each arc.
676 676
      ///
677 677
      typedef GraphItemIt<Digraph, Arc> ArcIt;
678 678

	
679 679
      /// \brief This iterator goes trough the incoming arcs of a node.
680 680
      ///
681 681
      /// This iterator goes trough the \e incoming arcs of a certain node
682 682
      /// of a digraph.
683 683
      typedef GraphIncIt<Digraph, Arc, Node, 'i'> InArcIt;
684 684

	
685 685
      /// \brief This iterator goes trough the outgoing arcs of a node.
686 686
      ///
687 687
      /// This iterator goes trough the \e outgoing arcs of a certain node
688 688
      /// of a digraph.
689 689
      typedef GraphIncIt<Digraph, Arc, Node, 'o'> OutArcIt;
690 690

	
691 691
      /// \brief The base node of the iterator.
692 692
      ///
693 693
      /// This function gives back the base node of the iterator.
694 694
      /// It is always the target node of the pointed arc.
695 695
      Node baseNode(const InArcIt&) const { return INVALID; }
696 696

	
697 697
      /// \brief The running node of the iterator.
698 698
      ///
699 699
      /// This function gives back the running node of the iterator.
700 700
      /// It is always the source node of the pointed arc.
701 701
      Node runningNode(const InArcIt&) const { return INVALID; }
702 702

	
703 703
      /// \brief The base node of the iterator.
704 704
      ///
705 705
      /// This function gives back the base node of the iterator.
706 706
      /// It is always the source node of the pointed arc.
707 707
      Node baseNode(const OutArcIt&) const { return INVALID; }
708 708

	
709 709
      /// \brief The running node of the iterator.
710 710
      ///
711 711
      /// This function gives back the running node of the iterator.
712 712
      /// It is always the target node of the pointed arc.
713 713
      Node runningNode(const OutArcIt&) const { return INVALID; }
714 714

	
715 715
      /// @}
716 716

	
717 717
      template <typename _Digraph>
718 718
      struct Constraints {
719 719
        void constraints() {
720 720
          checkConcept<Base, _Digraph>();
721 721

	
722 722
          {
723 723
            typename _Digraph::Node node(INVALID);
724 724
            typename _Digraph::Arc arc(INVALID);
725 725
            {
726 726
              digraph.first(node);
727 727
              digraph.next(node);
728 728
            }
729 729
            {
730 730
              digraph.first(arc);
731 731
              digraph.next(arc);
732 732
            }
733 733
            {
734 734
              digraph.firstIn(arc, node);
735 735
              digraph.nextIn(arc);
736 736
            }
737 737
            {
738 738
              digraph.firstOut(arc, node);
739 739
              digraph.nextOut(arc);
740 740
            }
741 741
          }
742 742

	
743 743
          {
744 744
            checkConcept<GraphItemIt<_Digraph, typename _Digraph::Arc>,
745 745
              typename _Digraph::ArcIt >();
746 746
            checkConcept<GraphItemIt<_Digraph, typename _Digraph::Node>,
747 747
              typename _Digraph::NodeIt >();
748 748
            checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc,
749 749
              typename _Digraph::Node, 'i'>, typename _Digraph::InArcIt>();
750 750
            checkConcept<GraphIncIt<_Digraph, typename _Digraph::Arc,
751 751
              typename _Digraph::Node, 'o'>, typename _Digraph::OutArcIt>();
752 752

	
753 753
            typename _Digraph::Node n;
754 754
            const typename _Digraph::InArcIt iait(INVALID);
755 755
            const typename _Digraph::OutArcIt oait(INVALID);
756 756
            n = digraph.baseNode(iait);
757 757
            n = digraph.runningNode(iait);
758 758
            n = digraph.baseNode(oait);
759 759
            n = digraph.runningNode(oait);
760 760
            ignore_unused_variable_warning(n);
761 761
          }
762 762
        }
763 763

	
764 764
        const _Digraph& digraph;
765 765
      };
766 766
    };
767 767

	
768 768
    /// \brief Skeleton class for iterable undirected graphs.
769 769
    ///
770 770
    /// This class describes the interface of iterable undirected
771 771
    /// graphs. It extends \ref IterableDigraphComponent with the core
772 772
    /// iterable interface of undirected graphs.
773 773
    /// This concept is part of the Graph concept.
774 774
    template <typename BAS = BaseGraphComponent>
775 775
    class IterableGraphComponent : public IterableDigraphComponent<BAS> {
776 776
    public:
777 777

	
778 778
      typedef BAS Base;
779 779
      typedef typename Base::Node Node;
780 780
      typedef typename Base::Arc Arc;
781 781
      typedef typename Base::Edge Edge;
782 782

	
783 783

	
784 784
      typedef IterableGraphComponent Graph;
785 785

	
786 786
      /// \name Base Iteration
787 787
      ///
788 788
      /// This interface provides functions for iteration on edges.
789 789
      ///
790 790
      /// @{
791 791

	
792 792
      using IterableDigraphComponent<Base>::first;
793 793
      using IterableDigraphComponent<Base>::next;
794 794

	
795 795
      /// \brief Return the first edge.
796 796
      ///
797 797
      /// This function gives back the first edge in the iteration order.
798 798
      void first(Edge&) const {}
799 799

	
800 800
      /// \brief Return the next edge.
801 801
      ///
802 802
      /// This function gives back the next edge in the iteration order.
803 803
      void next(Edge&) const {}
804 804

	
805 805
      /// \brief Return the first edge incident to the given node.
806 806
      ///
807 807
      /// This function gives back the first edge incident to the given 
808 808
      /// node. The bool parameter gives back the direction for which the
809 809
      /// source node of the directed arc representing the edge is the 
810 810
      /// given node.
811 811
      void firstInc(Edge&, bool&, const Node&) const {}
812 812

	
813 813
      /// \brief Gives back the next of the edges from the
814 814
      /// given node.
815 815
      ///
816 816
      /// This function gives back the next edge incident to the given 
817 817
      /// node. The bool parameter should be used as \c firstInc() use it.
818 818
      void nextInc(Edge&, bool&) const {}
819 819

	
820 820
      using IterableDigraphComponent<Base>::baseNode;
821 821
      using IterableDigraphComponent<Base>::runningNode;
822 822

	
823 823
      /// @}
824 824

	
825 825
      /// \name Class Based Iteration
826 826
      ///
827 827
      /// This interface provides iterator classes for edges.
828 828
      ///
829 829
      /// @{
830 830

	
831 831
      /// \brief This iterator goes through each edge.
832 832
      ///
833 833
      /// This iterator goes through each edge.
834 834
      typedef GraphItemIt<Graph, Edge> EdgeIt;
835 835

	
836 836
      /// \brief This iterator goes trough the incident edges of a
837 837
      /// node.
838 838
      ///
839 839
      /// This iterator goes trough the incident edges of a certain
840 840
      /// node of a graph.
841 841
      typedef GraphIncIt<Graph, Edge, Node, 'e'> IncEdgeIt;
842 842

	
843 843
      /// \brief The base node of the iterator.
844 844
      ///
845 845
      /// This function gives back the base node of the iterator.
846 846
      Node baseNode(const IncEdgeIt&) const { return INVALID; }
847 847

	
848 848
      /// \brief The running node of the iterator.
849 849
      ///
850 850
      /// This function gives back the running node of the iterator.
851 851
      Node runningNode(const IncEdgeIt&) const { return INVALID; }
852 852

	
853 853
      /// @}
854 854

	
855 855
      template <typename _Graph>
856 856
      struct Constraints {
857 857
        void constraints() {
858 858
          checkConcept<IterableDigraphComponent<Base>, _Graph>();
859 859

	
860 860
          {
861 861
            typename _Graph::Node node(INVALID);
862 862
            typename _Graph::Edge edge(INVALID);
863 863
            bool dir;
864 864
            {
865 865
              graph.first(edge);
866 866
              graph.next(edge);
867 867
            }
868 868
            {
869 869
              graph.firstInc(edge, dir, node);
870 870
              graph.nextInc(edge, dir);
871 871
            }
872 872

	
873 873
          }
874 874

	
875 875
          {
876 876
            checkConcept<GraphItemIt<_Graph, typename _Graph::Edge>,
877 877
              typename _Graph::EdgeIt >();
878 878
            checkConcept<GraphIncIt<_Graph, typename _Graph::Edge,
879 879
              typename _Graph::Node, 'e'>, typename _Graph::IncEdgeIt>();
880 880

	
881 881
            typename _Graph::Node n;
882 882
            const typename _Graph::IncEdgeIt ieit(INVALID);
883 883
            n = graph.baseNode(ieit);
884 884
            n = graph.runningNode(ieit);
885 885
          }
886 886
        }
887 887

	
888 888
        const _Graph& graph;
889 889
      };
890 890
    };
891 891

	
892 892
    /// \brief Skeleton class for alterable directed graphs.
893 893
    ///
894 894
    /// This class describes the interface of alterable directed
895 895
    /// graphs. It extends \ref BaseDigraphComponent with the alteration
896 896
    /// notifier interface. It implements
897 897
    /// an observer-notifier pattern for each digraph item. More
898 898
    /// obsevers can be registered into the notifier and whenever an
899 899
    /// alteration occured in the digraph all the observers will be
900 900
    /// notified about it.
901 901
    template <typename BAS = BaseDigraphComponent>
902 902
    class AlterableDigraphComponent : public BAS {
903 903
    public:
904 904

	
905 905
      typedef BAS Base;
906 906
      typedef typename Base::Node Node;
907 907
      typedef typename Base::Arc Arc;
908 908

	
909 909

	
910 910
      /// Node alteration notifier class.
911 911
      typedef AlterationNotifier<AlterableDigraphComponent, Node>
912 912
      NodeNotifier;
913 913
      /// Arc alteration notifier class.
914 914
      typedef AlterationNotifier<AlterableDigraphComponent, Arc>
915 915
      ArcNotifier;
916 916

	
917 917
      /// \brief Return the node alteration notifier.
918 918
      ///
919 919
      /// This function gives back the node alteration notifier.
920 920
      NodeNotifier& notifier(Node) const {
921 921
         return NodeNotifier();
922 922
      }
923 923

	
924 924
      /// \brief Return the arc alteration notifier.
925 925
      ///
926 926
      /// This function gives back the arc alteration notifier.
927 927
      ArcNotifier& notifier(Arc) const {
928 928
        return ArcNotifier();
929 929
      }
930 930

	
931 931
      template <typename _Digraph>
932 932
      struct Constraints {
933 933
        void constraints() {
934 934
          checkConcept<Base, _Digraph>();
935 935
          typename _Digraph::NodeNotifier& nn
936 936
            = digraph.notifier(typename _Digraph::Node());
937 937

	
938 938
          typename _Digraph::ArcNotifier& en
939 939
            = digraph.notifier(typename _Digraph::Arc());
940 940

	
941 941
          ignore_unused_variable_warning(nn);
942 942
          ignore_unused_variable_warning(en);
943 943
        }
944 944

	
945 945
        const _Digraph& digraph;
946 946
      };
947 947
    };
948 948

	
949 949
    /// \brief Skeleton class for alterable undirected graphs.
950 950
    ///
951 951
    /// This class describes the interface of alterable undirected
952 952
    /// graphs. It extends \ref AlterableDigraphComponent with the alteration
953 953
    /// notifier interface of undirected graphs. It implements
954 954
    /// an observer-notifier pattern for the edges. More
955 955
    /// obsevers can be registered into the notifier and whenever an
956 956
    /// alteration occured in the graph all the observers will be
957 957
    /// notified about it.
958 958
    template <typename BAS = BaseGraphComponent>
959 959
    class AlterableGraphComponent : public AlterableDigraphComponent<BAS> {
960 960
    public:
961 961

	
962 962
      typedef BAS Base;
963 963
      typedef typename Base::Edge Edge;
964 964

	
965 965

	
966 966
      /// Edge alteration notifier class.
967 967
      typedef AlterationNotifier<AlterableGraphComponent, Edge>
968 968
      EdgeNotifier;
969 969

	
970 970
      /// \brief Return the edge alteration notifier.
971 971
      ///
972 972
      /// This function gives back the edge alteration notifier.
973 973
      EdgeNotifier& notifier(Edge) const {
974 974
        return EdgeNotifier();
975 975
      }
976 976

	
977 977
      template <typename _Graph>
978 978
      struct Constraints {
979 979
        void constraints() {
980 980
          checkConcept<AlterableDigraphComponent<Base>, _Graph>();
981 981
          typename _Graph::EdgeNotifier& uen
982 982
            = graph.notifier(typename _Graph::Edge());
983 983
          ignore_unused_variable_warning(uen);
984 984
        }
985 985

	
986 986
        const _Graph& graph;
987 987
      };
988 988
    };
989 989

	
990 990
    /// \brief Concept class for standard graph maps.
991 991
    ///
992 992
    /// This class describes the concept of standard graph maps, i.e.
993 993
    /// the \c NodeMap, \c ArcMap and \c EdgeMap subtypes of digraph and 
994 994
    /// graph types, which can be used for associating data to graph items.
995 995
    /// The standard graph maps must conform to the ReferenceMap concept.
996 996
    template <typename GR, typename K, typename V>
997 997
    class GraphMap : public ReferenceMap<K, V, V&, const V&> {
998 998
      typedef ReferenceMap<K, V, V&, const V&> Parent;
999 999

	
1000 1000
    public:
1001 1001

	
1002 1002
      /// The key type of the map.
1003 1003
      typedef K Key;
1004 1004
      /// The value type of the map.
1005 1005
      typedef V Value;
1006 1006
      /// The reference type of the map.
1007 1007
      typedef Value& Reference;
1008 1008
      /// The const reference type of the map.
1009 1009
      typedef const Value& ConstReference;
1010 1010

	
1011 1011
      // The reference map tag.
1012 1012
      typedef True ReferenceMapTag;
1013 1013

	
1014 1014
      /// \brief Construct a new map.
1015 1015
      ///
1016 1016
      /// Construct a new map for the graph.
1017 1017
      explicit GraphMap(const GR&) {}
1018 1018
      /// \brief Construct a new map with default value.
1019 1019
      ///
1020 1020
      /// Construct a new map for the graph and initalize the values.
1021 1021
      GraphMap(const GR&, const Value&) {}
1022 1022

	
1023 1023
    private:
1024 1024
      /// \brief Copy constructor.
1025 1025
      ///
1026 1026
      /// Copy Constructor.
1027 1027
      GraphMap(const GraphMap&) : Parent() {}
1028 1028

	
1029 1029
      /// \brief Assignment operator.
1030 1030
      ///
1031 1031
      /// Assignment operator. It does not mofify the underlying graph,
1032 1032
      /// it just iterates on the current item set and set the  map
1033 1033
      /// with the value returned by the assigned map.
1034 1034
      template <typename CMap>
1035 1035
      GraphMap& operator=(const CMap&) {
1036 1036
        checkConcept<ReadMap<Key, Value>, CMap>();
1037 1037
        return *this;
1038 1038
      }
1039 1039

	
1040 1040
    public:
1041 1041
      template<typename _Map>
1042 1042
      struct Constraints {
1043 1043
        void constraints() {
1044 1044
          checkConcept
1045 1045
            <ReferenceMap<Key, Value, Value&, const Value&>, _Map>();
1046 1046
          _Map m1(g);
1047 1047
          _Map m2(g,t);
1048 1048
          
1049 1049
          // Copy constructor
1050 1050
          // _Map m3(m);
1051 1051

	
1052 1052
          // Assignment operator
1053 1053
          // ReadMap<Key, Value> cmap;
1054 1054
          // m3 = cmap;
1055 1055

	
1056 1056
          ignore_unused_variable_warning(m1);
1057 1057
          ignore_unused_variable_warning(m2);
1058 1058
          // ignore_unused_variable_warning(m3);
1059 1059
        }
1060 1060

	
1061 1061
        const _Map &m;
1062 1062
        const GR &g;
1063 1063
        const typename GraphMap::Value &t;
1064 1064
      };
1065 1065

	
1066 1066
    };
1067 1067

	
1068 1068
    /// \brief Skeleton class for mappable directed graphs.
1069 1069
    ///
1070 1070
    /// This class describes the interface of mappable directed graphs.
1071 1071
    /// It extends \ref BaseDigraphComponent with the standard digraph 
1072 1072
    /// map classes, namely \c NodeMap and \c ArcMap.
1073 1073
    /// This concept is part of the Digraph concept.
1074 1074
    template <typename BAS = BaseDigraphComponent>
1075 1075
    class MappableDigraphComponent : public BAS  {
1076 1076
    public:
1077 1077

	
1078 1078
      typedef BAS Base;
1079 1079
      typedef typename Base::Node Node;
1080 1080
      typedef typename Base::Arc Arc;
1081 1081

	
1082 1082
      typedef MappableDigraphComponent Digraph;
1083 1083

	
1084 1084
      /// \brief Standard graph map for the nodes.
1085 1085
      ///
1086 1086
      /// Standard graph map for the nodes.
1087 1087
      /// It conforms to the ReferenceMap concept.
1088 1088
      template <typename V>
1089 1089
      class NodeMap : public GraphMap<MappableDigraphComponent, Node, V> {
1090 1090
        typedef GraphMap<MappableDigraphComponent, Node, V> Parent;
1091 1091

	
1092 1092
      public:
1093 1093
        /// \brief Construct a new map.
1094 1094
        ///
1095 1095
        /// Construct a new map for the digraph.
1096 1096
        explicit NodeMap(const MappableDigraphComponent& digraph)
1097 1097
          : Parent(digraph) {}
1098 1098

	
1099 1099
        /// \brief Construct a new map with default value.
1100 1100
        ///
1101 1101
        /// Construct a new map for the digraph and initalize the values.
1102 1102
        NodeMap(const MappableDigraphComponent& digraph, const V& value)
1103 1103
          : Parent(digraph, value) {}
1104 1104

	
1105 1105
      private:
1106 1106
        /// \brief Copy constructor.
1107 1107
        ///
1108 1108
        /// Copy Constructor.
1109 1109
        NodeMap(const NodeMap& nm) : Parent(nm) {}
1110 1110

	
1111 1111
        /// \brief Assignment operator.
1112 1112
        ///
1113 1113
        /// Assignment operator.
1114 1114
        template <typename CMap>
1115 1115
        NodeMap& operator=(const CMap&) {
1116 1116
          checkConcept<ReadMap<Node, V>, CMap>();
1117 1117
          return *this;
1118 1118
        }
1119 1119

	
1120 1120
      };
1121 1121

	
1122 1122
      /// \brief Standard graph map for the arcs.
1123 1123
      ///
1124 1124
      /// Standard graph map for the arcs.
1125 1125
      /// It conforms to the ReferenceMap concept.
1126 1126
      template <typename V>
1127 1127
      class ArcMap : public GraphMap<MappableDigraphComponent, Arc, V> {
1128 1128
        typedef GraphMap<MappableDigraphComponent, Arc, V> Parent;
1129 1129

	
1130 1130
      public:
1131 1131
        /// \brief Construct a new map.
1132 1132
        ///
1133 1133
        /// Construct a new map for the digraph.
1134 1134
        explicit ArcMap(const MappableDigraphComponent& digraph)
1135 1135
          : Parent(digraph) {}
1136 1136

	
1137 1137
        /// \brief Construct a new map with default value.
1138 1138
        ///
1139 1139
        /// Construct a new map for the digraph and initalize the values.
1140 1140
        ArcMap(const MappableDigraphComponent& digraph, const V& value)
1141 1141
          : Parent(digraph, value) {}
1142 1142

	
1143 1143
      private:
1144 1144
        /// \brief Copy constructor.
1145 1145
        ///
1146 1146
        /// Copy Constructor.
1147 1147
        ArcMap(const ArcMap& nm) : Parent(nm) {}
1148 1148

	
1149 1149
        /// \brief Assignment operator.
1150 1150
        ///
1151 1151
        /// Assignment operator.
1152 1152
        template <typename CMap>
1153 1153
        ArcMap& operator=(const CMap&) {
1154 1154
          checkConcept<ReadMap<Arc, V>, CMap>();
1155 1155
          return *this;
1156 1156
        }
1157 1157

	
1158 1158
      };
1159 1159

	
1160 1160

	
1161 1161
      template <typename _Digraph>
1162 1162
      struct Constraints {
1163 1163

	
1164 1164
        struct Dummy {
1165 1165
          int value;
1166 1166
          Dummy() : value(0) {}
1167 1167
          Dummy(int _v) : value(_v) {}
1168 1168
        };
1169 1169

	
1170 1170
        void constraints() {
1171 1171
          checkConcept<Base, _Digraph>();
1172 1172
          { // int map test
1173 1173
            typedef typename _Digraph::template NodeMap<int> IntNodeMap;
1174 1174
            checkConcept<GraphMap<_Digraph, typename _Digraph::Node, int>,
1175 1175
              IntNodeMap >();
1176 1176
          } { // bool map test
1177 1177
            typedef typename _Digraph::template NodeMap<bool> BoolNodeMap;
1178 1178
            checkConcept<GraphMap<_Digraph, typename _Digraph::Node, bool>,
1179 1179
              BoolNodeMap >();
1180 1180
          } { // Dummy map test
1181 1181
            typedef typename _Digraph::template NodeMap<Dummy> DummyNodeMap;
1182 1182
            checkConcept<GraphMap<_Digraph, typename _Digraph::Node, Dummy>,
1183 1183
              DummyNodeMap >();
1184 1184
          }
1185 1185

	
1186 1186
          { // int map test
1187 1187
            typedef typename _Digraph::template ArcMap<int> IntArcMap;
1188 1188
            checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, int>,
1189 1189
              IntArcMap >();
1190 1190
          } { // bool map test
1191 1191
            typedef typename _Digraph::template ArcMap<bool> BoolArcMap;
1192 1192
            checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, bool>,
1193 1193
              BoolArcMap >();
1194 1194
          } { // Dummy map test
1195 1195
            typedef typename _Digraph::template ArcMap<Dummy> DummyArcMap;
1196 1196
            checkConcept<GraphMap<_Digraph, typename _Digraph::Arc, Dummy>,
1197 1197
              DummyArcMap >();
1198 1198
          }
1199 1199
        }
1200 1200

	
1201 1201
        const _Digraph& digraph;
1202 1202
      };
1203 1203
    };
1204 1204

	
1205 1205
    /// \brief Skeleton class for mappable undirected graphs.
1206 1206
    ///
1207 1207
    /// This class describes the interface of mappable undirected graphs.
1208 1208
    /// It extends \ref MappableDigraphComponent with the standard graph 
1209 1209
    /// map class for edges (\c EdgeMap).
1210 1210
    /// This concept is part of the Graph concept.
1211 1211
    template <typename BAS = BaseGraphComponent>
1212 1212
    class MappableGraphComponent : public MappableDigraphComponent<BAS>  {
1213 1213
    public:
1214 1214

	
1215 1215
      typedef BAS Base;
1216 1216
      typedef typename Base::Edge Edge;
1217 1217

	
1218 1218
      typedef MappableGraphComponent Graph;
1219 1219

	
1220 1220
      /// \brief Standard graph map for the edges.
1221 1221
      ///
1222 1222
      /// Standard graph map for the edges.
1223 1223
      /// It conforms to the ReferenceMap concept.
1224 1224
      template <typename V>
1225 1225
      class EdgeMap : public GraphMap<MappableGraphComponent, Edge, V> {
1226 1226
        typedef GraphMap<MappableGraphComponent, Edge, V> Parent;
1227 1227

	
1228 1228
      public:
1229 1229
        /// \brief Construct a new map.
1230 1230
        ///
1231 1231
        /// Construct a new map for the graph.
1232 1232
        explicit EdgeMap(const MappableGraphComponent& graph)
1233 1233
          : Parent(graph) {}
1234 1234

	
1235 1235
        /// \brief Construct a new map with default value.
1236 1236
        ///
1237 1237
        /// Construct a new map for the graph and initalize the values.
1238 1238
        EdgeMap(const MappableGraphComponent& graph, const V& value)
1239 1239
          : Parent(graph, value) {}
1240 1240

	
1241 1241
      private:
1242 1242
        /// \brief Copy constructor.
1243 1243
        ///
1244 1244
        /// Copy Constructor.
1245 1245
        EdgeMap(const EdgeMap& nm) : Parent(nm) {}
1246 1246

	
1247 1247
        /// \brief Assignment operator.
1248 1248
        ///
1249 1249
        /// Assignment operator.
1250 1250
        template <typename CMap>
1251 1251
        EdgeMap& operator=(const CMap&) {
1252 1252
          checkConcept<ReadMap<Edge, V>, CMap>();
1253 1253
          return *this;
1254 1254
        }
1255 1255

	
1256 1256
      };
1257 1257

	
1258 1258

	
1259 1259
      template <typename _Graph>
1260 1260
      struct Constraints {
1261 1261

	
1262 1262
        struct Dummy {
1263 1263
          int value;
1264 1264
          Dummy() : value(0) {}
1265 1265
          Dummy(int _v) : value(_v) {}
1266 1266
        };
1267 1267

	
1268 1268
        void constraints() {
1269 1269
          checkConcept<MappableDigraphComponent<Base>, _Graph>();
1270 1270

	
1271 1271
          { // int map test
1272 1272
            typedef typename _Graph::template EdgeMap<int> IntEdgeMap;
1273 1273
            checkConcept<GraphMap<_Graph, typename _Graph::Edge, int>,
1274 1274
              IntEdgeMap >();
1275 1275
          } { // bool map test
1276 1276
            typedef typename _Graph::template EdgeMap<bool> BoolEdgeMap;
1277 1277
            checkConcept<GraphMap<_Graph, typename _Graph::Edge, bool>,
1278 1278
              BoolEdgeMap >();
1279 1279
          } { // Dummy map test
1280 1280
            typedef typename _Graph::template EdgeMap<Dummy> DummyEdgeMap;
1281 1281
            checkConcept<GraphMap<_Graph, typename _Graph::Edge, Dummy>,
1282 1282
              DummyEdgeMap >();
1283 1283
          }
1284 1284
        }
1285 1285

	
1286 1286
        const _Graph& graph;
1287 1287
      };
1288 1288
    };
1289 1289

	
1290 1290
    /// \brief Skeleton class for extendable directed graphs.
1291 1291
    ///
1292 1292
    /// This class describes the interface of extendable directed graphs.
1293 1293
    /// It extends \ref BaseDigraphComponent with functions for adding 
1294 1294
    /// nodes and arcs to the digraph.
1295 1295
    /// This concept requires \ref AlterableDigraphComponent.
1296 1296
    template <typename BAS = BaseDigraphComponent>
1297 1297
    class ExtendableDigraphComponent : public BAS {
1298 1298
    public:
1299 1299
      typedef BAS Base;
1300 1300

	
1301 1301
      typedef typename Base::Node Node;
1302 1302
      typedef typename Base::Arc Arc;
1303 1303

	
1304 1304
      /// \brief Add a new node to the digraph.
1305 1305
      ///
1306 1306
      /// This function adds a new node to the digraph.
1307 1307
      Node addNode() {
1308 1308
        return INVALID;
1309 1309
      }
1310 1310

	
1311 1311
      /// \brief Add a new arc connecting the given two nodes.
1312 1312
      ///
1313 1313
      /// This function adds a new arc connecting the given two nodes
1314 1314
      /// of the digraph.
1315 1315
      Arc addArc(const Node&, const Node&) {
1316 1316
        return INVALID;
1317 1317
      }
1318 1318

	
1319 1319
      template <typename _Digraph>
1320 1320
      struct Constraints {
1321 1321
        void constraints() {
1322 1322
          checkConcept<Base, _Digraph>();
1323 1323
          typename _Digraph::Node node_a, node_b;
1324 1324
          node_a = digraph.addNode();
1325 1325
          node_b = digraph.addNode();
1326 1326
          typename _Digraph::Arc arc;
1327 1327
          arc = digraph.addArc(node_a, node_b);
1328 1328
        }
1329 1329

	
1330 1330
        _Digraph& digraph;
1331 1331
      };
1332 1332
    };
1333 1333

	
1334 1334
    /// \brief Skeleton class for extendable undirected graphs.
1335 1335
    ///
1336 1336
    /// This class describes the interface of extendable undirected graphs.
1337 1337
    /// It extends \ref BaseGraphComponent with functions for adding 
1338 1338
    /// nodes and edges to the graph.
1339 1339
    /// This concept requires \ref AlterableGraphComponent.
1340 1340
    template <typename BAS = BaseGraphComponent>
1341 1341
    class ExtendableGraphComponent : public BAS {
1342 1342
    public:
1343 1343

	
1344 1344
      typedef BAS Base;
1345 1345
      typedef typename Base::Node Node;
1346 1346
      typedef typename Base::Edge Edge;
1347 1347

	
1348 1348
      /// \brief Add a new node to the digraph.
1349 1349
      ///
1350 1350
      /// This function adds a new node to the digraph.
1351 1351
      Node addNode() {
1352 1352
        return INVALID;
1353 1353
      }
1354 1354

	
1355 1355
      /// \brief Add a new edge connecting the given two nodes.
1356 1356
      ///
1357 1357
      /// This function adds a new edge connecting the given two nodes
1358 1358
      /// of the graph.
1359 1359
      Edge addEdge(const Node&, const Node&) {
1360 1360
        return INVALID;
1361 1361
      }
1362 1362

	
1363 1363
      template <typename _Graph>
1364 1364
      struct Constraints {
1365 1365
        void constraints() {
1366 1366
          checkConcept<Base, _Graph>();
1367 1367
          typename _Graph::Node node_a, node_b;
1368 1368
          node_a = graph.addNode();
1369 1369
          node_b = graph.addNode();
1370 1370
          typename _Graph::Edge edge;
1371 1371
          edge = graph.addEdge(node_a, node_b);
1372 1372
        }
1373 1373

	
1374 1374
        _Graph& graph;
1375 1375
      };
1376 1376
    };
1377 1377

	
1378 1378
    /// \brief Skeleton class for erasable directed graphs.
1379 1379
    ///
1380 1380
    /// This class describes the interface of erasable directed graphs.
1381 1381
    /// It extends \ref BaseDigraphComponent with functions for removing 
1382 1382
    /// nodes and arcs from the digraph.
1383 1383
    /// This concept requires \ref AlterableDigraphComponent.
1384 1384
    template <typename BAS = BaseDigraphComponent>
1385 1385
    class ErasableDigraphComponent : public BAS {
1386 1386
    public:
1387 1387

	
1388 1388
      typedef BAS Base;
1389 1389
      typedef typename Base::Node Node;
1390 1390
      typedef typename Base::Arc Arc;
1391 1391

	
1392 1392
      /// \brief Erase a node from the digraph.
1393 1393
      ///
1394 1394
      /// This function erases the given node from the digraph and all arcs 
1395 1395
      /// connected to the node.
1396 1396
      void erase(const Node&) {}
1397 1397

	
1398 1398
      /// \brief Erase an arc from the digraph.
1399 1399
      ///
1400 1400
      /// This function erases the given arc from the digraph.
1401 1401
      void erase(const Arc&) {}
1402 1402

	
1403 1403
      template <typename _Digraph>
1404 1404
      struct Constraints {
1405 1405
        void constraints() {
1406 1406
          checkConcept<Base, _Digraph>();
1407 1407
          const typename _Digraph::Node node(INVALID);
1408 1408
          digraph.erase(node);
1409 1409
          const typename _Digraph::Arc arc(INVALID);
1410 1410
          digraph.erase(arc);
1411 1411
        }
1412 1412

	
1413 1413
        _Digraph& digraph;
1414 1414
      };
1415 1415
    };
1416 1416

	
1417 1417
    /// \brief Skeleton class for erasable undirected graphs.
1418 1418
    ///
1419 1419
    /// This class describes the interface of erasable undirected graphs.
1420 1420
    /// It extends \ref BaseGraphComponent with functions for removing 
1421 1421
    /// nodes and edges from the graph.
1422 1422
    /// This concept requires \ref AlterableGraphComponent.
1423 1423
    template <typename BAS = BaseGraphComponent>
1424 1424
    class ErasableGraphComponent : public BAS {
1425 1425
    public:
1426 1426

	
1427 1427
      typedef BAS Base;
1428 1428
      typedef typename Base::Node Node;
1429 1429
      typedef typename Base::Edge Edge;
1430 1430

	
1431 1431
      /// \brief Erase a node from the graph.
1432 1432
      ///
1433 1433
      /// This function erases the given node from the graph and all edges
1434 1434
      /// connected to the node.
1435 1435
      void erase(const Node&) {}
1436 1436

	
1437 1437
      /// \brief Erase an edge from the digraph.
1438 1438
      ///
1439 1439
      /// This function erases the given edge from the digraph.
1440 1440
      void erase(const Edge&) {}
1441 1441

	
1442 1442
      template <typename _Graph>
1443 1443
      struct Constraints {
1444 1444
        void constraints() {
1445 1445
          checkConcept<Base, _Graph>();
1446 1446
          const typename _Graph::Node node(INVALID);
1447 1447
          graph.erase(node);
1448 1448
          const typename _Graph::Edge edge(INVALID);
1449 1449
          graph.erase(edge);
1450 1450
        }
1451 1451

	
1452 1452
        _Graph& graph;
1453 1453
      };
1454 1454
    };
1455 1455

	
1456 1456
    /// \brief Skeleton class for clearable directed graphs.
1457 1457
    ///
1458 1458
    /// This class describes the interface of clearable directed graphs.
1459 1459
    /// It extends \ref BaseDigraphComponent with a function for clearing
1460 1460
    /// the digraph.
1461 1461
    /// This concept requires \ref AlterableDigraphComponent.
1462 1462
    template <typename BAS = BaseDigraphComponent>
1463 1463
    class ClearableDigraphComponent : public BAS {
1464 1464
    public:
1465 1465

	
1466 1466
      typedef BAS Base;
1467 1467

	
1468 1468
      /// \brief Erase all nodes and arcs from the digraph.
1469 1469
      ///
1470 1470
      /// This function erases all nodes and arcs from the digraph.
1471 1471
      void clear() {}
1472 1472

	
1473 1473
      template <typename _Digraph>
1474 1474
      struct Constraints {
1475 1475
        void constraints() {
1476 1476
          checkConcept<Base, _Digraph>();
1477 1477
          digraph.clear();
1478 1478
        }
1479 1479

	
1480 1480
        _Digraph& digraph;
1481 1481
      };
1482 1482
    };
1483 1483

	
1484 1484
    /// \brief Skeleton class for clearable undirected graphs.
1485 1485
    ///
1486 1486
    /// This class describes the interface of clearable undirected graphs.
1487 1487
    /// It extends \ref BaseGraphComponent with a function for clearing
1488 1488
    /// the graph.
1489 1489
    /// This concept requires \ref AlterableGraphComponent.
1490 1490
    template <typename BAS = BaseGraphComponent>
1491 1491
    class ClearableGraphComponent : public ClearableDigraphComponent<BAS> {
1492 1492
    public:
1493 1493

	
1494 1494
      typedef BAS Base;
1495 1495

	
1496 1496
      /// \brief Erase all nodes and edges from the graph.
1497 1497
      ///
1498 1498
      /// This function erases all nodes and edges from the graph.
1499 1499
      void clear() {}
1500 1500

	
1501 1501
      template <typename _Graph>
1502 1502
      struct Constraints {
1503 1503
        void constraints() {
1504 1504
          checkConcept<Base, _Graph>();
1505 1505
          graph.clear();
1506 1506
        }
1507 1507

	
1508 1508
        _Graph& graph;
1509 1509
      };
1510 1510
    };
1511 1511

	
1512 1512
  }
1513 1513

	
1514 1514
}
1515 1515

	
1516 1516
#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-2009
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_COUNTER_H
20 20
#define LEMON_COUNTER_H
21 21

	
22 22
#include <string>
23 23
#include <iostream>
24 24

	
25 25
///\ingroup timecount
26 26
///\file
27 27
///\brief Tools for counting steps and events
28 28

	
29 29
namespace lemon
30 30
{
31 31

	
32 32
  template<class P> class _NoSubCounter;
33 33

	
34 34
  template<class P>
35 35
  class _SubCounter
36 36
  {
37 37
    P &_parent;
38 38
    std::string _title;
39 39
    std::ostream &_os;
40 40
    int count;
41 41
  public:
42 42

	
43 43
    typedef _SubCounter<_SubCounter<P> > SubCounter;
44 44
    typedef _NoSubCounter<_SubCounter<P> > NoSubCounter;
45 45

	
46 46
    _SubCounter(P &parent)
47 47
      : _parent(parent), _title(), _os(std::cerr), count(0) {}
48 48
    _SubCounter(P &parent,std::string title,std::ostream &os=std::cerr)
49 49
      : _parent(parent), _title(title), _os(os), count(0) {}
50 50
    _SubCounter(P &parent,const char *title,std::ostream &os=std::cerr)
51 51
      : _parent(parent), _title(title), _os(os), count(0) {}
52 52
    ~_SubCounter() {
53 53
      _os << _title << count <<std::endl;
54 54
      _parent+=count;
55 55
    }
56 56
    _SubCounter &operator++() { count++; return *this;}
57 57
    int operator++(int) { return count++; }
58 58
    _SubCounter &operator--() { count--; return *this;}
59 59
    int operator--(int) { return count--; }
60 60
    _SubCounter &operator+=(int c) { count+=c; return *this;}
61 61
    _SubCounter &operator-=(int c) { count-=c; return *this;}
62 62
    operator int() {return count;}
63 63
  };
64 64

	
65 65
  template<class P>
66 66
  class _NoSubCounter
67 67
  {
68 68
    P &_parent;
69 69
  public:
70 70
    typedef _NoSubCounter<_NoSubCounter<P> > SubCounter;
71 71
    typedef _NoSubCounter<_NoSubCounter<P> > NoSubCounter;
72 72

	
73 73
    _NoSubCounter(P &parent) :_parent(parent) {}
74 74
    _NoSubCounter(P &parent,std::string,std::ostream &)
75 75
      :_parent(parent) {}
76 76
    _NoSubCounter(P &parent,std::string)
77 77
      :_parent(parent) {}
78 78
    _NoSubCounter(P &parent,const char *,std::ostream &)
79 79
      :_parent(parent) {}
80 80
    _NoSubCounter(P &parent,const char *)
81 81
      :_parent(parent) {}
82 82
    ~_NoSubCounter() {}
83 83
    _NoSubCounter &operator++() { ++_parent; return *this;}
84 84
    int operator++(int) { _parent++; return 0;}
85 85
    _NoSubCounter &operator--() { --_parent; return *this;}
86 86
    int operator--(int) { _parent--; return 0;}
87 87
    _NoSubCounter &operator+=(int c) { _parent+=c; return *this;}
88 88
    _NoSubCounter &operator-=(int c) { _parent-=c; return *this;}
89 89
    operator int() {return 0;}
90 90
  };
91 91

	
92 92

	
93 93
  /// \addtogroup timecount
94 94
  /// @{
95 95

	
96 96
  /// A counter class
97 97

	
98 98
  /// This class makes it easier to count certain events (e.g. for debug
99 99
  /// reasons).
100 100
  /// You can increment or decrement the counter using \c operator++,
101 101
  /// \c operator--, \c operator+= and \c operator-=. You can also
102 102
  /// define subcounters for the different phases of the algorithm or
103 103
  /// for different types of operations.
104 104
  /// A report containing the given title and the value of the counter
105 105
  /// is automatically printed on destruction.
106 106
  ///
107 107
  /// The following example shows the usage of counters and subcounters.
108 108
  /// \code
109 109
  /// // Bubble sort
110 110
  /// std::vector<T> v;
111 111
  /// ...
112 112
  /// Counter op("Operations: ");
113 113
  /// Counter::SubCounter as(op, "Assignments: ");
114 114
  /// Counter::SubCounter co(op, "Comparisons: ");
115 115
  /// for (int i = v.size()-1; i > 0; --i) {
116 116
  ///   for (int j = 0; j < i; ++j) {
117 117
  ///     if (v[j] > v[j+1]) {
118 118
  ///       T tmp = v[j];
119 119
  ///       v[j] = v[j+1];
120 120
  ///       v[j+1] = tmp;
121 121
  ///       as += 3;          // three assignments
122 122
  ///     }
123 123
  ///     ++co;               // one comparison
124 124
  ///   }
125 125
  /// }
126 126
  /// \endcode
127 127
  ///
128 128
  /// This code prints out something like that:
129 129
  /// \code
130 130
  /// Comparisons: 45
131 131
  /// Assignments: 57
132 132
  /// Operations: 102
133 133
  /// \endcode
134 134
  ///
135 135
  /// \sa NoCounter
136 136
  class Counter
137 137
  {
138 138
    std::string _title;
139 139
    std::ostream &_os;
140 140
    int count;
141 141
  public:
142 142

	
143 143
    /// SubCounter class
144 144

	
145 145
    /// This class can be used to setup subcounters for a \ref Counter
146 146
    /// to have finer reports. A subcounter provides exactly the same
147 147
    /// operations as the main \ref Counter, but it also increments and
148 148
    /// decrements the value of its parent.
149 149
    /// Subcounters can also have subcounters.
150 150
    ///
151 151
    /// The parent counter must be given as the first parameter of the
152 152
    /// constructor. Apart from that a title and an \c ostream object
153 153
    /// can also be given just like for the main \ref Counter.
154 154
    ///
155 155
    /// A report containing the given title and the value of the
156 156
    /// subcounter is automatically printed on destruction. If you
157 157
    /// would like to turn off this report, use \ref NoSubCounter
158 158
    /// instead.
159 159
    ///
160 160
    /// \sa NoSubCounter
161 161
    typedef _SubCounter<Counter> SubCounter;
162 162

	
163 163
    /// SubCounter class without printing report on destruction
164 164

	
165 165
    /// This class can be used to setup subcounters for a \ref Counter.
166 166
    /// It is the same as \ref SubCounter but it does not print report
167 167
    /// on destruction. (It modifies the value of its parent, so 'No'
168 168
    /// only means 'do not print'.)
169 169
    ///
170 170
    /// Replacing \ref SubCounter "SubCounter"s with \ref NoSubCounter
171 171
    /// "NoSubCounter"s makes it possible to turn off reporting
172 172
    /// subcounter values without actually removing the definitions
173 173
    /// and the increment or decrement operators.
174 174
    ///
175 175
    /// \sa SubCounter
176 176
    typedef _NoSubCounter<Counter> NoSubCounter;
177 177

	
178 178
    /// Constructor.
179 179
    Counter() : _title(), _os(std::cerr), count(0) {}
180 180
    /// Constructor.
181 181
    Counter(std::string title,std::ostream &os=std::cerr)
182 182
      : _title(title), _os(os), count(0) {}
183 183
    /// Constructor.
184 184
    Counter(const char *title,std::ostream &os=std::cerr)
185 185
      : _title(title), _os(os), count(0) {}
186 186
    /// Destructor. Prints the given title and the value of the counter.
187 187
    ~Counter() {
188 188
      _os << _title << count <<std::endl;
189 189
    }
190 190
    ///\e
191 191
    Counter &operator++() { count++; return *this;}
192 192
    ///\e
193 193
    int operator++(int) { return count++;}
194 194
    ///\e
195 195
    Counter &operator--() { count--; return *this;}
196 196
    ///\e
197 197
    int operator--(int) { return count--;}
198 198
    ///\e
199 199
    Counter &operator+=(int c) { count+=c; return *this;}
200 200
    ///\e
201 201
    Counter &operator-=(int c) { count-=c; return *this;}
202 202
    /// Resets the counter to the given value.
203 203

	
204 204
    /// Resets the counter to the given value.
205 205
    /// \note This function does not reset the values of
206 206
    /// \ref SubCounter "SubCounter"s but it resets \ref NoSubCounter
207 207
    /// "NoSubCounter"s along with the main counter.
208 208
    void reset(int c=0) {count=c;}
209 209
    /// Returns the value of the counter.
210 210
    operator int() {return count;}
211 211
  };
212 212

	
213 213
  /// 'Do nothing' version of Counter.
214 214

	
215
  /// This class can be used in the same way as \ref Counter however it
215
  /// This class can be used in the same way as \ref Counter, but it
216 216
  /// does not count at all and does not print report on destruction.
217 217
  ///
218 218
  /// Replacing a \ref Counter with a \ref NoCounter makes it possible
219 219
  /// to turn off all counting and reporting (SubCounters should also
220 220
  /// be replaced with NoSubCounters), so it does not affect the
221 221
  /// efficiency of the program at all.
222 222
  ///
223 223
  /// \sa Counter
224 224
  class NoCounter
225 225
  {
226 226
  public:
227 227
    typedef _NoSubCounter<NoCounter> SubCounter;
228 228
    typedef _NoSubCounter<NoCounter> NoSubCounter;
229 229

	
230 230
    NoCounter() {}
231 231
    NoCounter(std::string,std::ostream &) {}
232 232
    NoCounter(const char *,std::ostream &) {}
233 233
    NoCounter(std::string) {}
234 234
    NoCounter(const char *) {}
235 235
    NoCounter &operator++() { return *this; }
236 236
    int operator++(int) { return 0; }
237 237
    NoCounter &operator--() { return *this; }
238 238
    int operator--(int) { return 0; }
239 239
    NoCounter &operator+=(int) { return *this;}
240 240
    NoCounter &operator-=(int) { return *this;}
241 241
    void reset(int) {}
242 242
    void reset() {}
243 243
    operator int() {return 0;}
244 244
  };
245 245

	
246 246
  ///@}
247 247
}
248 248

	
249 249
#endif

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

0 comments (0 inline)