gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Various doc improvements
0 8 0
default
8 files changed with 170 insertions and 171 deletions:
↑ Collapse diff ↑
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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 meet the \ref concepts::WriteMap "WriteMap" concept.
51 51
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52
    ///Instantiates a PredMap.
52
    ///Instantiates a \c PredMap.
53 53

	
54
    ///This function instantiates a PredMap.
54
    ///This function instantiates a \ref PredMap.
55 55
    ///\param g is the digraph, to which we would like to define the
56
    ///PredMap.
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 meet the \ref concepts::WriteMap "WriteMap" concept.
66 66
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
67
    ///Instantiates a ProcessedMap.
67
    ///Instantiates a \c ProcessedMap.
68 68

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

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

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

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

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

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

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

	
112 112
  ///%BFS algorithm class.
113 113

	
114 114
  ///\ingroup search
115 115
  ///This class provides an efficient implementation of the %BFS algorithm.
116 116
  ///
117 117
  ///There is also a \ref bfs() "function-type interface" for the BFS
118 118
  ///algorithm, which is convenient in the simplier cases and it can be
119 119
  ///used easier.
120 120
  ///
121 121
  ///\tparam GR The type of the digraph the algorithm runs on.
122 122
  ///The default type is \ref ListDigraph.
123 123
#ifdef DOXYGEN
124 124
  template <typename GR,
125 125
            typename TR>
126 126
#else
127 127
  template <typename GR=ListDigraph,
128 128
            typename TR=BfsDefaultTraits<GR> >
129 129
#endif
130 130
  class Bfs {
131 131
  public:
132 132

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

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

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

	
151 151
  private:
152 152

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

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

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

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

	
202 202
  protected:
203 203

	
204 204
    Bfs() {}
205 205

	
206 206
  public:
207 207

	
208 208
    typedef Bfs Create;
209 209

	
210 210
    ///\name Named Template Parameters
211 211

	
212 212
    ///@{
213 213

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

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

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

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

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

	
313 313
    ///@}
314 314

	
315 315
  public:
316 316

	
317 317
    ///Constructor.
318 318

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

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

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

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

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

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

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

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

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

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

	
411 411
  public:
412 412

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

	
421 421
    ///@{
422 422

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

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

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

	
455 455
    ///Processes the next node.
456 456

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

	
481 481
    ///Processes the next node.
482 482

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

	
514 514
    ///Processes the next node.
515 515

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

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

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

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

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

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

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

	
571 571
    ///Executes the algorithm.
572 572

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

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

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

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

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

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

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

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

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

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

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

	
730 730
    ///@}
731 731

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

	
738 738
    ///@{
739 739

	
740 740
    ///The shortest path to a node.
741 741

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

	
750 750
    ///The distance of a node from the root(s).
751 751

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

	
761 761
    ///Returns the 'previous arc' of the shortest path tree for a node.
762 762

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

	
775 775
    ///Returns the 'previous node' of the shortest path tree for a node.
776 776

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

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

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

	
810 810
    ///Checks if a node is reached from the root(s).
811 811

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

	
818 818
    ///@}
819 819
  };
820 820

	
821 821
  ///Default traits class of bfs() function.
822 822

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

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

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

	
848 848
    ///The type of the map that indicates which nodes are processed.
849 849

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

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

	
868 868
    ///The type of the map that indicates which nodes are reached.
869 869

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

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

	
883 883
    ///The type of the map that stores the distances of the nodes.
884 884

	
885 885
    ///The type of the map that stores the distances of the nodes.
886 886
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
887 887
    typedef typename Digraph::template NodeMap<int> DistMap;
888 888
    ///Instantiates a DistMap.
889 889

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

	
898 898
    ///The type of the shortest paths.
899 899

	
900 900
    ///The type of the shortest paths.
901 901
    ///It must meet the \ref concepts::Path "Path" concept.
902 902
    typedef lemon::Path<Digraph> Path;
903 903
  };
904 904

	
905 905
  /// Default traits class used by BfsWizard
906 906

	
907 907
  /// To make it easier to use Bfs algorithm
908 908
  /// we have created a wizard class.
909 909
  /// This \ref BfsWizard class needs default traits,
910 910
  /// as well as the \ref Bfs class.
911 911
  /// The \ref BfsWizardBase is a class to be the default traits of the
912 912
  /// \ref BfsWizard class.
913 913
  template<class GR>
914 914
  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
915 915
  {
916 916

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

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

	
937 937
    public:
938 938
    /// Constructor.
939 939

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

	
945 945
    /// Constructor.
946 946

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

	
954 954
  };
955 955

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

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

	
970 970
    ///The type of the digraph the algorithm runs on.
971 971
    typedef typename TR::Digraph Digraph;
972 972

	
973 973
    typedef typename Digraph::Node Node;
974 974
    typedef typename Digraph::NodeIt NodeIt;
975 975
    typedef typename Digraph::Arc Arc;
976 976
    typedef typename Digraph::OutArcIt OutArcIt;
977 977

	
978 978
    ///\brief The type of the map that stores the predecessor
979 979
    ///arcs of the shortest paths.
980 980
    typedef typename TR::PredMap PredMap;
981 981
    ///\brief The type of the map that stores the distances of the nodes.
982 982
    typedef typename TR::DistMap DistMap;
983 983
    ///\brief The type of the map that indicates which nodes are reached.
984 984
    typedef typename TR::ReachedMap ReachedMap;
985 985
    ///\brief The type of the map that indicates which nodes are processed.
986 986
    typedef typename TR::ProcessedMap ProcessedMap;
987 987
    ///The type of the shortest paths
988 988
    typedef typename TR::Path Path;
989 989

	
990 990
  public:
991 991

	
992 992
    /// Constructor.
993 993
    BfsWizard() : TR() {}
994 994

	
995 995
    /// Constructor that requires parameters.
996 996

	
997 997
    /// Constructor that requires parameters.
998 998
    /// These parameters will be the default values for the traits class.
999 999
    /// \param g The digraph the algorithm runs on.
1000 1000
    BfsWizard(const Digraph &g) :
1001 1001
      TR(g) {}
1002 1002

	
1003 1003
    ///Copy constructor
1004 1004
    BfsWizard(const TR &b) : TR(b) {}
1005 1005

	
1006 1006
    ~BfsWizard() {}
1007 1007

	
1008 1008
    ///Runs BFS algorithm from the given source node.
1009 1009

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

	
1029 1029
    ///Finds the shortest path between \c s and \c t.
1030 1030

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

	
1055 1055
    ///Runs BFS algorithm to visit all nodes in the digraph.
1056 1056

	
1057 1057
    ///This method runs BFS algorithm in order to compute
1058 1058
    ///the shortest path to each node.
1059 1059
    void run()
1060 1060
    {
1061 1061
      run(INVALID);
1062 1062
    }
1063 1063

	
1064 1064
    template<class T>
1065 1065
    struct SetPredMapBase : public Base {
1066 1066
      typedef T PredMap;
1067 1067
      static PredMap *createPredMap(const Digraph &) { return 0; };
1068 1068
      SetPredMapBase(const TR &b) : TR(b) {}
1069 1069
    };
1070 1070
    ///\brief \ref named-func-param "Named parameter"
1071 1071
    ///for setting PredMap object.
1072 1072
    ///
1073 1073
    ///\ref named-func-param "Named parameter"
1074 1074
    ///for setting PredMap object.
1075 1075
    template<class T>
1076 1076
    BfsWizard<SetPredMapBase<T> > predMap(const T &t)
1077 1077
    {
1078 1078
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1079 1079
      return BfsWizard<SetPredMapBase<T> >(*this);
1080 1080
    }
1081 1081

	
1082 1082
    template<class T>
1083 1083
    struct SetReachedMapBase : public Base {
1084 1084
      typedef T ReachedMap;
1085 1085
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1086 1086
      SetReachedMapBase(const TR &b) : TR(b) {}
1087 1087
    };
1088 1088
    ///\brief \ref named-func-param "Named parameter"
1089 1089
    ///for setting ReachedMap object.
1090 1090
    ///
1091 1091
    /// \ref named-func-param "Named parameter"
1092 1092
    ///for setting ReachedMap object.
1093 1093
    template<class T>
1094 1094
    BfsWizard<SetReachedMapBase<T> > reachedMap(const T &t)
1095 1095
    {
1096 1096
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1097 1097
      return BfsWizard<SetReachedMapBase<T> >(*this);
1098 1098
    }
1099 1099

	
1100 1100
    template<class T>
1101 1101
    struct SetDistMapBase : public Base {
1102 1102
      typedef T DistMap;
1103 1103
      static DistMap *createDistMap(const Digraph &) { return 0; };
1104 1104
      SetDistMapBase(const TR &b) : TR(b) {}
1105 1105
    };
1106 1106
    ///\brief \ref named-func-param "Named parameter"
1107 1107
    ///for setting DistMap object.
1108 1108
    ///
1109 1109
    /// \ref named-func-param "Named parameter"
1110 1110
    ///for setting DistMap object.
1111 1111
    template<class T>
1112 1112
    BfsWizard<SetDistMapBase<T> > distMap(const T &t)
1113 1113
    {
1114 1114
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1115 1115
      return BfsWizard<SetDistMapBase<T> >(*this);
1116 1116
    }
1117 1117

	
1118 1118
    template<class T>
1119 1119
    struct SetProcessedMapBase : public Base {
1120 1120
      typedef T ProcessedMap;
1121 1121
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1122 1122
      SetProcessedMapBase(const TR &b) : TR(b) {}
1123 1123
    };
1124 1124
    ///\brief \ref named-func-param "Named parameter"
1125 1125
    ///for setting ProcessedMap object.
1126 1126
    ///
1127 1127
    /// \ref named-func-param "Named parameter"
1128 1128
    ///for setting ProcessedMap object.
1129 1129
    template<class T>
1130 1130
    BfsWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1131 1131
    {
1132 1132
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1133 1133
      return BfsWizard<SetProcessedMapBase<T> >(*this);
1134 1134
    }
1135 1135

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

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

	
1164 1164
  };
1165 1165

	
1166 1166
  ///Function-type interface for BFS algorithm.
1167 1167

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

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

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

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

	
1261 1261
    /// \brief The type of the digraph the algorithm runs on.
1262
    typedef _Digraph Digraph;
1262
    typedef GR Digraph;
1263 1263

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

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

	
1279 1279
  };
1280 1280

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

	
1320 1320
    ///The traits class.
1321
    typedef _Traits Traits;
1321
    typedef TR Traits;
1322 1322

	
1323 1323
    ///The type of the digraph the algorithm runs on.
1324 1324
    typedef typename Traits::Digraph Digraph;
1325 1325

	
1326 1326
    ///The visitor type used by the algorithm.
1327
    typedef _Visitor Visitor;
1327
    typedef VS Visitor;
1328 1328

	
1329 1329
    ///The type of the map that indicates which nodes are reached.
1330 1330
    typedef typename Traits::ReachedMap ReachedMap;
1331 1331

	
1332 1332
  private:
1333 1333

	
1334 1334
    typedef typename Digraph::Node Node;
1335 1335
    typedef typename Digraph::NodeIt NodeIt;
1336 1336
    typedef typename Digraph::Arc Arc;
1337 1337
    typedef typename Digraph::OutArcIt OutArcIt;
1338 1338

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

	
1348 1348
    std::vector<typename Digraph::Node> _list;
1349 1349
    int _list_front, _list_back;
1350 1350

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

	
1359 1359
  protected:
1360 1360

	
1361 1361
    BfsVisit() {}
1362 1362

	
1363 1363
  public:
1364 1364

	
1365 1365
    typedef BfsVisit Create;
1366 1366

	
1367 1367
    /// \name Named Template Parameters
1368 1368

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

	
1389 1389
  public:
1390 1390

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

	
1401 1401
    /// \brief Destructor.
1402 1402
    ~BfsVisit() {
1403 1403
      if(local_reached) delete _reached;
1404 1404
    }
1405 1405

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

	
1423 1423
  public:
1424 1424

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

	
1433 1433
    /// @{
1434 1434

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
1728 1728
    ///@}
1729 1729

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

	
1736 1736
    ///@{
1737 1737

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

	
1746 1746
    ///@}
1747 1747

	
1748 1748
  };
1749 1749

	
1750 1750
} //END OF NAMESPACE LEMON
1751 1751

	
1752 1752
#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_BITS_ARRAY_MAP_H
20 20
#define LEMON_BITS_ARRAY_MAP_H
21 21

	
22 22
#include <memory>
23 23

	
24 24
#include <lemon/bits/traits.h>
25 25
#include <lemon/bits/alteration_notifier.h>
26 26
#include <lemon/concept_check.h>
27 27
#include <lemon/concepts/maps.h>
28 28

	
29 29
// \ingroup graphbits
30 30
// \file
31 31
// \brief Graph map based on the array storage.
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  // \ingroup graphbits
36 36
  //
37 37
  // \brief Graph map based on the array storage.
38 38
  //
39 39
  // The ArrayMap template class is graph map structure that automatically
40 40
  // updates the map when a key is added to or erased from the graph.
41 41
  // This map uses the allocators to implement the container functionality.
42 42
  //
43 43
  // The template parameters are the Graph, the current Item type and
44 44
  // the Value type of the map.
45 45
  template <typename _Graph, typename _Item, typename _Value>
46 46
  class ArrayMap
47 47
    : public ItemSetTraits<_Graph, _Item>::ItemNotifier::ObserverBase {
48 48
  public:
49 49
    // The graph type.
50 50
    typedef _Graph Graph;
51 51
    // The item type.
52 52
    typedef _Item Item;
53 53
    // The reference map tag.
54 54
    typedef True ReferenceMapTag;
55 55

	
56 56
    // The key type of the map.
57 57
    typedef _Item Key;
58 58
    // The value type of the map.
59 59
    typedef _Value Value;
60 60

	
61 61
    // The const reference type of the map.
62 62
    typedef const _Value& ConstReference;
63 63
    // The reference type of the map.
64 64
    typedef _Value& Reference;
65 65

	
66 66
    // The notifier type.
67 67
    typedef typename ItemSetTraits<_Graph, _Item>::ItemNotifier Notifier;
68 68

	
69 69
    // The MapBase of the Map which imlements the core regisitry function.
70 70
    typedef typename Notifier::ObserverBase Parent;
71 71

	
72 72
  private:
73 73
    typedef std::allocator<Value> Allocator;
74 74

	
75 75
  public:
76 76

	
77 77
    // \brief Graph initialized map constructor.
78 78
    //
79 79
    // Graph initialized map constructor.
80 80
    explicit ArrayMap(const Graph& graph) {
81 81
      Parent::attach(graph.notifier(Item()));
82 82
      allocate_memory();
83 83
      Notifier* nf = Parent::notifier();
84 84
      Item it;
85 85
      for (nf->first(it); it != INVALID; nf->next(it)) {
86 86
        int id = nf->id(it);;
87 87
        allocator.construct(&(values[id]), Value());
88 88
      }
89 89
    }
90 90

	
91 91
    // \brief Constructor to use default value to initialize the map.
92 92
    //
93 93
    // It constructs a map and initialize all of the the map.
94 94
    ArrayMap(const Graph& graph, const Value& value) {
95 95
      Parent::attach(graph.notifier(Item()));
96 96
      allocate_memory();
97 97
      Notifier* nf = Parent::notifier();
98 98
      Item it;
99 99
      for (nf->first(it); it != INVALID; nf->next(it)) {
100 100
        int id = nf->id(it);;
101 101
        allocator.construct(&(values[id]), value);
102 102
      }
103 103
    }
104 104

	
105 105
  private:
106 106
    // \brief Constructor to copy a map of the same map type.
107 107
    //
108 108
    // Constructor to copy a map of the same map type.
109 109
    ArrayMap(const ArrayMap& copy) : Parent() {
110 110
      if (copy.attached()) {
111 111
        attach(*copy.notifier());
112 112
      }
113 113
      capacity = copy.capacity;
114 114
      if (capacity == 0) return;
115 115
      values = allocator.allocate(capacity);
116 116
      Notifier* nf = Parent::notifier();
117 117
      Item it;
118 118
      for (nf->first(it); it != INVALID; nf->next(it)) {
119 119
        int id = nf->id(it);;
120 120
        allocator.construct(&(values[id]), copy.values[id]);
121 121
      }
122 122
    }
123 123

	
124 124
    // \brief Assign operator.
125 125
    //
126 126
    // This operator assigns for each item in the map the
127 127
    // value mapped to the same item in the copied map.
128 128
    // The parameter map should be indiced with the same
129 129
    // itemset because this assign operator does not change
130 130
    // the container of the map.
131 131
    ArrayMap& operator=(const ArrayMap& cmap) {
132 132
      return operator=<ArrayMap>(cmap);
133 133
    }
134 134

	
135 135

	
136 136
    // \brief Template assign operator.
137 137
    //
138
    // The given parameter should be conform to the ReadMap
138
    // The given parameter should conform to the ReadMap
139 139
    // concecpt and could be indiced by the current item set of
140 140
    // the NodeMap. In this case the value for each item
141 141
    // is assigned by the value of the given ReadMap.
142 142
    template <typename CMap>
143 143
    ArrayMap& operator=(const CMap& cmap) {
144 144
      checkConcept<concepts::ReadMap<Key, _Value>, CMap>();
145 145
      const typename Parent::Notifier* nf = Parent::notifier();
146 146
      Item it;
147 147
      for (nf->first(it); it != INVALID; nf->next(it)) {
148 148
        set(it, cmap[it]);
149 149
      }
150 150
      return *this;
151 151
    }
152 152

	
153 153
  public:
154 154
    // \brief The destructor of the map.
155 155
    //
156 156
    // The destructor of the map.
157 157
    virtual ~ArrayMap() {
158 158
      if (attached()) {
159 159
        clear();
160 160
        detach();
161 161
      }
162 162
    }
163 163

	
164 164
  protected:
165 165

	
166 166
    using Parent::attach;
167 167
    using Parent::detach;
168 168
    using Parent::attached;
169 169

	
170 170
  public:
171 171

	
172 172
    // \brief The subscript operator.
173 173
    //
174 174
    // The subscript operator. The map can be subscripted by the
175 175
    // actual keys of the graph.
176 176
    Value& operator[](const Key& key) {
177 177
      int id = Parent::notifier()->id(key);
178 178
      return values[id];
179 179
    }
180 180

	
181 181
    // \brief The const subscript operator.
182 182
    //
183 183
    // The const subscript operator. The map can be subscripted by the
184 184
    // actual keys of the graph.
185 185
    const Value& operator[](const Key& key) const {
186 186
      int id = Parent::notifier()->id(key);
187 187
      return values[id];
188 188
    }
189 189

	
190 190
    // \brief Setter function of the map.
191 191
    //
192 192
    // Setter function of the map. Equivalent with map[key] = val.
193 193
    // This is a compatibility feature with the not dereferable maps.
194 194
    void set(const Key& key, const Value& val) {
195 195
      (*this)[key] = val;
196 196
    }
197 197

	
198 198
  protected:
199 199

	
200 200
    // \brief Adds a new key to the map.
201 201
    //
202 202
    // It adds a new key to the map. It is called by the observer notifier
203 203
    // and it overrides the add() member function of the observer base.
204 204
    virtual void add(const Key& key) {
205 205
      Notifier* nf = Parent::notifier();
206 206
      int id = nf->id(key);
207 207
      if (id >= capacity) {
208 208
        int new_capacity = (capacity == 0 ? 1 : capacity);
209 209
        while (new_capacity <= id) {
210 210
          new_capacity <<= 1;
211 211
        }
212 212
        Value* new_values = allocator.allocate(new_capacity);
213 213
        Item it;
214 214
        for (nf->first(it); it != INVALID; nf->next(it)) {
215 215
          int jd = nf->id(it);;
216 216
          if (id != jd) {
217 217
            allocator.construct(&(new_values[jd]), values[jd]);
218 218
            allocator.destroy(&(values[jd]));
219 219
          }
220 220
        }
221 221
        if (capacity != 0) allocator.deallocate(values, capacity);
222 222
        values = new_values;
223 223
        capacity = new_capacity;
224 224
      }
225 225
      allocator.construct(&(values[id]), Value());
226 226
    }
227 227

	
228 228
    // \brief Adds more new keys to the map.
229 229
    //
230 230
    // It adds more new keys to the map. It is called by the observer notifier
231 231
    // and it overrides the add() member function of the observer base.
232 232
    virtual void add(const std::vector<Key>& keys) {
233 233
      Notifier* nf = Parent::notifier();
234 234
      int max_id = -1;
235 235
      for (int i = 0; i < int(keys.size()); ++i) {
236 236
        int id = nf->id(keys[i]);
237 237
        if (id > max_id) {
238 238
          max_id = id;
239 239
        }
240 240
      }
241 241
      if (max_id >= capacity) {
242 242
        int new_capacity = (capacity == 0 ? 1 : capacity);
243 243
        while (new_capacity <= max_id) {
244 244
          new_capacity <<= 1;
245 245
        }
246 246
        Value* new_values = allocator.allocate(new_capacity);
247 247
        Item it;
248 248
        for (nf->first(it); it != INVALID; nf->next(it)) {
249 249
          int id = nf->id(it);
250 250
          bool found = false;
251 251
          for (int i = 0; i < int(keys.size()); ++i) {
252 252
            int jd = nf->id(keys[i]);
253 253
            if (id == jd) {
254 254
              found = true;
255 255
              break;
256 256
            }
257 257
          }
258 258
          if (found) continue;
259 259
          allocator.construct(&(new_values[id]), values[id]);
260 260
          allocator.destroy(&(values[id]));
261 261
        }
262 262
        if (capacity != 0) allocator.deallocate(values, capacity);
263 263
        values = new_values;
264 264
        capacity = new_capacity;
265 265
      }
266 266
      for (int i = 0; i < int(keys.size()); ++i) {
267 267
        int id = nf->id(keys[i]);
268 268
        allocator.construct(&(values[id]), Value());
269 269
      }
270 270
    }
271 271

	
272 272
    // \brief Erase a key from the map.
273 273
    //
274 274
    // Erase a key from the map. It is called by the observer notifier
275 275
    // and it overrides the erase() member function of the observer base.
276 276
    virtual void erase(const Key& key) {
277 277
      int id = Parent::notifier()->id(key);
278 278
      allocator.destroy(&(values[id]));
279 279
    }
280 280

	
281 281
    // \brief Erase more keys from the map.
282 282
    //
283 283
    // Erase more keys from the map. It is called by the observer notifier
284 284
    // and it overrides the erase() member function of the observer base.
285 285
    virtual void erase(const std::vector<Key>& keys) {
286 286
      for (int i = 0; i < int(keys.size()); ++i) {
287 287
        int id = Parent::notifier()->id(keys[i]);
288 288
        allocator.destroy(&(values[id]));
289 289
      }
290 290
    }
291 291

	
292 292
    // \brief Builds the map.
293 293
    //
294 294
    // It builds the map. It is called by the observer notifier
295 295
    // and it overrides the build() member function of the observer base.
296 296
    virtual void build() {
297 297
      Notifier* nf = Parent::notifier();
298 298
      allocate_memory();
299 299
      Item it;
300 300
      for (nf->first(it); it != INVALID; nf->next(it)) {
301 301
        int id = nf->id(it);;
302 302
        allocator.construct(&(values[id]), Value());
303 303
      }
304 304
    }
305 305

	
306 306
    // \brief Clear the map.
307 307
    //
308 308
    // It erase all items from the map. It is called by the observer notifier
309 309
    // and it overrides the clear() member function of the observer base.
310 310
    virtual void clear() {
311 311
      Notifier* nf = Parent::notifier();
312 312
      if (capacity != 0) {
313 313
        Item it;
314 314
        for (nf->first(it); it != INVALID; nf->next(it)) {
315 315
          int id = nf->id(it);
316 316
          allocator.destroy(&(values[id]));
317 317
        }
318 318
        allocator.deallocate(values, capacity);
319 319
        capacity = 0;
320 320
      }
321 321
    }
322 322

	
323 323
  private:
324 324

	
325 325
    void allocate_memory() {
326 326
      int max_id = Parent::notifier()->maxId();
327 327
      if (max_id == -1) {
328 328
        capacity = 0;
329 329
        values = 0;
330 330
        return;
331 331
      }
332 332
      capacity = 1;
333 333
      while (capacity <= max_id) {
334 334
        capacity <<= 1;
335 335
      }
336 336
      values = allocator.allocate(capacity);
337 337
    }
338 338

	
339 339
    int capacity;
340 340
    Value* values;
341 341
    Allocator allocator;
342 342

	
343 343
  };
344 344

	
345 345
}
346 346

	
347 347
#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_BITS_VECTOR_MAP_H
20 20
#define LEMON_BITS_VECTOR_MAP_H
21 21

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

	
25 25
#include <lemon/core.h>
26 26
#include <lemon/bits/alteration_notifier.h>
27 27

	
28 28
#include <lemon/concept_check.h>
29 29
#include <lemon/concepts/maps.h>
30 30

	
31 31
//\ingroup graphbits
32 32
//
33 33
//\file
34 34
//\brief Vector based graph maps.
35 35
namespace lemon {
36 36

	
37 37
  // \ingroup graphbits
38 38
  //
39 39
  // \brief Graph map based on the std::vector storage.
40 40
  //
41 41
  // The VectorMap template class is graph map structure that automatically
42 42
  // updates the map when a key is added to or erased from the graph.
43 43
  // This map type uses std::vector to store the values.
44 44
  //
45 45
  // \tparam _Graph The graph this map is attached to.
46 46
  // \tparam _Item The item type of the graph items.
47 47
  // \tparam _Value The value type of the map.
48 48
  template <typename _Graph, typename _Item, typename _Value>
49 49
  class VectorMap
50 50
    : public ItemSetTraits<_Graph, _Item>::ItemNotifier::ObserverBase {
51 51
  private:
52 52

	
53 53
    // The container type of the map.
54 54
    typedef std::vector<_Value> Container;
55 55

	
56 56
  public:
57 57

	
58 58
    // The graph type of the map.
59 59
    typedef _Graph Graph;
60 60
    // The item type of the map.
61 61
    typedef _Item Item;
62 62
    // The reference map tag.
63 63
    typedef True ReferenceMapTag;
64 64

	
65 65
    // The key type of the map.
66 66
    typedef _Item Key;
67 67
    // The value type of the map.
68 68
    typedef _Value Value;
69 69

	
70 70
    // The notifier type.
71 71
    typedef typename ItemSetTraits<_Graph, _Item>::ItemNotifier Notifier;
72 72

	
73 73
    // The map type.
74 74
    typedef VectorMap Map;
75 75
    // The base class of the map.
76 76
    typedef typename Notifier::ObserverBase Parent;
77 77

	
78 78
    // The reference type of the map;
79 79
    typedef typename Container::reference Reference;
80 80
    // The const reference type of the map;
81 81
    typedef typename Container::const_reference ConstReference;
82 82

	
83 83

	
84 84
    // \brief Constructor to attach the new map into the notifier.
85 85
    //
86 86
    // It constructs a map and attachs it into the notifier.
87 87
    // It adds all the items of the graph to the map.
88 88
    VectorMap(const Graph& graph) {
89 89
      Parent::attach(graph.notifier(Item()));
90 90
      container.resize(Parent::notifier()->maxId() + 1);
91 91
    }
92 92

	
93 93
    // \brief Constructor uses given value to initialize the map.
94 94
    //
95 95
    // It constructs a map uses a given value to initialize the map.
96 96
    // It adds all the items of the graph to the map.
97 97
    VectorMap(const Graph& graph, const Value& value) {
98 98
      Parent::attach(graph.notifier(Item()));
99 99
      container.resize(Parent::notifier()->maxId() + 1, value);
100 100
    }
101 101

	
102 102
  private:
103 103
    // \brief Copy constructor
104 104
    //
105 105
    // Copy constructor.
106 106
    VectorMap(const VectorMap& _copy) : Parent() {
107 107
      if (_copy.attached()) {
108 108
        Parent::attach(*_copy.notifier());
109 109
        container = _copy.container;
110 110
      }
111 111
    }
112 112

	
113 113
    // \brief Assign operator.
114 114
    //
115 115
    // This operator assigns for each item in the map the
116 116
    // value mapped to the same item in the copied map.
117 117
    // The parameter map should be indiced with the same
118 118
    // itemset because this assign operator does not change
119 119
    // the container of the map.
120 120
    VectorMap& operator=(const VectorMap& cmap) {
121 121
      return operator=<VectorMap>(cmap);
122 122
    }
123 123

	
124 124

	
125 125
    // \brief Template assign operator.
126 126
    //
127
    // The given parameter should be conform to the ReadMap
127
    // The given parameter should conform to the ReadMap
128 128
    // concecpt and could be indiced by the current item set of
129 129
    // the NodeMap. In this case the value for each item
130 130
    // is assigned by the value of the given ReadMap.
131 131
    template <typename CMap>
132 132
    VectorMap& operator=(const CMap& cmap) {
133 133
      checkConcept<concepts::ReadMap<Key, _Value>, CMap>();
134 134
      const typename Parent::Notifier* nf = Parent::notifier();
135 135
      Item it;
136 136
      for (nf->first(it); it != INVALID; nf->next(it)) {
137 137
        set(it, cmap[it]);
138 138
      }
139 139
      return *this;
140 140
    }
141 141

	
142 142
  public:
143 143

	
144 144
    // \brief The subcript operator.
145 145
    //
146 146
    // The subscript operator. The map can be subscripted by the
147 147
    // actual items of the graph.
148 148
    Reference operator[](const Key& key) {
149 149
      return container[Parent::notifier()->id(key)];
150 150
    }
151 151

	
152 152
    // \brief The const subcript operator.
153 153
    //
154 154
    // The const subscript operator. The map can be subscripted by the
155 155
    // actual items of the graph.
156 156
    ConstReference operator[](const Key& key) const {
157 157
      return container[Parent::notifier()->id(key)];
158 158
    }
159 159

	
160 160

	
161 161
    // \brief The setter function of the map.
162 162
    //
163 163
    // It the same as operator[](key) = value expression.
164 164
    void set(const Key& key, const Value& value) {
165 165
      (*this)[key] = value;
166 166
    }
167 167

	
168 168
  protected:
169 169

	
170 170
    // \brief Adds a new key to the map.
171 171
    //
172 172
    // It adds a new key to the map. It is called by the observer notifier
173 173
    // and it overrides the add() member function of the observer base.
174 174
    virtual void add(const Key& key) {
175 175
      int id = Parent::notifier()->id(key);
176 176
      if (id >= int(container.size())) {
177 177
        container.resize(id + 1);
178 178
      }
179 179
    }
180 180

	
181 181
    // \brief Adds more new keys to the map.
182 182
    //
183 183
    // It adds more new keys to the map. It is called by the observer notifier
184 184
    // and it overrides the add() member function of the observer base.
185 185
    virtual void add(const std::vector<Key>& keys) {
186 186
      int max = container.size() - 1;
187 187
      for (int i = 0; i < int(keys.size()); ++i) {
188 188
        int id = Parent::notifier()->id(keys[i]);
189 189
        if (id >= max) {
190 190
          max = id;
191 191
        }
192 192
      }
193 193
      container.resize(max + 1);
194 194
    }
195 195

	
196 196
    // \brief Erase a key from the map.
197 197
    //
198 198
    // Erase a key from the map. It is called by the observer notifier
199 199
    // and it overrides the erase() member function of the observer base.
200 200
    virtual void erase(const Key& key) {
201 201
      container[Parent::notifier()->id(key)] = Value();
202 202
    }
203 203

	
204 204
    // \brief Erase more keys from the map.
205 205
    //
206 206
    // It erases more keys from the map. It is called by the observer notifier
207 207
    // and it overrides the erase() member function of the observer base.
208 208
    virtual void erase(const std::vector<Key>& keys) {
209 209
      for (int i = 0; i < int(keys.size()); ++i) {
210 210
        container[Parent::notifier()->id(keys[i])] = Value();
211 211
      }
212 212
    }
213 213

	
214 214
    // \brief Build the map.
215 215
    //
216 216
    // It builds the map. It is called by the observer notifier
217 217
    // and it overrides the build() member function of the observer base.
218 218
    virtual void build() {
219 219
      int size = Parent::notifier()->maxId() + 1;
220 220
      container.reserve(size);
221 221
      container.resize(size);
222 222
    }
223 223

	
224 224
    // \brief Clear the map.
225 225
    //
226 226
    // It erases all items from the map. It is called by the observer notifier
227 227
    // and it overrides the clear() member function of the observer base.
228 228
    virtual void clear() {
229 229
      container.clear();
230 230
    }
231 231

	
232 232
  private:
233 233

	
234 234
    Container container;
235 235

	
236 236
  };
237 237

	
238 238
}
239 239

	
240 240
#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

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

	
31 31
  /// \brief Default traits class of Circulation class.
32 32
  ///
33 33
  /// Default traits class of Circulation class.
34
  /// \tparam _Diraph Digraph type.
35
  /// \tparam _LCapMap Lower bound capacity map type.
36
  /// \tparam _UCapMap Upper bound capacity map type.
37
  /// \tparam _DeltaMap Delta map type.
38
  template <typename _Diraph, typename _LCapMap,
39
            typename _UCapMap, typename _DeltaMap>
34
  /// \tparam GR Digraph type.
35
  /// \tparam LM Lower bound capacity map type.
36
  /// \tparam UM Upper bound capacity map type.
37
  /// \tparam DM Delta map type.
38
  template <typename GR, typename LM,
39
            typename UM, typename DM>
40 40
  struct CirculationDefaultTraits {
41 41

	
42 42
    /// \brief The type of the digraph the algorithm runs on.
43
    typedef _Diraph Digraph;
43
    typedef GR Digraph;
44 44

	
45 45
    /// \brief The type of the map that stores the circulation lower
46 46
    /// bound.
47 47
    ///
48 48
    /// The type of the map that stores the circulation lower bound.
49 49
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
50
    typedef _LCapMap LCapMap;
50
    typedef LM LCapMap;
51 51

	
52 52
    /// \brief The type of the map that stores the circulation upper
53 53
    /// bound.
54 54
    ///
55 55
    /// The type of the map that stores the circulation upper bound.
56 56
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
57
    typedef _UCapMap UCapMap;
57
    typedef UM UCapMap;
58 58

	
59 59
    /// \brief The type of the map that stores the lower bound for
60 60
    /// the supply of the nodes.
61 61
    ///
62 62
    /// The type of the map that stores the lower bound for the supply
63 63
    /// of the nodes. It must meet the \ref concepts::ReadMap "ReadMap"
64 64
    /// concept.
65
    typedef _DeltaMap DeltaMap;
65
    typedef DM DeltaMap;
66 66

	
67 67
    /// \brief The type of the flow values.
68 68
    typedef typename DeltaMap::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 meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
74 74
    typedef typename Digraph::template ArcMap<Value> FlowMap;
75 75

	
76 76
    /// \brief Instantiates a FlowMap.
77 77
    ///
78 78
    /// This function instantiates a \ref FlowMap.
79 79
    /// \param digraph The digraph, to which we would like to define
80 80
    /// the flow map.
81 81
    static FlowMap* createFlowMap(const Digraph& digraph) {
82 82
      return new FlowMap(digraph);
83 83
    }
84 84

	
85 85
    /// \brief The elevator type used by the algorithm.
86 86
    ///
87 87
    /// The elevator type used by the algorithm.
88 88
    ///
89 89
    /// \sa Elevator
90 90
    /// \sa LinkedElevator
91 91
    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
92 92

	
93 93
    /// \brief Instantiates an Elevator.
94 94
    ///
95 95
    /// This function instantiates an \ref Elevator.
96 96
    /// \param digraph The digraph, to which we would like to define
97 97
    /// the elevator.
98 98
    /// \param max_level The maximum level of the elevator.
99 99
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
100 100
      return new Elevator(digraph, max_level);
101 101
    }
102 102

	
103 103
    /// \brief The tolerance used by the algorithm
104 104
    ///
105 105
    /// The tolerance used by the algorithm to handle inexact computation.
106 106
    typedef lemon::Tolerance<Value> Tolerance;
107 107

	
108 108
  };
109 109

	
110 110
  /**
111 111
     \brief Push-relabel algorithm for the network circulation problem.
112 112

	
113 113
     \ingroup max_flow
114 114
     This class implements a push-relabel algorithm for the network
115 115
     circulation problem.
116 116
     It is to find a feasible circulation when lower and upper bounds
117 117
     are given for the flow values on the arcs and lower bounds
118 118
     are given for the supply values of the nodes.
119 119

	
120 120
     The exact formulation of this problem is the following.
121 121
     Let \f$G=(V,A)\f$ be a digraph,
122 122
     \f$lower, upper: A\rightarrow\mathbf{R}^+_0\f$,
123 123
     \f$delta: V\rightarrow\mathbf{R}\f$. Find a feasible circulation
124 124
     \f$f: A\rightarrow\mathbf{R}^+_0\f$ so that
125 125
     \f[ \sum_{a\in\delta_{out}(v)} f(a) - \sum_{a\in\delta_{in}(v)} f(a)
126 126
     \geq delta(v) \quad \forall v\in V, \f]
127 127
     \f[ lower(a)\leq f(a) \leq upper(a) \quad \forall a\in A. \f]
128 128
     \note \f$delta(v)\f$ specifies a lower bound for the supply of node
129 129
     \f$v\f$. It can be either positive or negative, however note that
130 130
     \f$\sum_{v\in V}delta(v)\f$ should be zero or negative in order to
131 131
     have a feasible solution.
132 132

	
133 133
     \note A special case of this problem is when
134 134
     \f$\sum_{v\in V}delta(v) = 0\f$. Then the supply of each node \f$v\f$
135 135
     will be \e equal \e to \f$delta(v)\f$, if a circulation can be found.
136 136
     Thus a feasible solution for the
137 137
     \ref min_cost_flow "minimum cost flow" problem can be calculated
138 138
     in this way.
139 139

	
140
     \tparam _Digraph The type of the digraph the algorithm runs on.
141
     \tparam _LCapMap The type of the lower bound capacity map. The default
142
     map type is \ref concepts::Digraph::ArcMap "_Digraph::ArcMap<int>".
143
     \tparam _UCapMap The type of the upper bound capacity map. The default
144
     map type is \c _LCapMap.
145
     \tparam _DeltaMap The type of the map that stores the lower bound
140
     \tparam GR The type of the digraph the algorithm runs on.
141
     \tparam LM The type of the lower bound capacity map. The default
142
     map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
143
     \tparam UM The type of the upper bound capacity map. The default
144
     map type is \c LM.
145
     \tparam DM The type of the map that stores the lower bound
146 146
     for the supply of the nodes. The default map type is
147
     \c _Digraph::ArcMap<_UCapMap::Value>.
147
     \ref concepts::Digraph::NodeMap "GR::NodeMap<UM::Value>".
148 148
  */
149 149
#ifdef DOXYGEN
150
template< typename _Digraph,
151
          typename _LCapMap,
152
          typename _UCapMap,
153
          typename _DeltaMap,
154
          typename _Traits >
150
template< typename GR,
151
          typename LM,
152
          typename UM,
153
          typename DM,
154
          typename TR >
155 155
#else
156
template< typename _Digraph,
157
          typename _LCapMap = typename _Digraph::template ArcMap<int>,
158
          typename _UCapMap = _LCapMap,
159
          typename _DeltaMap = typename _Digraph::
160
                               template NodeMap<typename _UCapMap::Value>,
161
          typename _Traits=CirculationDefaultTraits<_Digraph, _LCapMap,
162
                                                    _UCapMap, _DeltaMap> >
156
template< typename GR,
157
          typename LM = typename GR::template ArcMap<int>,
158
          typename UM = LM,
159
          typename DM = typename GR::template NodeMap<typename UM::Value>,
160
          typename TR = CirculationDefaultTraits<GR, LM, UM, DM> >
163 161
#endif
164 162
  class Circulation {
165 163
  public:
166 164

	
167 165
    ///The \ref CirculationDefaultTraits "traits class" of the algorithm.
168
    typedef _Traits Traits;
166
    typedef TR Traits;
169 167
    ///The type of the digraph the algorithm runs on.
170 168
    typedef typename Traits::Digraph Digraph;
171 169
    ///The type of the flow values.
172 170
    typedef typename Traits::Value Value;
173 171

	
174 172
    /// The type of the lower bound capacity map.
175 173
    typedef typename Traits::LCapMap LCapMap;
176 174
    /// The type of the upper bound capacity map.
177 175
    typedef typename Traits::UCapMap UCapMap;
178 176
    /// \brief The type of the map that stores the lower bound for
179 177
    /// the supply of the nodes.
180 178
    typedef typename Traits::DeltaMap DeltaMap;
181 179
    ///The type of the flow map.
182 180
    typedef typename Traits::FlowMap FlowMap;
183 181

	
184 182
    ///The type of the elevator.
185 183
    typedef typename Traits::Elevator Elevator;
186 184
    ///The type of the tolerance.
187 185
    typedef typename Traits::Tolerance Tolerance;
188 186

	
189 187
  private:
190 188

	
191 189
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
192 190

	
193 191
    const Digraph &_g;
194 192
    int _node_num;
195 193

	
196 194
    const LCapMap *_lo;
197 195
    const UCapMap *_up;
198 196
    const DeltaMap *_delta;
199 197

	
200 198
    FlowMap *_flow;
201 199
    bool _local_flow;
202 200

	
203 201
    Elevator* _level;
204 202
    bool _local_level;
205 203

	
206 204
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
207 205
    ExcessMap* _excess;
208 206

	
209 207
    Tolerance _tol;
210 208
    int _el;
211 209

	
212 210
  public:
213 211

	
214 212
    typedef Circulation Create;
215 213

	
216 214
    ///\name Named Template Parameters
217 215

	
218 216
    ///@{
219 217

	
220 218
    template <typename _FlowMap>
221 219
    struct SetFlowMapTraits : public Traits {
222 220
      typedef _FlowMap FlowMap;
223 221
      static FlowMap *createFlowMap(const Digraph&) {
224 222
        LEMON_ASSERT(false, "FlowMap is not initialized");
225 223
        return 0; // ignore warnings
226 224
      }
227 225
    };
228 226

	
229 227
    /// \brief \ref named-templ-param "Named parameter" for setting
230 228
    /// FlowMap type
231 229
    ///
232 230
    /// \ref named-templ-param "Named parameter" for setting FlowMap
233 231
    /// type.
234 232
    template <typename _FlowMap>
235 233
    struct SetFlowMap
236 234
      : public Circulation<Digraph, LCapMap, UCapMap, DeltaMap,
237 235
                           SetFlowMapTraits<_FlowMap> > {
238 236
      typedef Circulation<Digraph, LCapMap, UCapMap, DeltaMap,
239 237
                          SetFlowMapTraits<_FlowMap> > Create;
240 238
    };
241 239

	
242 240
    template <typename _Elevator>
243 241
    struct SetElevatorTraits : public Traits {
244 242
      typedef _Elevator Elevator;
245 243
      static Elevator *createElevator(const Digraph&, int) {
246 244
        LEMON_ASSERT(false, "Elevator is not initialized");
247 245
        return 0; // ignore warnings
248 246
      }
249 247
    };
250 248

	
251 249
    /// \brief \ref named-templ-param "Named parameter" for setting
252 250
    /// Elevator type
253 251
    ///
254 252
    /// \ref named-templ-param "Named parameter" for setting Elevator
255 253
    /// type. If this named parameter is used, then an external
256 254
    /// elevator object must be passed to the algorithm using the
257 255
    /// \ref elevator(Elevator&) "elevator()" function before calling
258 256
    /// \ref run() or \ref init().
259 257
    /// \sa SetStandardElevator
260 258
    template <typename _Elevator>
261 259
    struct SetElevator
262 260
      : public Circulation<Digraph, LCapMap, UCapMap, DeltaMap,
263 261
                           SetElevatorTraits<_Elevator> > {
264 262
      typedef Circulation<Digraph, LCapMap, UCapMap, DeltaMap,
265 263
                          SetElevatorTraits<_Elevator> > Create;
266 264
    };
267 265

	
268 266
    template <typename _Elevator>
269 267
    struct SetStandardElevatorTraits : public Traits {
270 268
      typedef _Elevator Elevator;
271 269
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
272 270
        return new Elevator(digraph, max_level);
273 271
      }
274 272
    };
275 273

	
276 274
    /// \brief \ref named-templ-param "Named parameter" for setting
277 275
    /// Elevator type with automatic allocation
278 276
    ///
279 277
    /// \ref named-templ-param "Named parameter" for setting Elevator
280 278
    /// type with automatic allocation.
281 279
    /// The Elevator should have standard constructor interface to be
282 280
    /// able to automatically created by the algorithm (i.e. the
283 281
    /// digraph and the maximum level should be passed to it).
284 282
    /// However an external elevator object could also be passed to the
285 283
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
286 284
    /// before calling \ref run() or \ref init().
287 285
    /// \sa SetElevator
288 286
    template <typename _Elevator>
289 287
    struct SetStandardElevator
290 288
      : public Circulation<Digraph, LCapMap, UCapMap, DeltaMap,
291 289
                       SetStandardElevatorTraits<_Elevator> > {
292 290
      typedef Circulation<Digraph, LCapMap, UCapMap, DeltaMap,
293 291
                      SetStandardElevatorTraits<_Elevator> > Create;
294 292
    };
295 293

	
296 294
    /// @}
297 295

	
298 296
  protected:
299 297

	
300 298
    Circulation() {}
301 299

	
302 300
  public:
303 301

	
304 302
    /// The constructor of the class.
305 303

	
306 304
    /// The constructor of the class.
307 305
    /// \param g The digraph the algorithm runs on.
308 306
    /// \param lo The lower bound capacity of the arcs.
309 307
    /// \param up The upper bound capacity of the arcs.
310 308
    /// \param delta The lower bound for the supply of the nodes.
311 309
    Circulation(const Digraph &g,const LCapMap &lo,
312 310
                const UCapMap &up,const DeltaMap &delta)
313 311
      : _g(g), _node_num(),
314 312
        _lo(&lo),_up(&up),_delta(&delta),_flow(0),_local_flow(false),
315 313
        _level(0), _local_level(false), _excess(0), _el() {}
316 314

	
317 315
    /// Destructor.
318 316
    ~Circulation() {
319 317
      destroyStructures();
320 318
    }
321 319

	
322 320

	
323 321
  private:
324 322

	
325 323
    void createStructures() {
326 324
      _node_num = _el = countNodes(_g);
327 325

	
328 326
      if (!_flow) {
329 327
        _flow = Traits::createFlowMap(_g);
330 328
        _local_flow = true;
331 329
      }
332 330
      if (!_level) {
333 331
        _level = Traits::createElevator(_g, _node_num);
334 332
        _local_level = true;
335 333
      }
336 334
      if (!_excess) {
337 335
        _excess = new ExcessMap(_g);
338 336
      }
339 337
    }
340 338

	
341 339
    void destroyStructures() {
342 340
      if (_local_flow) {
343 341
        delete _flow;
344 342
      }
345 343
      if (_local_level) {
346 344
        delete _level;
347 345
      }
348 346
      if (_excess) {
349 347
        delete _excess;
350 348
      }
351 349
    }
352 350

	
353 351
  public:
354 352

	
355 353
    /// Sets the lower bound capacity map.
356 354

	
357 355
    /// Sets the lower bound capacity map.
358 356
    /// \return <tt>(*this)</tt>
359 357
    Circulation& lowerCapMap(const LCapMap& map) {
360 358
      _lo = &map;
361 359
      return *this;
362 360
    }
363 361

	
364 362
    /// Sets the upper bound capacity map.
365 363

	
366 364
    /// Sets the upper bound capacity map.
367 365
    /// \return <tt>(*this)</tt>
368 366
    Circulation& upperCapMap(const LCapMap& map) {
369 367
      _up = &map;
370 368
      return *this;
371 369
    }
372 370

	
373 371
    /// Sets the lower bound map for the supply of the nodes.
374 372

	
375 373
    /// Sets the lower bound map for the supply of the nodes.
376 374
    /// \return <tt>(*this)</tt>
377 375
    Circulation& deltaMap(const DeltaMap& map) {
378 376
      _delta = &map;
379 377
      return *this;
380 378
    }
381 379

	
382 380
    /// \brief Sets the flow map.
383 381
    ///
384 382
    /// Sets the flow map.
385 383
    /// If you don't use this function before calling \ref run() or
386 384
    /// \ref init(), an instance will be allocated automatically.
387 385
    /// The destructor deallocates this automatically allocated map,
388 386
    /// of course.
389 387
    /// \return <tt>(*this)</tt>
390 388
    Circulation& flowMap(FlowMap& map) {
391 389
      if (_local_flow) {
392 390
        delete _flow;
393 391
        _local_flow = false;
394 392
      }
395 393
      _flow = &map;
396 394
      return *this;
397 395
    }
398 396

	
399 397
    /// \brief Sets the elevator used by algorithm.
400 398
    ///
401 399
    /// Sets the elevator used by algorithm.
402 400
    /// If you don't use this function before calling \ref run() or
403 401
    /// \ref init(), an instance will be allocated automatically.
404 402
    /// The destructor deallocates this automatically allocated elevator,
405 403
    /// of course.
406 404
    /// \return <tt>(*this)</tt>
407 405
    Circulation& elevator(Elevator& elevator) {
408 406
      if (_local_level) {
409 407
        delete _level;
410 408
        _local_level = false;
411 409
      }
412 410
      _level = &elevator;
413 411
      return *this;
414 412
    }
415 413

	
416 414
    /// \brief Returns a const reference to the elevator.
417 415
    ///
418 416
    /// Returns a const reference to the elevator.
419 417
    ///
420 418
    /// \pre Either \ref run() or \ref init() must be called before
421 419
    /// using this function.
422 420
    const Elevator& elevator() const {
423 421
      return *_level;
424 422
    }
425 423

	
426 424
    /// \brief Sets the tolerance used by algorithm.
427 425
    ///
428 426
    /// Sets the tolerance used by algorithm.
429 427
    Circulation& tolerance(const Tolerance& tolerance) const {
430 428
      _tol = tolerance;
431 429
      return *this;
432 430
    }
433 431

	
434 432
    /// \brief Returns a const reference to the tolerance.
435 433
    ///
436 434
    /// Returns a const reference to the tolerance.
437 435
    const Tolerance& tolerance() const {
438 436
      return tolerance;
439 437
    }
440 438

	
441 439
    /// \name Execution Control
442 440
    /// The simplest way to execute the algorithm is to call \ref run().\n
443 441
    /// If you need more control on the initial solution or the execution,
444 442
    /// first you have to call one of the \ref init() functions, then
445 443
    /// the \ref start() function.
446 444

	
447 445
    ///@{
448 446

	
449 447
    /// Initializes the internal data structures.
450 448

	
451 449
    /// Initializes the internal data structures and sets all flow values
452 450
    /// to the lower bound.
453 451
    void init()
454 452
    {
455 453
      createStructures();
456 454

	
457 455
      for(NodeIt n(_g);n!=INVALID;++n) {
458 456
        _excess->set(n, (*_delta)[n]);
459 457
      }
460 458

	
461 459
      for (ArcIt e(_g);e!=INVALID;++e) {
462 460
        _flow->set(e, (*_lo)[e]);
463 461
        _excess->set(_g.target(e), (*_excess)[_g.target(e)] + (*_flow)[e]);
464 462
        _excess->set(_g.source(e), (*_excess)[_g.source(e)] - (*_flow)[e]);
465 463
      }
466 464

	
467 465
      // global relabeling tested, but in general case it provides
468 466
      // worse performance for random digraphs
469 467
      _level->initStart();
470 468
      for(NodeIt n(_g);n!=INVALID;++n)
471 469
        _level->initAddItem(n);
472 470
      _level->initFinish();
473 471
      for(NodeIt n(_g);n!=INVALID;++n)
474 472
        if(_tol.positive((*_excess)[n]))
475 473
          _level->activate(n);
476 474
    }
477 475

	
478 476
    /// Initializes the internal data structures using a greedy approach.
479 477

	
480 478
    /// Initializes the internal data structures using a greedy approach
481 479
    /// to construct the initial solution.
482 480
    void greedyInit()
483 481
    {
484 482
      createStructures();
485 483

	
486 484
      for(NodeIt n(_g);n!=INVALID;++n) {
487 485
        _excess->set(n, (*_delta)[n]);
488 486
      }
489 487

	
490 488
      for (ArcIt e(_g);e!=INVALID;++e) {
491 489
        if (!_tol.positive((*_excess)[_g.target(e)] + (*_up)[e])) {
492 490
          _flow->set(e, (*_up)[e]);
493 491
          _excess->set(_g.target(e), (*_excess)[_g.target(e)] + (*_up)[e]);
494 492
          _excess->set(_g.source(e), (*_excess)[_g.source(e)] - (*_up)[e]);
495 493
        } else if (_tol.positive((*_excess)[_g.target(e)] + (*_lo)[e])) {
496 494
          _flow->set(e, (*_lo)[e]);
497 495
          _excess->set(_g.target(e), (*_excess)[_g.target(e)] + (*_lo)[e]);
498 496
          _excess->set(_g.source(e), (*_excess)[_g.source(e)] - (*_lo)[e]);
499 497
        } else {
500 498
          Value fc = -(*_excess)[_g.target(e)];
501 499
          _flow->set(e, fc);
502 500
          _excess->set(_g.target(e), 0);
503 501
          _excess->set(_g.source(e), (*_excess)[_g.source(e)] - fc);
504 502
        }
505 503
      }
506 504

	
507 505
      _level->initStart();
508 506
      for(NodeIt n(_g);n!=INVALID;++n)
509 507
        _level->initAddItem(n);
510 508
      _level->initFinish();
511 509
      for(NodeIt n(_g);n!=INVALID;++n)
512 510
        if(_tol.positive((*_excess)[n]))
513 511
          _level->activate(n);
514 512
    }
515 513

	
516 514
    ///Executes the algorithm
517 515

	
518 516
    ///This function executes the algorithm.
519 517
    ///
520 518
    ///\return \c true if a feasible circulation is found.
521 519
    ///
522 520
    ///\sa barrier()
523 521
    ///\sa barrierMap()
524 522
    bool start()
525 523
    {
526 524

	
527 525
      Node act;
528 526
      Node bact=INVALID;
529 527
      Node last_activated=INVALID;
530 528
      while((act=_level->highestActive())!=INVALID) {
531 529
        int actlevel=(*_level)[act];
532 530
        int mlevel=_node_num;
533 531
        Value exc=(*_excess)[act];
534 532

	
535 533
        for(OutArcIt e(_g,act);e!=INVALID; ++e) {
536 534
          Node v = _g.target(e);
537 535
          Value fc=(*_up)[e]-(*_flow)[e];
538 536
          if(!_tol.positive(fc)) continue;
539 537
          if((*_level)[v]<actlevel) {
540 538
            if(!_tol.less(fc, exc)) {
541 539
              _flow->set(e, (*_flow)[e] + exc);
542 540
              _excess->set(v, (*_excess)[v] + exc);
543 541
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
544 542
                _level->activate(v);
545 543
              _excess->set(act,0);
546 544
              _level->deactivate(act);
547 545
              goto next_l;
548 546
            }
549 547
            else {
550 548
              _flow->set(e, (*_up)[e]);
551 549
              _excess->set(v, (*_excess)[v] + fc);
552 550
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
553 551
                _level->activate(v);
554 552
              exc-=fc;
555 553
            }
556 554
          }
557 555
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
558 556
        }
559 557
        for(InArcIt e(_g,act);e!=INVALID; ++e) {
560 558
          Node v = _g.source(e);
561 559
          Value fc=(*_flow)[e]-(*_lo)[e];
562 560
          if(!_tol.positive(fc)) continue;
563 561
          if((*_level)[v]<actlevel) {
564 562
            if(!_tol.less(fc, exc)) {
565 563
              _flow->set(e, (*_flow)[e] - exc);
566 564
              _excess->set(v, (*_excess)[v] + exc);
567 565
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
568 566
                _level->activate(v);
569 567
              _excess->set(act,0);
570 568
              _level->deactivate(act);
571 569
              goto next_l;
572 570
            }
573 571
            else {
574 572
              _flow->set(e, (*_lo)[e]);
575 573
              _excess->set(v, (*_excess)[v] + fc);
576 574
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
577 575
                _level->activate(v);
578 576
              exc-=fc;
579 577
            }
580 578
          }
581 579
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
582 580
        }
583 581

	
584 582
        _excess->set(act, exc);
585 583
        if(!_tol.positive(exc)) _level->deactivate(act);
586 584
        else if(mlevel==_node_num) {
587 585
          _level->liftHighestActiveToTop();
588 586
          _el = _node_num;
589 587
          return false;
590 588
        }
591 589
        else {
592 590
          _level->liftHighestActive(mlevel+1);
593 591
          if(_level->onLevel(actlevel)==0) {
594 592
            _el = actlevel;
595 593
            return false;
596 594
          }
597 595
        }
598 596
      next_l:
599 597
        ;
600 598
      }
601 599
      return true;
602 600
    }
603 601

	
604 602
    /// Runs the algorithm.
605 603

	
606 604
    /// This function runs the algorithm.
607 605
    ///
608 606
    /// \return \c true if a feasible circulation is found.
609 607
    ///
610 608
    /// \note Apart from the return value, c.run() is just a shortcut of
611 609
    /// the following code.
612 610
    /// \code
613 611
    ///   c.greedyInit();
614 612
    ///   c.start();
615 613
    /// \endcode
616 614
    bool run() {
617 615
      greedyInit();
618 616
      return start();
619 617
    }
620 618

	
621 619
    /// @}
622 620

	
623 621
    /// \name Query Functions
624 622
    /// The results of the circulation algorithm can be obtained using
625 623
    /// these functions.\n
626 624
    /// Either \ref run() or \ref start() should be called before
627 625
    /// using them.
628 626

	
629 627
    ///@{
630 628

	
631 629
    /// \brief Returns the flow on the given arc.
632 630
    ///
633 631
    /// Returns the flow on the given arc.
634 632
    ///
635 633
    /// \pre Either \ref run() or \ref init() must be called before
636 634
    /// using this function.
637 635
    Value flow(const Arc& arc) const {
638 636
      return (*_flow)[arc];
639 637
    }
640 638

	
641 639
    /// \brief Returns a const reference to the flow map.
642 640
    ///
643 641
    /// Returns a const reference to the arc map storing the found flow.
644 642
    ///
645 643
    /// \pre Either \ref run() or \ref init() must be called before
646 644
    /// using this function.
647 645
    const FlowMap& flowMap() const {
648 646
      return *_flow;
649 647
    }
650 648

	
651 649
    /**
652 650
       \brief Returns \c true if the given node is in a barrier.
653 651

	
654 652
       Barrier is a set \e B of nodes for which
655 653

	
656 654
       \f[ \sum_{a\in\delta_{out}(B)} upper(a) -
657 655
           \sum_{a\in\delta_{in}(B)} lower(a) < \sum_{v\in B}delta(v) \f]
658 656

	
659 657
       holds. The existence of a set with this property prooves that a
660 658
       feasible circualtion cannot exist.
661 659

	
662 660
       This function returns \c true if the given node is in the found
663 661
       barrier. If a feasible circulation is found, the function
664 662
       gives back \c false for every node.
665 663

	
666 664
       \pre Either \ref run() or \ref init() must be called before
667 665
       using this function.
668 666

	
669 667
       \sa barrierMap()
670 668
       \sa checkBarrier()
671 669
    */
672 670
    bool barrier(const Node& node) const
673 671
    {
674 672
      return (*_level)[node] >= _el;
675 673
    }
676 674

	
677 675
    /// \brief Gives back a barrier.
678 676
    ///
679 677
    /// This function sets \c bar to the characteristic vector of the
680 678
    /// found barrier. \c bar should be a \ref concepts::WriteMap "writable"
681 679
    /// node map with \c bool (or convertible) value type.
682 680
    ///
683 681
    /// If a feasible circulation is found, the function gives back an
684 682
    /// empty set, so \c bar[v] will be \c false for all nodes \c v.
685 683
    ///
686 684
    /// \note This function calls \ref barrier() for each node,
687 685
    /// so it runs in \f$O(n)\f$ time.
688 686
    ///
689 687
    /// \pre Either \ref run() or \ref init() must be called before
690 688
    /// using this function.
691 689
    ///
692 690
    /// \sa barrier()
693 691
    /// \sa checkBarrier()
694 692
    template<class BarrierMap>
695 693
    void barrierMap(BarrierMap &bar) const
696 694
    {
697 695
      for(NodeIt n(_g);n!=INVALID;++n)
698 696
        bar.set(n, (*_level)[n] >= _el);
699 697
    }
700 698

	
701 699
    /// @}
702 700

	
703 701
    /// \name Checker Functions
704 702
    /// The feasibility of the results can be checked using
705 703
    /// these functions.\n
706 704
    /// Either \ref run() or \ref start() should be called before
707 705
    /// using them.
708 706

	
709 707
    ///@{
710 708

	
711 709
    ///Check if the found flow is a feasible circulation
712 710

	
713 711
    ///Check if the found flow is a feasible circulation,
714 712
    ///
715 713
    bool checkFlow() const {
716 714
      for(ArcIt e(_g);e!=INVALID;++e)
717 715
        if((*_flow)[e]<(*_lo)[e]||(*_flow)[e]>(*_up)[e]) return false;
718 716
      for(NodeIt n(_g);n!=INVALID;++n)
719 717
        {
720 718
          Value dif=-(*_delta)[n];
721 719
          for(InArcIt e(_g,n);e!=INVALID;++e) dif-=(*_flow)[e];
722 720
          for(OutArcIt e(_g,n);e!=INVALID;++e) dif+=(*_flow)[e];
723 721
          if(_tol.negative(dif)) return false;
724 722
        }
725 723
      return true;
726 724
    }
727 725

	
728 726
    ///Check whether or not the last execution provides a barrier
729 727

	
730 728
    ///Check whether or not the last execution provides a barrier.
731 729
    ///\sa barrier()
732 730
    ///\sa barrierMap()
733 731
    bool checkBarrier() const
734 732
    {
735 733
      Value delta=0;
736 734
      for(NodeIt n(_g);n!=INVALID;++n)
737 735
        if(barrier(n))
738 736
          delta-=(*_delta)[n];
739 737
      for(ArcIt e(_g);e!=INVALID;++e)
740 738
        {
741 739
          Node s=_g.source(e);
742 740
          Node t=_g.target(e);
743 741
          if(barrier(s)&&!barrier(t)) delta+=(*_up)[e];
744 742
          else if(barrier(t)&&!barrier(s)) delta-=(*_lo)[e];
745 743
        }
746 744
      return _tol.negative(delta);
747 745
    }
748 746

	
749 747
    /// @}
750 748

	
751 749
  };
752 750

	
753 751
}
754 752

	
755 753
#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 graph components.
22 22

	
23 23

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

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

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

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

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

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

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

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

	
100 100
          i1 = i2 = i3;
101 101

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

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

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

	
124 124
      typedef BaseDigraphComponent Digraph;
125 125

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
291 291
    };
292 292

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
559 559
        }
560 560

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

	
568 568

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

	
577 577
    public:
578 578

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

	
583 583
      typedef IterableDigraphComponent Digraph;
584 584

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

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

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

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

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

	
615 615

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

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

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

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

	
644 644
      /// @}
645 645

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

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

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

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

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

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

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

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

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

	
700 700
      /// @}
701 701

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

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

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

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

	
749 749
        const _Digraph& digraph;
750 750

	
751 751
      };
752 752
    };
753 753

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

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

	
768 768

	
769 769
      typedef IterableGraphComponent Graph;
770 770

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

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

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

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

	
793 793

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

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

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

	
814 814
      /// @}
815 815

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

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

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

	
842 842
      /// @}
843 843

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

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

	
862 862
          }
863 863

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

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

	
877 877
        const _Graph& graph;
878 878

	
879 879
      };
880 880
    };
881 881

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

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

	
898 898

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

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

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

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

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

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

	
934 934
        const _Digraph& digraph;
935 935

	
936 936
      };
937 937

	
938 938
    };
939 939

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

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

	
955 955

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

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

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

	
976 976
        const _Graph& graph;
977 977

	
978 978
      };
979 979

	
980 980
    };
981 981

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

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

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

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

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

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

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

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

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

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

	
1051 1051
    };
1052 1052

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

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

	
1066 1066
      typedef MappableDigraphComponent Digraph;
1067 1067

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

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

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

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

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

	
1104 1104
      };
1105 1105

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

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

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

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

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

	
1142 1142
      };
1143 1143

	
1144 1144

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

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

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

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

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

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

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

	
1201 1201
      typedef MappableGraphComponent Graph;
1202 1202

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

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

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

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

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

	
1239 1239
      };
1240 1240

	
1241 1241

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
1452 1452
      typedef _Base Base;
1453 1453

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

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

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

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

	
1481 1481
      typedef _Base Base;
1482 1482

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

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

	
1493 1493
  }
1494 1494

	
1495 1495
}
1496 1496

	
1497 1497
#endif
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-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_DFS_H
20 20
#define LEMON_DFS_H
21 21

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

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

	
33 33
namespace lemon {
34 34

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

	
37 37
  ///Default traits class of Dfs class.
38 38
  ///\tparam GR Digraph type.
39 39
  template<class GR>
40 40
  struct DfsDefaultTraits
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 %DFS paths.
47 47
    ///
48 48
    ///The type of the map that stores the predecessor
49 49
    ///arcs of the %DFS paths.
50 50
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
51 51
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
52
    ///Instantiates a PredMap.
52
    ///Instantiates a \c PredMap.
53 53

	
54
    ///This function instantiates a PredMap.
54
    ///This function instantiates a \ref PredMap.
55 55
    ///\param g is the digraph, to which we would like to define the
56
    ///PredMap.
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 meet the \ref concepts::WriteMap "WriteMap" concept.
66 66
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
67
    ///Instantiates a ProcessedMap.
67
    ///Instantiates a \c ProcessedMap.
68 68

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

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

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

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

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

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

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

	
112 112
  ///%DFS algorithm class.
113 113

	
114 114
  ///\ingroup search
115 115
  ///This class provides an efficient implementation of the %DFS algorithm.
116 116
  ///
117 117
  ///There is also a \ref dfs() "function-type interface" for the DFS
118 118
  ///algorithm, which is convenient in the simplier cases and it can be
119 119
  ///used easier.
120 120
  ///
121 121
  ///\tparam GR The type of the digraph the algorithm runs on.
122 122
  ///The default type is \ref ListDigraph.
123 123
#ifdef DOXYGEN
124 124
  template <typename GR,
125 125
            typename TR>
126 126
#else
127 127
  template <typename GR=ListDigraph,
128 128
            typename TR=DfsDefaultTraits<GR> >
129 129
#endif
130 130
  class Dfs {
131 131
  public:
132 132

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

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

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

	
151 151
  private:
152 152

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

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

	
177 177
    std::vector<typename Digraph::OutArcIt> _stack;
178 178
    int _stack_head;
179 179

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

	
201 201
  protected:
202 202

	
203 203
    Dfs() {}
204 204

	
205 205
  public:
206 206

	
207 207
    typedef Dfs Create;
208 208

	
209 209
    ///\name Named template parameters
210 210

	
211 211
    ///@{
212 212

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

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

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

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

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

	
311 311
    ///@}
312 312

	
313 313
  public:
314 314

	
315 315
    ///Constructor.
316 316

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

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

	
336 336
    ///Sets the map that stores the predecessor arcs.
337 337

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

	
354 354
    ///Sets the map that indicates which nodes are reached.
355 355

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

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

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

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

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

	
409 409
  public:
410 410

	
411 411
    ///\name Execution Control
412 412
    ///The simplest way to execute the DFS algorithm is to use one of the
413 413
    ///member functions called \ref run(Node) "run()".\n
414 414
    ///If you need more control on the execution, first you have to call
415 415
    ///\ref init(), then you can add a source node with \ref addSource()
416 416
    ///and perform the actual computation with \ref start().
417 417
    ///This procedure can be repeated if there are nodes that have not
418 418
    ///been reached.
419 419

	
420 420
    ///@{
421 421

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

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

	
439 439
    ///Adds a new source node to the set of nodes to be processed.
440 440
    ///
441 441
    ///\pre The stack must be empty. Otherwise the algorithm gives
442 442
    ///wrong results. (One of the outgoing arcs of all the source nodes
443 443
    ///except for the last one will not be visited and distances will
444 444
    ///also be wrong.)
445 445
    void addSource(Node s)
446 446
    {
447 447
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
448 448
      if(!(*_reached)[s])
449 449
        {
450 450
          _reached->set(s,true);
451 451
          _pred->set(s,INVALID);
452 452
          OutArcIt e(*G,s);
453 453
          if(e!=INVALID) {
454 454
            _stack[++_stack_head]=e;
455 455
            _dist->set(s,_stack_head);
456 456
          }
457 457
          else {
458 458
            _processed->set(s,true);
459 459
            _dist->set(s,0);
460 460
          }
461 461
        }
462 462
    }
463 463

	
464 464
    ///Processes the next arc.
465 465

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

	
497 497
    ///Next arc to be processed.
498 498

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

	
508 508
    ///Returns \c false if there are nodes to be processed.
509 509

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

	
514 514
    ///Returns the number of the nodes to be processed.
515 515

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

	
520 520
    ///Executes the algorithm.
521 521

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

	
545 545
    ///Executes the algorithm until the given target node is reached.
546 546

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

	
564 564
    ///Executes the algorithm until a condition is met.
565 565

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

	
590 590
    ///Runs the algorithm from the given source node.
591 591

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

	
611 611
    ///Finds the %DFS path between \c s and \c t.
612 612

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

	
633 633
    ///Runs the algorithm to visit all nodes in the digraph.
634 634

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

	
662 662
    ///@}
663 663

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

	
670 670
    ///@{
671 671

	
672 672
    ///The DFS path to a node.
673 673

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

	
682 682
    ///The distance of a node from the root(s).
683 683

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

	
693 693
    ///Returns the 'previous arc' of the %DFS tree for a node.
694 694

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

	
707 707
    ///Returns the 'previous node' of the %DFS tree.
708 708

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

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

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

	
742 742
    ///Checks if a node is reached from the root(s).
743 743

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

	
750 750
    ///@}
751 751
  };
752 752

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
837 837
  /// Default traits class used by DfsWizard
838 838

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

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

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

	
869 869
    public:
870 870
    /// Constructor.
871 871

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

	
877 877
    /// Constructor.
878 878

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

	
886 886
  };
887 887

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

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

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

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

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

	
922 922
  public:
923 923

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

	
927 927
    /// Constructor that requires parameters.
928 928

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

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

	
938 938
    ~DfsWizard() {}
939 939

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

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

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

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

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

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

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

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

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

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

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

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

	
1096 1096
  };
1097 1097

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

	
1100 1100
  ///\ingroup search
1101 1101
  ///Function-type interface for DFS algorithm.
1102 1102
  ///
1103 1103
  ///This function also has several \ref named-func-param "named parameters",
1104 1104
  ///they are declared as the members of class \ref DfsWizard.
1105 1105
  ///The following examples show how to use these parameters.
1106 1106
  ///\code
1107 1107
  ///  // Compute the DFS tree
1108 1108
  ///  dfs(g).predMap(preds).distMap(dists).run(s);
1109 1109
  ///
1110 1110
  ///  // Compute the DFS path from s to t
1111 1111
  ///  bool reached = dfs(g).path(p).dist(d).run(s,t);
1112 1112
  ///\endcode
1113 1113
  ///\warning Don't forget to put the \ref DfsWizard::run(Node) "run()"
1114 1114
  ///to the end of the parameter list.
1115 1115
  ///\sa DfsWizard
1116 1116
  ///\sa Dfs
1117 1117
  template<class GR>
1118 1118
  DfsWizard<DfsWizardBase<GR> >
1119 1119
  dfs(const GR &digraph)
1120 1120
  {
1121 1121
    return DfsWizard<DfsWizardBase<GR> >(digraph);
1122 1122
  }
1123 1123

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

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

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

	
1205 1205
    /// \brief The type of the digraph the algorithm runs on.
1206
    typedef _Digraph Digraph;
1206
    typedef GR Digraph;
1207 1207

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

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

	
1223 1223
  };
1224 1224

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

	
1264 1264
    ///The traits class.
1265
    typedef _Traits Traits;
1265
    typedef TR Traits;
1266 1266

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

	
1270 1270
    ///The visitor type used by the algorithm.
1271
    typedef _Visitor Visitor;
1271
    typedef VS Visitor;
1272 1272

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

	
1276 1276
  private:
1277 1277

	
1278 1278
    typedef typename Digraph::Node Node;
1279 1279
    typedef typename Digraph::NodeIt NodeIt;
1280 1280
    typedef typename Digraph::Arc Arc;
1281 1281
    typedef typename Digraph::OutArcIt OutArcIt;
1282 1282

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

	
1292 1292
    std::vector<typename Digraph::Arc> _stack;
1293 1293
    int _stack_head;
1294 1294

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

	
1303 1303
  protected:
1304 1304

	
1305 1305
    DfsVisit() {}
1306 1306

	
1307 1307
  public:
1308 1308

	
1309 1309
    typedef DfsVisit Create;
1310 1310

	
1311 1311
    /// \name Named Template Parameters
1312 1312

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

	
1333 1333
  public:
1334 1334

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

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

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

	
1367 1367
  public:
1368 1368

	
1369 1369
    /// \name Execution Control
1370 1370
    /// The simplest way to execute the DFS algorithm is to use one of the
1371 1371
    /// member functions called \ref run(Node) "run()".\n
1372 1372
    /// If you need more control on the execution, first you have to call
1373 1373
    /// \ref init(), then you can add a source node with \ref addSource()
1374 1374
    /// and perform the actual computation with \ref start().
1375 1375
    /// This procedure can be repeated if there are nodes that have not
1376 1376
    /// been reached.
1377 1377

	
1378 1378
    /// @{
1379 1379

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

	
1392 1392
    /// \brief Adds a new source node.
1393 1393
    ///
1394 1394
    /// Adds a new source node to the set of nodes to be processed.
1395 1395
    ///
1396 1396
    /// \pre The stack must be empty. Otherwise the algorithm gives
1397 1397
    /// wrong results. (One of the outgoing arcs of all the source nodes
1398 1398
    /// except for the last one will not be visited and distances will
1399 1399
    /// also be wrong.)
1400 1400
    void addSource(Node s)
1401 1401
    {
1402 1402
      LEMON_DEBUG(emptyQueue(), "The stack is not empty.");
1403 1403
      if(!(*_reached)[s]) {
1404 1404
          _reached->set(s,true);
1405 1405
          _visitor->start(s);
1406 1406
          _visitor->reach(s);
1407 1407
          Arc e;
1408 1408
          _digraph->firstOut(e, s);
1409 1409
          if (e != INVALID) {
1410 1410
            _stack[++_stack_head] = e;
1411 1411
          } else {
1412 1412
            _visitor->leave(s);
1413 1413
            _visitor->stop(s);
1414 1414
          }
1415 1415
        }
1416 1416
    }
1417 1417

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

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

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

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

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

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

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

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

	
1562 1562
    /// \brief Finds the %DFS path between \c s and \c t.
1563 1563

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

	
1584 1584
    /// \brief Runs the algorithm to visit all nodes in the digraph.
1585 1585

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

	
1613 1613
    ///@}
1614 1614

	
1615 1615
    /// \name Query Functions
1616 1616
    /// The results of the DFS algorithm can be obtained using these
1617 1617
    /// functions.\n
1618 1618
    /// Either \ref run(Node) "run()" or \ref start() should be called
1619 1619
    /// before using them.
1620 1620

	
1621 1621
    ///@{
1622 1622

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

	
1631 1631
    ///@}
1632 1632

	
1633 1633
  };
1634 1634

	
1635 1635
} //END OF NAMESPACE LEMON
1636 1636

	
1637 1637
#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_DIJKSTRA_H
20 20
#define LEMON_DIJKSTRA_H
21 21

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

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

	
35 35
namespace lemon {
36 36

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

	
57 57
  ///Default traits class of Dijkstra class.
58 58

	
59 59
  ///Default traits class of Dijkstra class.
60 60
  ///\tparam GR The type of the digraph.
61 61
  ///\tparam LM The type of the length map.
62 62
  template<class GR, class LM>
63 63
  struct DijkstraDefaultTraits
64 64
  {
65 65
    ///The type of the digraph the algorithm runs on.
66 66
    typedef GR Digraph;
67 67

	
68 68
    ///The type of the map that stores the arc lengths.
69 69

	
70 70
    ///The type of the map that stores the arc lengths.
71 71
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
72 72
    typedef LM LengthMap;
73 73
    ///The type of the length of the arcs.
74 74
    typedef typename LM::Value Value;
75 75

	
76
    /// Operation traits for Dijkstra algorithm.
76
    /// Operation traits for %Dijkstra algorithm.
77 77

	
78 78
    /// This class defines the operations that are used in the algorithm.
79 79
    /// \see DijkstraDefaultOperationTraits
80 80
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
81 81

	
82 82
    /// The cross reference type used by the heap.
83 83

	
84 84
    /// The cross reference type used by the heap.
85 85
    /// Usually it is \c Digraph::NodeMap<int>.
86 86
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
87
    ///Instantiates a \ref HeapCrossRef.
87
    ///Instantiates a \c HeapCrossRef.
88 88

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

	
97
    ///The heap type used by the Dijkstra algorithm.
97
    ///The heap type used by the %Dijkstra algorithm.
98 98

	
99 99
    ///The heap type used by the Dijkstra algorithm.
100 100
    ///
101 101
    ///\sa BinHeap
102 102
    ///\sa Dijkstra
103 103
    typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap;
104
    ///Instantiates a \ref Heap.
104
    ///Instantiates a \c Heap.
105 105

	
106 106
    ///This function instantiates a \ref Heap.
107 107
    static Heap *createHeap(HeapCrossRef& r)
108 108
    {
109 109
      return new Heap(r);
110 110
    }
111 111

	
112 112
    ///\brief The type of the map that stores the predecessor
113 113
    ///arcs of the shortest paths.
114 114
    ///
115 115
    ///The type of the map that stores the predecessor
116 116
    ///arcs of the shortest paths.
117 117
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
118 118
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
119
    ///Instantiates a PredMap.
119
    ///Instantiates a \c PredMap.
120 120

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

	
129 129
    ///The type of the map that indicates which nodes are processed.
130 130

	
131 131
    ///The type of the map that indicates which nodes are processed.
132 132
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
133 133
    ///By default it is a NullMap.
134 134
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
135
    ///Instantiates a ProcessedMap.
135
    ///Instantiates a \c ProcessedMap.
136 136

	
137
    ///This function instantiates a ProcessedMap.
137
    ///This function instantiates a \ref ProcessedMap.
138 138
    ///\param g is the digraph, to which
139
    ///we would like to define the ProcessedMap
139
    ///we would like to define the \ref ProcessedMap.
140 140
#ifdef DOXYGEN
141 141
    static ProcessedMap *createProcessedMap(const Digraph &g)
142 142
#else
143 143
    static ProcessedMap *createProcessedMap(const Digraph &)
144 144
#endif
145 145
    {
146 146
      return new ProcessedMap();
147 147
    }
148 148

	
149 149
    ///The type of the map that stores the distances of the nodes.
150 150

	
151 151
    ///The type of the map that stores the distances of the nodes.
152 152
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
153 153
    typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
154
    ///Instantiates a DistMap.
154
    ///Instantiates a \c DistMap.
155 155

	
156
    ///This function instantiates a DistMap.
156
    ///This function instantiates a \ref DistMap.
157 157
    ///\param g is the digraph, to which we would like to define
158
    ///the DistMap
158
    ///the \ref DistMap.
159 159
    static DistMap *createDistMap(const Digraph &g)
160 160
    {
161 161
      return new DistMap(g);
162 162
    }
163 163
  };
164 164

	
165 165
  ///%Dijkstra algorithm class.
166 166

	
167 167
  /// \ingroup shortest_path
168 168
  ///This class provides an efficient implementation of the %Dijkstra algorithm.
169 169
  ///
170 170
  ///The arc lengths are passed to the algorithm using a
171 171
  ///\ref concepts::ReadMap "ReadMap",
172 172
  ///so it is easy to change it to any kind of length.
173 173
  ///The type of the length is determined by the
174 174
  ///\ref concepts::ReadMap::Value "Value" of the length map.
175 175
  ///It is also possible to change the underlying priority heap.
176 176
  ///
177 177
  ///There is also a \ref dijkstra() "function-type interface" for the
178 178
  ///%Dijkstra algorithm, which is convenient in the simplier cases and
179 179
  ///it can be used easier.
180 180
  ///
181 181
  ///\tparam GR The type of the digraph the algorithm runs on.
182 182
  ///The default type is \ref ListDigraph.
183 183
  ///\tparam LM A \ref concepts::ReadMap "readable" arc map that specifies
184 184
  ///the lengths of the arcs.
185 185
  ///It is read once for each arc, so the map may involve in
186 186
  ///relatively time consuming process to compute the arc lengths if
187 187
  ///it is necessary. The default map type is \ref
188 188
  ///concepts::Digraph::ArcMap "GR::ArcMap<int>".
189 189
#ifdef DOXYGEN
190 190
  template <typename GR, typename LM, typename TR>
191 191
#else
192 192
  template <typename GR=ListDigraph,
193 193
            typename LM=typename GR::template ArcMap<int>,
194 194
            typename TR=DijkstraDefaultTraits<GR,LM> >
195 195
#endif
196 196
  class Dijkstra {
197 197
  public:
198 198

	
199 199
    ///The type of the digraph the algorithm runs on.
200 200
    typedef typename TR::Digraph Digraph;
201 201

	
202 202
    ///The type of the length of the arcs.
203 203
    typedef typename TR::LengthMap::Value Value;
204 204
    ///The type of the map that stores the arc lengths.
205 205
    typedef typename TR::LengthMap LengthMap;
206 206
    ///\brief The type of the map that stores the predecessor arcs of the
207 207
    ///shortest paths.
208 208
    typedef typename TR::PredMap PredMap;
209 209
    ///The type of the map that stores the distances of the nodes.
210 210
    typedef typename TR::DistMap DistMap;
211 211
    ///The type of the map that indicates which nodes are processed.
212 212
    typedef typename TR::ProcessedMap ProcessedMap;
213 213
    ///The type of the paths.
214 214
    typedef PredMapPath<Digraph, PredMap> Path;
215 215
    ///The cross reference type used for the current heap.
216 216
    typedef typename TR::HeapCrossRef HeapCrossRef;
217 217
    ///The heap type used by the algorithm.
218 218
    typedef typename TR::Heap Heap;
219
    ///The operation traits class.
219
    ///\brief The \ref DijkstraDefaultOperationTraits "operation traits class"
220
    ///of the algorithm.
220 221
    typedef typename TR::OperationTraits OperationTraits;
221 222

	
222 223
    ///The \ref DijkstraDefaultTraits "traits class" of the algorithm.
223 224
    typedef TR Traits;
224 225

	
225 226
  private:
226 227

	
227 228
    typedef typename Digraph::Node Node;
228 229
    typedef typename Digraph::NodeIt NodeIt;
229 230
    typedef typename Digraph::Arc Arc;
230 231
    typedef typename Digraph::OutArcIt OutArcIt;
231 232

	
232 233
    //Pointer to the underlying digraph.
233 234
    const Digraph *G;
234 235
    //Pointer to the length map.
235
    const LengthMap *length;
236
    const LengthMap *_length;
236 237
    //Pointer to the map of predecessors arcs.
237 238
    PredMap *_pred;
238 239
    //Indicates if _pred is locally allocated (true) or not.
239 240
    bool local_pred;
240 241
    //Pointer to the map of distances.
241 242
    DistMap *_dist;
242 243
    //Indicates if _dist is locally allocated (true) or not.
243 244
    bool local_dist;
244 245
    //Pointer to the map of processed status of the nodes.
245 246
    ProcessedMap *_processed;
246 247
    //Indicates if _processed is locally allocated (true) or not.
247 248
    bool local_processed;
248 249
    //Pointer to the heap cross references.
249 250
    HeapCrossRef *_heap_cross_ref;
250 251
    //Indicates if _heap_cross_ref is locally allocated (true) or not.
251 252
    bool local_heap_cross_ref;
252 253
    //Pointer to the heap.
253 254
    Heap *_heap;
254 255
    //Indicates if _heap is locally allocated (true) or not.
255 256
    bool local_heap;
256 257

	
257 258
    //Creates the maps if necessary.
258 259
    void create_maps()
259 260
    {
260 261
      if(!_pred) {
261 262
        local_pred = true;
262 263
        _pred = Traits::createPredMap(*G);
263 264
      }
264 265
      if(!_dist) {
265 266
        local_dist = true;
266 267
        _dist = Traits::createDistMap(*G);
267 268
      }
268 269
      if(!_processed) {
269 270
        local_processed = true;
270 271
        _processed = Traits::createProcessedMap(*G);
271 272
      }
272 273
      if (!_heap_cross_ref) {
273 274
        local_heap_cross_ref = true;
274 275
        _heap_cross_ref = Traits::createHeapCrossRef(*G);
275 276
      }
276 277
      if (!_heap) {
277 278
        local_heap = true;
278 279
        _heap = Traits::createHeap(*_heap_cross_ref);
279 280
      }
280 281
    }
281 282

	
282 283
  public:
283 284

	
284 285
    typedef Dijkstra Create;
285 286

	
286 287
    ///\name Named template parameters
287 288

	
288 289
    ///@{
289 290

	
290 291
    template <class T>
291 292
    struct SetPredMapTraits : public Traits {
292 293
      typedef T PredMap;
293 294
      static PredMap *createPredMap(const Digraph &)
294 295
      {
295 296
        LEMON_ASSERT(false, "PredMap is not initialized");
296 297
        return 0; // ignore warnings
297 298
      }
298 299
    };
299 300
    ///\brief \ref named-templ-param "Named parameter" for setting
300
    ///PredMap type.
301
    ///\c PredMap type.
301 302
    ///
302 303
    ///\ref named-templ-param "Named parameter" for setting
303
    ///PredMap type.
304
    ///\c PredMap type.
304 305
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
305 306
    template <class T>
306 307
    struct SetPredMap
307 308
      : public Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > {
308 309
      typedef Dijkstra< Digraph, LengthMap, SetPredMapTraits<T> > Create;
309 310
    };
310 311

	
311 312
    template <class T>
312 313
    struct SetDistMapTraits : public Traits {
313 314
      typedef T DistMap;
314 315
      static DistMap *createDistMap(const Digraph &)
315 316
      {
316 317
        LEMON_ASSERT(false, "DistMap is not initialized");
317 318
        return 0; // ignore warnings
318 319
      }
319 320
    };
320 321
    ///\brief \ref named-templ-param "Named parameter" for setting
321
    ///DistMap type.
322
    ///\c DistMap type.
322 323
    ///
323 324
    ///\ref named-templ-param "Named parameter" for setting
324
    ///DistMap type.
325
    ///\c DistMap type.
325 326
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
326 327
    template <class T>
327 328
    struct SetDistMap
328 329
      : public Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > {
329 330
      typedef Dijkstra< Digraph, LengthMap, SetDistMapTraits<T> > Create;
330 331
    };
331 332

	
332 333
    template <class T>
333 334
    struct SetProcessedMapTraits : public Traits {
334 335
      typedef T ProcessedMap;
335 336
      static ProcessedMap *createProcessedMap(const Digraph &)
336 337
      {
337 338
        LEMON_ASSERT(false, "ProcessedMap is not initialized");
338 339
        return 0; // ignore warnings
339 340
      }
340 341
    };
341 342
    ///\brief \ref named-templ-param "Named parameter" for setting
342
    ///ProcessedMap type.
343
    ///\c ProcessedMap type.
343 344
    ///
344 345
    ///\ref named-templ-param "Named parameter" for setting
345
    ///ProcessedMap type.
346
    ///\c ProcessedMap type.
346 347
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
347 348
    template <class T>
348 349
    struct SetProcessedMap
349 350
      : public Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > {
350 351
      typedef Dijkstra< Digraph, LengthMap, SetProcessedMapTraits<T> > Create;
351 352
    };
352 353

	
353 354
    struct SetStandardProcessedMapTraits : public Traits {
354 355
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
355 356
      static ProcessedMap *createProcessedMap(const Digraph &g)
356 357
      {
357 358
        return new ProcessedMap(g);
358 359
      }
359 360
    };
360 361
    ///\brief \ref named-templ-param "Named parameter" for setting
361
    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
362
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
362 363
    ///
363 364
    ///\ref named-templ-param "Named parameter" for setting
364
    ///ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
365
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
365 366
    ///If you don't set it explicitly, it will be automatically allocated.
366 367
    struct SetStandardProcessedMap
367 368
      : public Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits > {
368 369
      typedef Dijkstra< Digraph, LengthMap, SetStandardProcessedMapTraits >
369 370
      Create;
370 371
    };
371 372

	
372 373
    template <class H, class CR>
373 374
    struct SetHeapTraits : public Traits {
374 375
      typedef CR HeapCrossRef;
375 376
      typedef H Heap;
376 377
      static HeapCrossRef *createHeapCrossRef(const Digraph &) {
377 378
        LEMON_ASSERT(false, "HeapCrossRef is not initialized");
378 379
        return 0; // ignore warnings
379 380
      }
380 381
      static Heap *createHeap(HeapCrossRef &)
381 382
      {
382 383
        LEMON_ASSERT(false, "Heap is not initialized");
383 384
        return 0; // ignore warnings
384 385
      }
385 386
    };
386 387
    ///\brief \ref named-templ-param "Named parameter" for setting
387 388
    ///heap and cross reference types
388 389
    ///
389 390
    ///\ref named-templ-param "Named parameter" for setting heap and cross
390 391
    ///reference types. If this named parameter is used, then external
391 392
    ///heap and cross reference objects must be passed to the algorithm
392 393
    ///using the \ref heap() function before calling \ref run(Node) "run()"
393 394
    ///or \ref init().
394 395
    ///\sa SetStandardHeap
395 396
    template <class H, class CR = typename Digraph::template NodeMap<int> >
396 397
    struct SetHeap
397 398
      : public Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > {
398 399
      typedef Dijkstra< Digraph, LengthMap, SetHeapTraits<H, CR> > Create;
399 400
    };
400 401

	
401 402
    template <class H, class CR>
402 403
    struct SetStandardHeapTraits : public Traits {
403 404
      typedef CR HeapCrossRef;
404 405
      typedef H Heap;
405 406
      static HeapCrossRef *createHeapCrossRef(const Digraph &G) {
406 407
        return new HeapCrossRef(G);
407 408
      }
408 409
      static Heap *createHeap(HeapCrossRef &R)
409 410
      {
410 411
        return new Heap(R);
411 412
      }
412 413
    };
413 414
    ///\brief \ref named-templ-param "Named parameter" for setting
414 415
    ///heap and cross reference types with automatic allocation
415 416
    ///
416 417
    ///\ref named-templ-param "Named parameter" for setting heap and cross
417 418
    ///reference types with automatic allocation.
418 419
    ///They should have standard constructor interfaces to be able to
419 420
    ///automatically created by the algorithm (i.e. the digraph should be
420 421
    ///passed to the constructor of the cross reference and the cross
421 422
    ///reference should be passed to the constructor of the heap).
422 423
    ///However external heap and cross reference objects could also be
423 424
    ///passed to the algorithm using the \ref heap() function before
424 425
    ///calling \ref run(Node) "run()" or \ref init().
425 426
    ///\sa SetHeap
426 427
    template <class H, class CR = typename Digraph::template NodeMap<int> >
427 428
    struct SetStandardHeap
428 429
      : public Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> > {
429 430
      typedef Dijkstra< Digraph, LengthMap, SetStandardHeapTraits<H, CR> >
430 431
      Create;
431 432
    };
432 433

	
433 434
    template <class T>
434 435
    struct SetOperationTraitsTraits : public Traits {
435 436
      typedef T OperationTraits;
436 437
    };
437 438

	
438 439
    /// \brief \ref named-templ-param "Named parameter" for setting
439 440
    ///\c OperationTraits type
440 441
    ///
441 442
    ///\ref named-templ-param "Named parameter" for setting
442
    ///\ref OperationTraits type.
443
    ///\c OperationTraits type.
443 444
    template <class T>
444 445
    struct SetOperationTraits
445 446
      : public Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> > {
446 447
      typedef Dijkstra<Digraph, LengthMap, SetOperationTraitsTraits<T> >
447 448
      Create;
448 449
    };
449 450

	
450 451
    ///@}
451 452

	
452 453
  protected:
453 454

	
454 455
    Dijkstra() {}
455 456

	
456 457
  public:
457 458

	
458 459
    ///Constructor.
459 460

	
460 461
    ///Constructor.
461
    ///\param _g The digraph the algorithm runs on.
462
    ///\param _length The length map used by the algorithm.
463
    Dijkstra(const Digraph& _g, const LengthMap& _length) :
464
      G(&_g), length(&_length),
462
    ///\param g The digraph the algorithm runs on.
463
    ///\param length The length map used by the algorithm.
464
    Dijkstra(const Digraph& g, const LengthMap& length) :
465
      G(&g), _length(&length),
465 466
      _pred(NULL), local_pred(false),
466 467
      _dist(NULL), local_dist(false),
467 468
      _processed(NULL), local_processed(false),
468 469
      _heap_cross_ref(NULL), local_heap_cross_ref(false),
469 470
      _heap(NULL), local_heap(false)
470 471
    { }
471 472

	
472 473
    ///Destructor.
473 474
    ~Dijkstra()
474 475
    {
475 476
      if(local_pred) delete _pred;
476 477
      if(local_dist) delete _dist;
477 478
      if(local_processed) delete _processed;
478 479
      if(local_heap_cross_ref) delete _heap_cross_ref;
479 480
      if(local_heap) delete _heap;
480 481
    }
481 482

	
482 483
    ///Sets the length map.
483 484

	
484 485
    ///Sets the length map.
485 486
    ///\return <tt> (*this) </tt>
486 487
    Dijkstra &lengthMap(const LengthMap &m)
487 488
    {
488
      length = &m;
489
      _length = &m;
489 490
      return *this;
490 491
    }
491 492

	
492 493
    ///Sets the map that stores the predecessor arcs.
493 494

	
494 495
    ///Sets the map that stores the predecessor arcs.
495 496
    ///If you don't use this function before calling \ref run(Node) "run()"
496 497
    ///or \ref init(), an instance will be allocated automatically.
497 498
    ///The destructor deallocates this automatically allocated map,
498 499
    ///of course.
499 500
    ///\return <tt> (*this) </tt>
500 501
    Dijkstra &predMap(PredMap &m)
501 502
    {
502 503
      if(local_pred) {
503 504
        delete _pred;
504 505
        local_pred=false;
505 506
      }
506 507
      _pred = &m;
507 508
      return *this;
508 509
    }
509 510

	
510 511
    ///Sets the map that indicates which nodes are processed.
511 512

	
512 513
    ///Sets the map that indicates which nodes are processed.
513 514
    ///If you don't use this function before calling \ref run(Node) "run()"
514 515
    ///or \ref init(), an instance will be allocated automatically.
515 516
    ///The destructor deallocates this automatically allocated map,
516 517
    ///of course.
517 518
    ///\return <tt> (*this) </tt>
518 519
    Dijkstra &processedMap(ProcessedMap &m)
519 520
    {
520 521
      if(local_processed) {
521 522
        delete _processed;
522 523
        local_processed=false;
523 524
      }
524 525
      _processed = &m;
525 526
      return *this;
526 527
    }
527 528

	
528 529
    ///Sets the map that stores the distances of the nodes.
529 530

	
530 531
    ///Sets the map that stores the distances of the nodes calculated by the
531 532
    ///algorithm.
532 533
    ///If you don't use this function before calling \ref run(Node) "run()"
533 534
    ///or \ref init(), an instance will be allocated automatically.
534 535
    ///The destructor deallocates this automatically allocated map,
535 536
    ///of course.
536 537
    ///\return <tt> (*this) </tt>
537 538
    Dijkstra &distMap(DistMap &m)
538 539
    {
539 540
      if(local_dist) {
540 541
        delete _dist;
541 542
        local_dist=false;
542 543
      }
543 544
      _dist = &m;
544 545
      return *this;
545 546
    }
546 547

	
547 548
    ///Sets the heap and the cross reference used by algorithm.
548 549

	
549 550
    ///Sets the heap and the cross reference used by algorithm.
550 551
    ///If you don't use this function before calling \ref run(Node) "run()"
551 552
    ///or \ref init(), heap and cross reference instances will be
552 553
    ///allocated automatically.
553 554
    ///The destructor deallocates these automatically allocated objects,
554 555
    ///of course.
555 556
    ///\return <tt> (*this) </tt>
556 557
    Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
557 558
    {
558 559
      if(local_heap_cross_ref) {
559 560
        delete _heap_cross_ref;
560 561
        local_heap_cross_ref=false;
561 562
      }
562 563
      _heap_cross_ref = &cr;
563 564
      if(local_heap) {
564 565
        delete _heap;
565 566
        local_heap=false;
566 567
      }
567 568
      _heap = &hp;
568 569
      return *this;
569 570
    }
570 571

	
571 572
  private:
572 573

	
573 574
    void finalizeNodeData(Node v,Value dst)
574 575
    {
575 576
      _processed->set(v,true);
576 577
      _dist->set(v, dst);
577 578
    }
578 579

	
579 580
  public:
580 581

	
581 582
    ///\name Execution Control
582 583
    ///The simplest way to execute the %Dijkstra algorithm is to use
583 584
    ///one of the member functions called \ref run(Node) "run()".\n
584 585
    ///If you need more control on the execution, first you have to call
585 586
    ///\ref init(), then you can add several source nodes with
586 587
    ///\ref addSource(). Finally the actual path computation can be
587 588
    ///performed with one of the \ref start() functions.
588 589

	
589 590
    ///@{
590 591

	
591 592
    ///\brief Initializes the internal data structures.
592 593
    ///
593 594
    ///Initializes the internal data structures.
594 595
    void init()
595 596
    {
596 597
      create_maps();
597 598
      _heap->clear();
598 599
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
599 600
        _pred->set(u,INVALID);
600 601
        _processed->set(u,false);
601 602
        _heap_cross_ref->set(u,Heap::PRE_HEAP);
602 603
      }
603 604
    }
604 605

	
605 606
    ///Adds a new source node.
606 607

	
607 608
    ///Adds a new source node to the priority heap.
608 609
    ///The optional second parameter is the initial distance of the node.
609 610
    ///
610 611
    ///The function checks if the node has already been added to the heap and
611 612
    ///it is pushed to the heap only if either it was not in the heap
612 613
    ///or the shortest path found till then is shorter than \c dst.
613 614
    void addSource(Node s,Value dst=OperationTraits::zero())
614 615
    {
615 616
      if(_heap->state(s) != Heap::IN_HEAP) {
616 617
        _heap->push(s,dst);
617 618
      } else if(OperationTraits::less((*_heap)[s], dst)) {
618 619
        _heap->set(s,dst);
619 620
        _pred->set(s,INVALID);
620 621
      }
621 622
    }
622 623

	
623 624
    ///Processes the next node in the priority heap
624 625

	
625 626
    ///Processes the next node in the priority heap.
626 627
    ///
627 628
    ///\return The processed node.
628 629
    ///
629 630
    ///\warning The priority heap must not be empty.
630 631
    Node processNextNode()
631 632
    {
632 633
      Node v=_heap->top();
633 634
      Value oldvalue=_heap->prio();
634 635
      _heap->pop();
635 636
      finalizeNodeData(v,oldvalue);
636 637

	
637 638
      for(OutArcIt e(*G,v); e!=INVALID; ++e) {
638 639
        Node w=G->target(e);
639 640
        switch(_heap->state(w)) {
640 641
        case Heap::PRE_HEAP:
641
          _heap->push(w,OperationTraits::plus(oldvalue, (*length)[e]));
642
          _heap->push(w,OperationTraits::plus(oldvalue, (*_length)[e]));
642 643
          _pred->set(w,e);
643 644
          break;
644 645
        case Heap::IN_HEAP:
645 646
          {
646
            Value newvalue = OperationTraits::plus(oldvalue, (*length)[e]);
647
            Value newvalue = OperationTraits::plus(oldvalue, (*_length)[e]);
647 648
            if ( OperationTraits::less(newvalue, (*_heap)[w]) ) {
648 649
              _heap->decrease(w, newvalue);
649 650
              _pred->set(w,e);
650 651
            }
651 652
          }
652 653
          break;
653 654
        case Heap::POST_HEAP:
654 655
          break;
655 656
        }
656 657
      }
657 658
      return v;
658 659
    }
659 660

	
660 661
    ///The next node to be processed.
661 662

	
662 663
    ///Returns the next node to be processed or \c INVALID if the
663 664
    ///priority heap is empty.
664 665
    Node nextNode() const
665 666
    {
666 667
      return !_heap->empty()?_heap->top():INVALID;
667 668
    }
668 669

	
669 670
    ///Returns \c false if there are nodes to be processed.
670 671

	
671 672
    ///Returns \c false if there are nodes to be processed
672 673
    ///in the priority heap.
673 674
    bool emptyQueue() const { return _heap->empty(); }
674 675

	
675 676
    ///Returns the number of the nodes to be processed.
676 677

	
677 678
    ///Returns the number of the nodes to be processed
678 679
    ///in the priority heap.
679 680
    int queueSize() const { return _heap->size(); }
680 681

	
681 682
    ///Executes the algorithm.
682 683

	
683 684
    ///Executes the algorithm.
684 685
    ///
685 686
    ///This method runs the %Dijkstra algorithm from the root node(s)
686 687
    ///in order to compute the shortest path to each node.
687 688
    ///
688 689
    ///The algorithm computes
689 690
    ///- the shortest path tree (forest),
690 691
    ///- the distance of each node from the root(s).
691 692
    ///
692 693
    ///\pre init() must be called and at least one root node should be
693 694
    ///added with addSource() before using this function.
694 695
    ///
695 696
    ///\note <tt>d.start()</tt> is just a shortcut of the following code.
696 697
    ///\code
697 698
    ///  while ( !d.emptyQueue() ) {
698 699
    ///    d.processNextNode();
699 700
    ///  }
700 701
    ///\endcode
701 702
    void start()
702 703
    {
703 704
      while ( !emptyQueue() ) processNextNode();
704 705
    }
705 706

	
706 707
    ///Executes the algorithm until the given target node is processed.
707 708

	
708 709
    ///Executes the algorithm until the given target node is processed.
709 710
    ///
710 711
    ///This method runs the %Dijkstra algorithm from the root node(s)
711 712
    ///in order to compute the shortest path to \c t.
712 713
    ///
713 714
    ///The algorithm computes
714 715
    ///- the shortest path to \c t,
715 716
    ///- the distance of \c t from the root(s).
716 717
    ///
717 718
    ///\pre init() must be called and at least one root node should be
718 719
    ///added with addSource() before using this function.
719 720
    void start(Node t)
720 721
    {
721 722
      while ( !_heap->empty() && _heap->top()!=t ) processNextNode();
722 723
      if ( !_heap->empty() ) {
723 724
        finalizeNodeData(_heap->top(),_heap->prio());
724 725
        _heap->pop();
725 726
      }
726 727
    }
727 728

	
728 729
    ///Executes the algorithm until a condition is met.
729 730

	
730 731
    ///Executes the algorithm until a condition is met.
731 732
    ///
732 733
    ///This method runs the %Dijkstra algorithm from the root node(s) in
733 734
    ///order to compute the shortest path to a node \c v with
734 735
    /// <tt>nm[v]</tt> true, if such a node can be found.
735 736
    ///
736 737
    ///\param nm A \c bool (or convertible) node map. The algorithm
737 738
    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
738 739
    ///
739 740
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
740 741
    ///\c INVALID if no such node was found.
741 742
    ///
742 743
    ///\pre init() must be called and at least one root node should be
743 744
    ///added with addSource() before using this function.
744 745
    template<class NodeBoolMap>
745 746
    Node start(const NodeBoolMap &nm)
746 747
    {
747 748
      while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
748 749
      if ( _heap->empty() ) return INVALID;
749 750
      finalizeNodeData(_heap->top(),_heap->prio());
750 751
      return _heap->top();
751 752
    }
752 753

	
753 754
    ///Runs the algorithm from the given source node.
754 755

	
755 756
    ///This method runs the %Dijkstra algorithm from node \c s
756 757
    ///in order to compute the shortest path to each node.
757 758
    ///
758 759
    ///The algorithm computes
759 760
    ///- the shortest path tree,
760 761
    ///- the distance of each node from the root.
761 762
    ///
762 763
    ///\note <tt>d.run(s)</tt> is just a shortcut of the following code.
763 764
    ///\code
764 765
    ///  d.init();
765 766
    ///  d.addSource(s);
766 767
    ///  d.start();
767 768
    ///\endcode
768 769
    void run(Node s) {
769 770
      init();
770 771
      addSource(s);
771 772
      start();
772 773
    }
773 774

	
774 775
    ///Finds the shortest path between \c s and \c t.
775 776

	
776 777
    ///This method runs the %Dijkstra algorithm from node \c s
777 778
    ///in order to compute the shortest path to node \c t
778 779
    ///(it stops searching when \c t is processed).
779 780
    ///
780 781
    ///\return \c true if \c t is reachable form \c s.
781 782
    ///
782 783
    ///\note Apart from the return value, <tt>d.run(s,t)</tt> is just a
783 784
    ///shortcut of the following code.
784 785
    ///\code
785 786
    ///  d.init();
786 787
    ///  d.addSource(s);
787 788
    ///  d.start(t);
788 789
    ///\endcode
789 790
    bool run(Node s,Node t) {
790 791
      init();
791 792
      addSource(s);
792 793
      start(t);
793 794
      return (*_heap_cross_ref)[t] == Heap::POST_HEAP;
794 795
    }
795 796

	
796 797
    ///@}
797 798

	
798 799
    ///\name Query Functions
799 800
    ///The results of the %Dijkstra algorithm can be obtained using these
800 801
    ///functions.\n
801 802
    ///Either \ref run(Node) "run()" or \ref start() should be called
802 803
    ///before using them.
803 804

	
804 805
    ///@{
805 806

	
806 807
    ///The shortest path to a node.
807 808

	
808 809
    ///Returns the shortest path to a node.
809 810
    ///
810 811
    ///\warning \c t should be reached from the root(s).
811 812
    ///
812 813
    ///\pre Either \ref run(Node) "run()" or \ref init()
813 814
    ///must be called before using this function.
814 815
    Path path(Node t) const { return Path(*G, *_pred, t); }
815 816

	
816 817
    ///The distance of a node from the root(s).
817 818

	
818 819
    ///Returns the distance of a node from the root(s).
819 820
    ///
820 821
    ///\warning If node \c v is not reached from the root(s), then
821 822
    ///the return value of this function is undefined.
822 823
    ///
823 824
    ///\pre Either \ref run(Node) "run()" or \ref init()
824 825
    ///must be called before using this function.
825 826
    Value dist(Node v) const { return (*_dist)[v]; }
826 827

	
827 828
    ///Returns the 'previous arc' of the shortest path tree for a node.
828 829

	
829 830
    ///This function returns the 'previous arc' of the shortest path
830 831
    ///tree for the node \c v, i.e. it returns the last arc of a
831 832
    ///shortest path from a root to \c v. It is \c INVALID if \c v
832 833
    ///is not reached from the root(s) or if \c v is a root.
833 834
    ///
834 835
    ///The shortest path tree used here is equal to the shortest path
835 836
    ///tree used in \ref predNode().
836 837
    ///
837 838
    ///\pre Either \ref run(Node) "run()" or \ref init()
838 839
    ///must be called before using this function.
839 840
    Arc predArc(Node v) const { return (*_pred)[v]; }
840 841

	
841 842
    ///Returns the 'previous node' of the shortest path tree for a node.
842 843

	
843 844
    ///This function returns the 'previous node' of the shortest path
844 845
    ///tree for the node \c v, i.e. it returns the last but one node
845 846
    ///from a shortest path from a root to \c v. It is \c INVALID
846 847
    ///if \c v is not reached from the root(s) or if \c v is a root.
847 848
    ///
848 849
    ///The shortest path tree used here is equal to the shortest path
849 850
    ///tree used in \ref predArc().
850 851
    ///
851 852
    ///\pre Either \ref run(Node) "run()" or \ref init()
852 853
    ///must be called before using this function.
853 854
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
854 855
                                  G->source((*_pred)[v]); }
855 856

	
856 857
    ///\brief Returns a const reference to the node map that stores the
857 858
    ///distances of the nodes.
858 859
    ///
859 860
    ///Returns a const reference to the node map that stores the distances
860 861
    ///of the nodes calculated by the algorithm.
861 862
    ///
862 863
    ///\pre Either \ref run(Node) "run()" or \ref init()
863 864
    ///must be called before using this function.
864 865
    const DistMap &distMap() const { return *_dist;}
865 866

	
866 867
    ///\brief Returns a const reference to the node map that stores the
867 868
    ///predecessor arcs.
868 869
    ///
869 870
    ///Returns a const reference to the node map that stores the predecessor
870 871
    ///arcs, which form the shortest path tree.
871 872
    ///
872 873
    ///\pre Either \ref run(Node) "run()" or \ref init()
873 874
    ///must be called before using this function.
874 875
    const PredMap &predMap() const { return *_pred;}
875 876

	
876 877
    ///Checks if a node is reached from the root(s).
877 878

	
878 879
    ///Returns \c true if \c v is reached from the root(s).
879 880
    ///
880 881
    ///\pre Either \ref run(Node) "run()" or \ref init()
881 882
    ///must be called before using this function.
882 883
    bool reached(Node v) const { return (*_heap_cross_ref)[v] !=
883 884
                                        Heap::PRE_HEAP; }
884 885

	
885 886
    ///Checks if a node is processed.
886 887

	
887 888
    ///Returns \c true if \c v is processed, i.e. the shortest
888 889
    ///path to \c v has already found.
889 890
    ///
890 891
    ///\pre Either \ref run(Node) "run()" or \ref init()
891 892
    ///must be called before using this function.
892 893
    bool processed(Node v) const { return (*_heap_cross_ref)[v] ==
893 894
                                          Heap::POST_HEAP; }
894 895

	
895 896
    ///The current distance of a node from the root(s).
896 897

	
897 898
    ///Returns the current distance of a node from the root(s).
898 899
    ///It may be decreased in the following processes.
899 900
    ///
900 901
    ///\pre Either \ref run(Node) "run()" or \ref init()
901 902
    ///must be called before using this function and
902 903
    ///node \c v must be reached but not necessarily processed.
903 904
    Value currentDist(Node v) const {
904 905
      return processed(v) ? (*_dist)[v] : (*_heap)[v];
905 906
    }
906 907

	
907 908
    ///@}
908 909
  };
909 910

	
910 911

	
911 912
  ///Default traits class of dijkstra() function.
912 913

	
913 914
  ///Default traits class of dijkstra() function.
914 915
  ///\tparam GR The type of the digraph.
915 916
  ///\tparam LM The type of the length map.
916 917
  template<class GR, class LM>
917 918
  struct DijkstraWizardDefaultTraits
918 919
  {
919 920
    ///The type of the digraph the algorithm runs on.
920 921
    typedef GR Digraph;
921 922
    ///The type of the map that stores the arc lengths.
922 923

	
923 924
    ///The type of the map that stores the arc lengths.
924 925
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
925 926
    typedef LM LengthMap;
926 927
    ///The type of the length of the arcs.
927 928
    typedef typename LM::Value Value;
928 929

	
929 930
    /// Operation traits for Dijkstra algorithm.
930 931

	
931 932
    /// This class defines the operations that are used in the algorithm.
932 933
    /// \see DijkstraDefaultOperationTraits
933 934
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
934 935

	
935 936
    /// The cross reference type used by the heap.
936 937

	
937 938
    /// The cross reference type used by the heap.
938 939
    /// Usually it is \c Digraph::NodeMap<int>.
939 940
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
940 941
    ///Instantiates a \ref HeapCrossRef.
941 942

	
942 943
    ///This function instantiates a \ref HeapCrossRef.
943 944
    /// \param g is the digraph, to which we would like to define the
944 945
    /// HeapCrossRef.
945 946
    static HeapCrossRef *createHeapCrossRef(const Digraph &g)
946 947
    {
947 948
      return new HeapCrossRef(g);
948 949
    }
949 950

	
950 951
    ///The heap type used by the Dijkstra algorithm.
951 952

	
952 953
    ///The heap type used by the Dijkstra algorithm.
953 954
    ///
954 955
    ///\sa BinHeap
955 956
    ///\sa Dijkstra
956 957
    typedef BinHeap<Value, typename Digraph::template NodeMap<int>,
957 958
                    std::less<Value> > Heap;
958 959

	
959 960
    ///Instantiates a \ref Heap.
960 961

	
961 962
    ///This function instantiates a \ref Heap.
962 963
    /// \param r is the HeapCrossRef which is used.
963 964
    static Heap *createHeap(HeapCrossRef& r)
964 965
    {
965 966
      return new Heap(r);
966 967
    }
967 968

	
968 969
    ///\brief The type of the map that stores the predecessor
969 970
    ///arcs of the shortest paths.
970 971
    ///
971 972
    ///The type of the map that stores the predecessor
972 973
    ///arcs of the shortest paths.
973 974
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
974 975
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
975 976
    ///Instantiates a PredMap.
976 977

	
977 978
    ///This function instantiates a PredMap.
978 979
    ///\param g is the digraph, to which we would like to define the
979 980
    ///PredMap.
980 981
    static PredMap *createPredMap(const Digraph &g)
981 982
    {
982 983
      return new PredMap(g);
983 984
    }
984 985

	
985 986
    ///The type of the map that indicates which nodes are processed.
986 987

	
987 988
    ///The type of the map that indicates which nodes are processed.
988 989
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
989 990
    ///By default it is a NullMap.
990 991
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
991 992
    ///Instantiates a ProcessedMap.
992 993

	
993 994
    ///This function instantiates a ProcessedMap.
994 995
    ///\param g is the digraph, to which
995 996
    ///we would like to define the ProcessedMap.
996 997
#ifdef DOXYGEN
997 998
    static ProcessedMap *createProcessedMap(const Digraph &g)
998 999
#else
999 1000
    static ProcessedMap *createProcessedMap(const Digraph &)
1000 1001
#endif
1001 1002
    {
1002 1003
      return new ProcessedMap();
1003 1004
    }
1004 1005

	
1005 1006
    ///The type of the map that stores the distances of the nodes.
1006 1007

	
1007 1008
    ///The type of the map that stores the distances of the nodes.
1008 1009
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
1009 1010
    typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
1010 1011
    ///Instantiates a DistMap.
1011 1012

	
1012 1013
    ///This function instantiates a DistMap.
1013 1014
    ///\param g is the digraph, to which we would like to define
1014 1015
    ///the DistMap
1015 1016
    static DistMap *createDistMap(const Digraph &g)
1016 1017
    {
1017 1018
      return new DistMap(g);
1018 1019
    }
1019 1020

	
1020 1021
    ///The type of the shortest paths.
1021 1022

	
1022 1023
    ///The type of the shortest paths.
1023 1024
    ///It must meet the \ref concepts::Path "Path" concept.
1024 1025
    typedef lemon::Path<Digraph> Path;
1025 1026
  };
1026 1027

	
1027 1028
  /// Default traits class used by DijkstraWizard
1028 1029

	
1029 1030
  /// To make it easier to use Dijkstra algorithm
1030 1031
  /// we have created a wizard class.
1031 1032
  /// This \ref DijkstraWizard class needs default traits,
1032 1033
  /// as well as the \ref Dijkstra class.
1033 1034
  /// The \ref DijkstraWizardBase is a class to be the default traits of the
1034 1035
  /// \ref DijkstraWizard class.
1035 1036
  template<class GR,class LM>
1036 1037
  class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
1037 1038
  {
1038 1039
    typedef DijkstraWizardDefaultTraits<GR,LM> Base;
1039 1040
  protected:
1040 1041
    //The type of the nodes in the digraph.
1041 1042
    typedef typename Base::Digraph::Node Node;
1042 1043

	
1043 1044
    //Pointer to the digraph the algorithm runs on.
1044 1045
    void *_g;
1045 1046
    //Pointer to the length map.
1046 1047
    void *_length;
1047 1048
    //Pointer to the map of processed nodes.
1048 1049
    void *_processed;
1049 1050
    //Pointer to the map of predecessors arcs.
1050 1051
    void *_pred;
1051 1052
    //Pointer to the map of distances.
1052 1053
    void *_dist;
1053 1054
    //Pointer to the shortest path to the target node.
1054 1055
    void *_path;
1055 1056
    //Pointer to the distance of the target node.
1056 1057
    void *_di;
1057 1058

	
1058 1059
  public:
1059 1060
    /// Constructor.
1060 1061

	
1061 1062
    /// This constructor does not require parameters, therefore it initiates
1062 1063
    /// all of the attributes to \c 0.
1063 1064
    DijkstraWizardBase() : _g(0), _length(0), _processed(0), _pred(0),
1064 1065
                           _dist(0), _path(0), _di(0) {}
1065 1066

	
1066 1067
    /// Constructor.
1067 1068

	
1068 1069
    /// This constructor requires two parameters,
1069 1070
    /// others are initiated to \c 0.
1070 1071
    /// \param g The digraph the algorithm runs on.
1071 1072
    /// \param l The length map.
1072 1073
    DijkstraWizardBase(const GR &g,const LM &l) :
1073 1074
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1074 1075
      _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1075 1076
      _processed(0), _pred(0), _dist(0), _path(0), _di(0) {}
1076 1077

	
1077 1078
  };
1078 1079

	
1079 1080
  /// Auxiliary class for the function-type interface of Dijkstra algorithm.
1080 1081

	
1081 1082
  /// This auxiliary class is created to implement the
1082 1083
  /// \ref dijkstra() "function-type interface" of \ref Dijkstra algorithm.
1083 1084
  /// It does not have own \ref run(Node) "run()" method, it uses the
1084 1085
  /// functions and features of the plain \ref Dijkstra.
1085 1086
  ///
1086 1087
  /// This class should only be used through the \ref dijkstra() function,
1087 1088
  /// which makes it easier to use the algorithm.
1088 1089
  template<class TR>
1089 1090
  class DijkstraWizard : public TR
1090 1091
  {
1091 1092
    typedef TR Base;
1092 1093

	
1093 1094
    ///The type of the digraph the algorithm runs on.
1094 1095
    typedef typename TR::Digraph Digraph;
1095 1096

	
1096 1097
    typedef typename Digraph::Node Node;
1097 1098
    typedef typename Digraph::NodeIt NodeIt;
1098 1099
    typedef typename Digraph::Arc Arc;
1099 1100
    typedef typename Digraph::OutArcIt OutArcIt;
1100 1101

	
1101 1102
    ///The type of the map that stores the arc lengths.
1102 1103
    typedef typename TR::LengthMap LengthMap;
1103 1104
    ///The type of the length of the arcs.
1104 1105
    typedef typename LengthMap::Value Value;
1105 1106
    ///\brief The type of the map that stores the predecessor
1106 1107
    ///arcs of the shortest paths.
1107 1108
    typedef typename TR::PredMap PredMap;
1108 1109
    ///The type of the map that stores the distances of the nodes.
1109 1110
    typedef typename TR::DistMap DistMap;
1110 1111
    ///The type of the map that indicates which nodes are processed.
1111 1112
    typedef typename TR::ProcessedMap ProcessedMap;
1112 1113
    ///The type of the shortest paths
1113 1114
    typedef typename TR::Path Path;
1114 1115
    ///The heap type used by the dijkstra algorithm.
1115 1116
    typedef typename TR::Heap Heap;
1116 1117

	
1117 1118
  public:
1118 1119

	
1119 1120
    /// Constructor.
1120 1121
    DijkstraWizard() : TR() {}
1121 1122

	
1122 1123
    /// Constructor that requires parameters.
1123 1124

	
1124 1125
    /// Constructor that requires parameters.
1125 1126
    /// These parameters will be the default values for the traits class.
1126 1127
    /// \param g The digraph the algorithm runs on.
1127 1128
    /// \param l The length map.
1128 1129
    DijkstraWizard(const Digraph &g, const LengthMap &l) :
1129 1130
      TR(g,l) {}
1130 1131

	
1131 1132
    ///Copy constructor
1132 1133
    DijkstraWizard(const TR &b) : TR(b) {}
1133 1134

	
1134 1135
    ~DijkstraWizard() {}
1135 1136

	
1136 1137
    ///Runs Dijkstra algorithm from the given source node.
1137 1138

	
1138 1139
    ///This method runs %Dijkstra algorithm from the given source node
1139 1140
    ///in order to compute the shortest path to each node.
1140 1141
    void run(Node s)
1141 1142
    {
1142 1143
      Dijkstra<Digraph,LengthMap,TR>
1143 1144
        dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1144 1145
             *reinterpret_cast<const LengthMap*>(Base::_length));
1145 1146
      if (Base::_pred)
1146 1147
        dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1147 1148
      if (Base::_dist)
1148 1149
        dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1149 1150
      if (Base::_processed)
1150 1151
        dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1151 1152
      dijk.run(s);
1152 1153
    }
1153 1154

	
1154 1155
    ///Finds the shortest path between \c s and \c t.
1155 1156

	
1156 1157
    ///This method runs the %Dijkstra algorithm from node \c s
1157 1158
    ///in order to compute the shortest path to node \c t
1158 1159
    ///(it stops searching when \c t is processed).
1159 1160
    ///
1160 1161
    ///\return \c true if \c t is reachable form \c s.
1161 1162
    bool run(Node s, Node t)
1162 1163
    {
1163 1164
      Dijkstra<Digraph,LengthMap,TR>
1164 1165
        dijk(*reinterpret_cast<const Digraph*>(Base::_g),
1165 1166
             *reinterpret_cast<const LengthMap*>(Base::_length));
1166 1167
      if (Base::_pred)
1167 1168
        dijk.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1168 1169
      if (Base::_dist)
1169 1170
        dijk.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1170 1171
      if (Base::_processed)
1171 1172
        dijk.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
1172 1173
      dijk.run(s,t);
1173 1174
      if (Base::_path)
1174 1175
        *reinterpret_cast<Path*>(Base::_path) = dijk.path(t);
1175 1176
      if (Base::_di)
1176 1177
        *reinterpret_cast<Value*>(Base::_di) = dijk.dist(t);
1177 1178
      return dijk.reached(t);
1178 1179
    }
1179 1180

	
1180 1181
    template<class T>
1181 1182
    struct SetPredMapBase : public Base {
1182 1183
      typedef T PredMap;
1183 1184
      static PredMap *createPredMap(const Digraph &) { return 0; };
1184 1185
      SetPredMapBase(const TR &b) : TR(b) {}
1185 1186
    };
1186 1187
    ///\brief \ref named-func-param "Named parameter"
1187 1188
    ///for setting PredMap object.
1188 1189
    ///
1189 1190
    ///\ref named-func-param "Named parameter"
1190 1191
    ///for setting PredMap object.
1191 1192
    template<class T>
1192 1193
    DijkstraWizard<SetPredMapBase<T> > predMap(const T &t)
1193 1194
    {
1194 1195
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1195 1196
      return DijkstraWizard<SetPredMapBase<T> >(*this);
1196 1197
    }
1197 1198

	
1198 1199
    template<class T>
1199 1200
    struct SetDistMapBase : public Base {
1200 1201
      typedef T DistMap;
1201 1202
      static DistMap *createDistMap(const Digraph &) { return 0; };
1202 1203
      SetDistMapBase(const TR &b) : TR(b) {}
1203 1204
    };
1204 1205
    ///\brief \ref named-func-param "Named parameter"
1205 1206
    ///for setting DistMap object.
1206 1207
    ///
1207 1208
    ///\ref named-func-param "Named parameter"
1208 1209
    ///for setting DistMap object.
1209 1210
    template<class T>
1210 1211
    DijkstraWizard<SetDistMapBase<T> > distMap(const T &t)
1211 1212
    {
1212 1213
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1213 1214
      return DijkstraWizard<SetDistMapBase<T> >(*this);
1214 1215
    }
1215 1216

	
1216 1217
    template<class T>
1217 1218
    struct SetProcessedMapBase : public Base {
1218 1219
      typedef T ProcessedMap;
1219 1220
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1220 1221
      SetProcessedMapBase(const TR &b) : TR(b) {}
1221 1222
    };
1222 1223
    ///\brief \ref named-func-param "Named parameter"
1223 1224
    ///for setting ProcessedMap object.
1224 1225
    ///
1225 1226
    /// \ref named-func-param "Named parameter"
1226 1227
    ///for setting ProcessedMap object.
1227 1228
    template<class T>
1228 1229
    DijkstraWizard<SetProcessedMapBase<T> > processedMap(const T &t)
1229 1230
    {
1230 1231
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1231 1232
      return DijkstraWizard<SetProcessedMapBase<T> >(*this);
1232 1233
    }
1233 1234

	
1234 1235
    template<class T>
1235 1236
    struct SetPathBase : public Base {
1236 1237
      typedef T Path;
1237 1238
      SetPathBase(const TR &b) : TR(b) {}
1238 1239
    };
1239 1240
    ///\brief \ref named-func-param "Named parameter"
1240 1241
    ///for getting the shortest path to the target node.
1241 1242
    ///
1242 1243
    ///\ref named-func-param "Named parameter"
1243 1244
    ///for getting the shortest path to the target node.
1244 1245
    template<class T>
1245 1246
    DijkstraWizard<SetPathBase<T> > path(const T &t)
1246 1247
    {
1247 1248
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1248 1249
      return DijkstraWizard<SetPathBase<T> >(*this);
1249 1250
    }
1250 1251

	
1251 1252
    ///\brief \ref named-func-param "Named parameter"
1252 1253
    ///for getting the distance of the target node.
1253 1254
    ///
1254 1255
    ///\ref named-func-param "Named parameter"
1255 1256
    ///for getting the distance of the target node.
1256 1257
    DijkstraWizard dist(const Value &d)
1257 1258
    {
1258 1259
      Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1259 1260
      return *this;
1260 1261
    }
1261 1262

	
1262 1263
  };
1263 1264

	
1264 1265
  ///Function-type interface for Dijkstra algorithm.
1265 1266

	
1266 1267
  /// \ingroup shortest_path
1267 1268
  ///Function-type interface for Dijkstra algorithm.
1268 1269
  ///
1269 1270
  ///This function also has several \ref named-func-param "named parameters",
1270 1271
  ///they are declared as the members of class \ref DijkstraWizard.
1271 1272
  ///The following examples show how to use these parameters.
1272 1273
  ///\code
1273 1274
  ///  // Compute shortest path from node s to each node
1274 1275
  ///  dijkstra(g,length).predMap(preds).distMap(dists).run(s);
1275 1276
  ///
1276 1277
  ///  // Compute shortest path from s to t
1277 1278
  ///  bool reached = dijkstra(g,length).path(p).dist(d).run(s,t);
1278 1279
  ///\endcode
1279 1280
  ///\warning Don't forget to put the \ref DijkstraWizard::run(Node) "run()"
1280 1281
  ///to the end of the parameter list.
1281 1282
  ///\sa DijkstraWizard
1282 1283
  ///\sa Dijkstra
1283 1284
  template<class GR, class LM>
1284 1285
  DijkstraWizard<DijkstraWizardBase<GR,LM> >
1285 1286
  dijkstra(const GR &digraph, const LM &length)
1286 1287
  {
1287 1288
    return DijkstraWizard<DijkstraWizardBase<GR,LM> >(digraph,length);
1288 1289
  }
1289 1290

	
1290 1291
} //END OF NAMESPACE LEMON
1291 1292

	
1292 1293
#endif
Ignore white space 32768 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_PREFLOW_H
20 20
#define LEMON_PREFLOW_H
21 21

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

	
25 25
/// \file
26 26
/// \ingroup max_flow
27 27
/// \brief Implementation of the preflow algorithm.
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  /// \brief Default traits class of Preflow class.
32 32
  ///
33 33
  /// Default traits class of Preflow class.
34
  /// \tparam _Digraph Digraph type.
35
  /// \tparam _CapacityMap Capacity map type.
36
  template <typename _Digraph, typename _CapacityMap>
34
  /// \tparam GR Digraph type.
35
  /// \tparam CM Capacity map type.
36
  template <typename GR, typename CM>
37 37
  struct PreflowDefaultTraits {
38 38

	
39 39
    /// \brief The type of the digraph the algorithm runs on.
40
    typedef _Digraph Digraph;
40
    typedef GR Digraph;
41 41

	
42 42
    /// \brief The type of the map that stores the arc capacities.
43 43
    ///
44 44
    /// The type of the map that stores the arc capacities.
45 45
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
46
    typedef _CapacityMap CapacityMap;
46
    typedef CM CapacityMap;
47 47

	
48 48
    /// \brief The type of the flow values.
49 49
    typedef typename CapacityMap::Value Value;
50 50

	
51 51
    /// \brief The type of the map that stores the flow values.
52 52
    ///
53 53
    /// The type of the map that stores the flow values.
54 54
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
55 55
    typedef typename Digraph::template ArcMap<Value> FlowMap;
56 56

	
57 57
    /// \brief Instantiates a FlowMap.
58 58
    ///
59 59
    /// This function instantiates a \ref FlowMap.
60 60
    /// \param digraph The digraph, to which we would like to define
61 61
    /// the flow map.
62 62
    static FlowMap* createFlowMap(const Digraph& digraph) {
63 63
      return new FlowMap(digraph);
64 64
    }
65 65

	
66 66
    /// \brief The elevator type used by Preflow algorithm.
67 67
    ///
68 68
    /// The elevator type used by Preflow algorithm.
69 69
    ///
70 70
    /// \sa Elevator
71 71
    /// \sa LinkedElevator
72 72
    typedef LinkedElevator<Digraph, typename Digraph::Node> Elevator;
73 73

	
74 74
    /// \brief Instantiates an Elevator.
75 75
    ///
76 76
    /// This function instantiates an \ref Elevator.
77 77
    /// \param digraph The digraph, to which we would like to define
78 78
    /// the elevator.
79 79
    /// \param max_level The maximum level of the elevator.
80 80
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
81 81
      return new Elevator(digraph, max_level);
82 82
    }
83 83

	
84 84
    /// \brief The tolerance used by the algorithm
85 85
    ///
86 86
    /// The tolerance used by the algorithm to handle inexact computation.
87 87
    typedef lemon::Tolerance<Value> Tolerance;
88 88

	
89 89
  };
90 90

	
91 91

	
92 92
  /// \ingroup max_flow
93 93
  ///
94 94
  /// \brief %Preflow algorithm class.
95 95
  ///
96 96
  /// This class provides an implementation of Goldberg-Tarjan's \e preflow
97 97
  /// \e push-relabel algorithm producing a flow of maximum value in a
98 98
  /// digraph. The preflow algorithms are the fastest known maximum
99 99
  /// flow algorithms. The current implementation use a mixture of the
100 100
  /// \e "highest label" and the \e "bound decrease" heuristics.
101 101
  /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
102 102
  ///
103 103
  /// The algorithm consists of two phases. After the first phase
104 104
  /// the maximum flow value and the minimum cut is obtained. The
105 105
  /// second phase constructs a feasible maximum flow on each arc.
106 106
  ///
107
  /// \tparam _Digraph The type of the digraph the algorithm runs on.
108
  /// \tparam _CapacityMap The type of the capacity map. The default map
109
  /// type is \ref concepts::Digraph::ArcMap "_Digraph::ArcMap<int>".
107
  /// \tparam GR The type of the digraph the algorithm runs on.
108
  /// \tparam CM The type of the capacity map. The default map
109
  /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
110 110
#ifdef DOXYGEN
111
  template <typename _Digraph, typename _CapacityMap, typename _Traits>
111
  template <typename GR, typename CM, typename TR>
112 112
#else
113
  template <typename _Digraph,
114
            typename _CapacityMap = typename _Digraph::template ArcMap<int>,
115
            typename _Traits = PreflowDefaultTraits<_Digraph, _CapacityMap> >
113
  template <typename GR,
114
            typename CM = typename GR::template ArcMap<int>,
115
            typename TR = PreflowDefaultTraits<GR, CM> >
116 116
#endif
117 117
  class Preflow {
118 118
  public:
119 119

	
120 120
    ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
121
    typedef _Traits Traits;
121
    typedef TR Traits;
122 122
    ///The type of the digraph the algorithm runs on.
123 123
    typedef typename Traits::Digraph Digraph;
124 124
    ///The type of the capacity map.
125 125
    typedef typename Traits::CapacityMap CapacityMap;
126 126
    ///The type of the flow values.
127 127
    typedef typename Traits::Value Value;
128 128

	
129 129
    ///The type of the flow map.
130 130
    typedef typename Traits::FlowMap FlowMap;
131 131
    ///The type of the elevator.
132 132
    typedef typename Traits::Elevator Elevator;
133 133
    ///The type of the tolerance.
134 134
    typedef typename Traits::Tolerance Tolerance;
135 135

	
136 136
  private:
137 137

	
138 138
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
139 139

	
140 140
    const Digraph& _graph;
141 141
    const CapacityMap* _capacity;
142 142

	
143 143
    int _node_num;
144 144

	
145 145
    Node _source, _target;
146 146

	
147 147
    FlowMap* _flow;
148 148
    bool _local_flow;
149 149

	
150 150
    Elevator* _level;
151 151
    bool _local_level;
152 152

	
153 153
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
154 154
    ExcessMap* _excess;
155 155

	
156 156
    Tolerance _tolerance;
157 157

	
158 158
    bool _phase;
159 159

	
160 160

	
161 161
    void createStructures() {
162 162
      _node_num = countNodes(_graph);
163 163

	
164 164
      if (!_flow) {
165 165
        _flow = Traits::createFlowMap(_graph);
166 166
        _local_flow = true;
167 167
      }
168 168
      if (!_level) {
169 169
        _level = Traits::createElevator(_graph, _node_num);
170 170
        _local_level = true;
171 171
      }
172 172
      if (!_excess) {
173 173
        _excess = new ExcessMap(_graph);
174 174
      }
175 175
    }
176 176

	
177 177
    void destroyStructures() {
178 178
      if (_local_flow) {
179 179
        delete _flow;
180 180
      }
181 181
      if (_local_level) {
182 182
        delete _level;
183 183
      }
184 184
      if (_excess) {
185 185
        delete _excess;
186 186
      }
187 187
    }
188 188

	
189 189
  public:
190 190

	
191 191
    typedef Preflow Create;
192 192

	
193 193
    ///\name Named Template Parameters
194 194

	
195 195
    ///@{
196 196

	
197 197
    template <typename _FlowMap>
198 198
    struct SetFlowMapTraits : public Traits {
199 199
      typedef _FlowMap FlowMap;
200 200
      static FlowMap *createFlowMap(const Digraph&) {
201 201
        LEMON_ASSERT(false, "FlowMap is not initialized");
202 202
        return 0; // ignore warnings
203 203
      }
204 204
    };
205 205

	
206 206
    /// \brief \ref named-templ-param "Named parameter" for setting
207 207
    /// FlowMap type
208 208
    ///
209 209
    /// \ref named-templ-param "Named parameter" for setting FlowMap
210 210
    /// type.
211 211
    template <typename _FlowMap>
212 212
    struct SetFlowMap
213 213
      : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<_FlowMap> > {
214 214
      typedef Preflow<Digraph, CapacityMap,
215 215
                      SetFlowMapTraits<_FlowMap> > Create;
216 216
    };
217 217

	
218 218
    template <typename _Elevator>
219 219
    struct SetElevatorTraits : public Traits {
220 220
      typedef _Elevator Elevator;
221 221
      static Elevator *createElevator(const Digraph&, int) {
222 222
        LEMON_ASSERT(false, "Elevator is not initialized");
223 223
        return 0; // ignore warnings
224 224
      }
225 225
    };
226 226

	
227 227
    /// \brief \ref named-templ-param "Named parameter" for setting
228 228
    /// Elevator type
229 229
    ///
230 230
    /// \ref named-templ-param "Named parameter" for setting Elevator
231 231
    /// type. If this named parameter is used, then an external
232 232
    /// elevator object must be passed to the algorithm using the
233 233
    /// \ref elevator(Elevator&) "elevator()" function before calling
234 234
    /// \ref run() or \ref init().
235 235
    /// \sa SetStandardElevator
236 236
    template <typename _Elevator>
237 237
    struct SetElevator
238 238
      : public Preflow<Digraph, CapacityMap, SetElevatorTraits<_Elevator> > {
239 239
      typedef Preflow<Digraph, CapacityMap,
240 240
                      SetElevatorTraits<_Elevator> > Create;
241 241
    };
242 242

	
243 243
    template <typename _Elevator>
244 244
    struct SetStandardElevatorTraits : public Traits {
245 245
      typedef _Elevator Elevator;
246 246
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
247 247
        return new Elevator(digraph, max_level);
248 248
      }
249 249
    };
250 250

	
251 251
    /// \brief \ref named-templ-param "Named parameter" for setting
252 252
    /// Elevator type with automatic allocation
253 253
    ///
254 254
    /// \ref named-templ-param "Named parameter" for setting Elevator
255 255
    /// type with automatic allocation.
256 256
    /// The Elevator should have standard constructor interface to be
257 257
    /// able to automatically created by the algorithm (i.e. the
258 258
    /// digraph and the maximum level should be passed to it).
259 259
    /// However an external elevator object could also be passed to the
260 260
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
261 261
    /// before calling \ref run() or \ref init().
262 262
    /// \sa SetElevator
263 263
    template <typename _Elevator>
264 264
    struct SetStandardElevator
265 265
      : public Preflow<Digraph, CapacityMap,
266 266
                       SetStandardElevatorTraits<_Elevator> > {
267 267
      typedef Preflow<Digraph, CapacityMap,
268 268
                      SetStandardElevatorTraits<_Elevator> > Create;
269 269
    };
270 270

	
271 271
    /// @}
272 272

	
273 273
  protected:
274 274

	
275 275
    Preflow() {}
276 276

	
277 277
  public:
278 278

	
279 279

	
280 280
    /// \brief The constructor of the class.
281 281
    ///
282 282
    /// The constructor of the class.
283 283
    /// \param digraph The digraph the algorithm runs on.
284 284
    /// \param capacity The capacity of the arcs.
285 285
    /// \param source The source node.
286 286
    /// \param target The target node.
287 287
    Preflow(const Digraph& digraph, const CapacityMap& capacity,
288 288
            Node source, Node target)
289 289
      : _graph(digraph), _capacity(&capacity),
290 290
        _node_num(0), _source(source), _target(target),
291 291
        _flow(0), _local_flow(false),
292 292
        _level(0), _local_level(false),
293 293
        _excess(0), _tolerance(), _phase() {}
294 294

	
295 295
    /// \brief Destructor.
296 296
    ///
297 297
    /// Destructor.
298 298
    ~Preflow() {
299 299
      destroyStructures();
300 300
    }
301 301

	
302 302
    /// \brief Sets the capacity map.
303 303
    ///
304 304
    /// Sets the capacity map.
305 305
    /// \return <tt>(*this)</tt>
306 306
    Preflow& capacityMap(const CapacityMap& map) {
307 307
      _capacity = &map;
308 308
      return *this;
309 309
    }
310 310

	
311 311
    /// \brief Sets the flow map.
312 312
    ///
313 313
    /// Sets the flow map.
314 314
    /// If you don't use this function before calling \ref run() or
315 315
    /// \ref init(), an instance will be allocated automatically.
316 316
    /// The destructor deallocates this automatically allocated map,
317 317
    /// of course.
318 318
    /// \return <tt>(*this)</tt>
319 319
    Preflow& flowMap(FlowMap& map) {
320 320
      if (_local_flow) {
321 321
        delete _flow;
322 322
        _local_flow = false;
323 323
      }
324 324
      _flow = &map;
325 325
      return *this;
326 326
    }
327 327

	
328 328
    /// \brief Sets the source node.
329 329
    ///
330 330
    /// Sets the source node.
331 331
    /// \return <tt>(*this)</tt>
332 332
    Preflow& source(const Node& node) {
333 333
      _source = node;
334 334
      return *this;
335 335
    }
336 336

	
337 337
    /// \brief Sets the target node.
338 338
    ///
339 339
    /// Sets the target node.
340 340
    /// \return <tt>(*this)</tt>
341 341
    Preflow& target(const Node& node) {
342 342
      _target = node;
343 343
      return *this;
344 344
    }
345 345

	
346 346
    /// \brief Sets the elevator used by algorithm.
347 347
    ///
348 348
    /// Sets the elevator used by algorithm.
349 349
    /// If you don't use this function before calling \ref run() or
350 350
    /// \ref init(), an instance will be allocated automatically.
351 351
    /// The destructor deallocates this automatically allocated elevator,
352 352
    /// of course.
353 353
    /// \return <tt>(*this)</tt>
354 354
    Preflow& elevator(Elevator& elevator) {
355 355
      if (_local_level) {
356 356
        delete _level;
357 357
        _local_level = false;
358 358
      }
359 359
      _level = &elevator;
360 360
      return *this;
361 361
    }
362 362

	
363 363
    /// \brief Returns a const reference to the elevator.
364 364
    ///
365 365
    /// Returns a const reference to the elevator.
366 366
    ///
367 367
    /// \pre Either \ref run() or \ref init() must be called before
368 368
    /// using this function.
369 369
    const Elevator& elevator() const {
370 370
      return *_level;
371 371
    }
372 372

	
373 373
    /// \brief Sets the tolerance used by algorithm.
374 374
    ///
375 375
    /// Sets the tolerance used by algorithm.
376 376
    Preflow& tolerance(const Tolerance& tolerance) const {
377 377
      _tolerance = tolerance;
378 378
      return *this;
379 379
    }
380 380

	
381 381
    /// \brief Returns a const reference to the tolerance.
382 382
    ///
383 383
    /// Returns a const reference to the tolerance.
384 384
    const Tolerance& tolerance() const {
385 385
      return tolerance;
386 386
    }
387 387

	
388 388
    /// \name Execution Control
389 389
    /// The simplest way to execute the preflow algorithm is to use
390 390
    /// \ref run() or \ref runMinCut().\n
391 391
    /// If you need more control on the initial solution or the execution,
392 392
    /// first you have to call one of the \ref init() functions, then
393 393
    /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
394 394

	
395 395
    ///@{
396 396

	
397 397
    /// \brief Initializes the internal data structures.
398 398
    ///
399 399
    /// Initializes the internal data structures and sets the initial
400 400
    /// flow to zero on each arc.
401 401
    void init() {
402 402
      createStructures();
403 403

	
404 404
      _phase = true;
405 405
      for (NodeIt n(_graph); n != INVALID; ++n) {
406 406
        _excess->set(n, 0);
407 407
      }
408 408

	
409 409
      for (ArcIt e(_graph); e != INVALID; ++e) {
410 410
        _flow->set(e, 0);
411 411
      }
412 412

	
413 413
      typename Digraph::template NodeMap<bool> reached(_graph, false);
414 414

	
415 415
      _level->initStart();
416 416
      _level->initAddItem(_target);
417 417

	
418 418
      std::vector<Node> queue;
419 419
      reached.set(_source, true);
420 420

	
421 421
      queue.push_back(_target);
422 422
      reached.set(_target, true);
423 423
      while (!queue.empty()) {
424 424
        _level->initNewLevel();
425 425
        std::vector<Node> nqueue;
426 426
        for (int i = 0; i < int(queue.size()); ++i) {
427 427
          Node n = queue[i];
428 428
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
429 429
            Node u = _graph.source(e);
430 430
            if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
431 431
              reached.set(u, true);
432 432
              _level->initAddItem(u);
433 433
              nqueue.push_back(u);
434 434
            }
435 435
          }
436 436
        }
437 437
        queue.swap(nqueue);
438 438
      }
439 439
      _level->initFinish();
440 440

	
441 441
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
442 442
        if (_tolerance.positive((*_capacity)[e])) {
443 443
          Node u = _graph.target(e);
444 444
          if ((*_level)[u] == _level->maxLevel()) continue;
445 445
          _flow->set(e, (*_capacity)[e]);
446 446
          _excess->set(u, (*_excess)[u] + (*_capacity)[e]);
447 447
          if (u != _target && !_level->active(u)) {
448 448
            _level->activate(u);
449 449
          }
450 450
        }
451 451
      }
452 452
    }
453 453

	
454 454
    /// \brief Initializes the internal data structures using the
455 455
    /// given flow map.
456 456
    ///
457 457
    /// Initializes the internal data structures and sets the initial
458 458
    /// flow to the given \c flowMap. The \c flowMap should contain a
459 459
    /// flow or at least a preflow, i.e. at each node excluding the
460 460
    /// source node the incoming flow should greater or equal to the
461 461
    /// outgoing flow.
462 462
    /// \return \c false if the given \c flowMap is not a preflow.
463 463
    template <typename FlowMap>
464 464
    bool init(const FlowMap& flowMap) {
465 465
      createStructures();
466 466

	
467 467
      for (ArcIt e(_graph); e != INVALID; ++e) {
468 468
        _flow->set(e, flowMap[e]);
469 469
      }
470 470

	
471 471
      for (NodeIt n(_graph); n != INVALID; ++n) {
472 472
        Value excess = 0;
473 473
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
474 474
          excess += (*_flow)[e];
475 475
        }
476 476
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
477 477
          excess -= (*_flow)[e];
478 478
        }
479 479
        if (excess < 0 && n != _source) return false;
480 480
        _excess->set(n, excess);
481 481
      }
482 482

	
483 483
      typename Digraph::template NodeMap<bool> reached(_graph, false);
484 484

	
485 485
      _level->initStart();
486 486
      _level->initAddItem(_target);
487 487

	
488 488
      std::vector<Node> queue;
489 489
      reached.set(_source, true);
490 490

	
491 491
      queue.push_back(_target);
492 492
      reached.set(_target, true);
493 493
      while (!queue.empty()) {
494 494
        _level->initNewLevel();
495 495
        std::vector<Node> nqueue;
496 496
        for (int i = 0; i < int(queue.size()); ++i) {
497 497
          Node n = queue[i];
498 498
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
499 499
            Node u = _graph.source(e);
500 500
            if (!reached[u] &&
501 501
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
502 502
              reached.set(u, true);
503 503
              _level->initAddItem(u);
504 504
              nqueue.push_back(u);
505 505
            }
506 506
          }
507 507
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
508 508
            Node v = _graph.target(e);
509 509
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
510 510
              reached.set(v, true);
511 511
              _level->initAddItem(v);
512 512
              nqueue.push_back(v);
513 513
            }
514 514
          }
515 515
        }
516 516
        queue.swap(nqueue);
517 517
      }
518 518
      _level->initFinish();
519 519

	
520 520
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
521 521
        Value rem = (*_capacity)[e] - (*_flow)[e];
522 522
        if (_tolerance.positive(rem)) {
523 523
          Node u = _graph.target(e);
524 524
          if ((*_level)[u] == _level->maxLevel()) continue;
525 525
          _flow->set(e, (*_capacity)[e]);
526 526
          _excess->set(u, (*_excess)[u] + rem);
527 527
          if (u != _target && !_level->active(u)) {
528 528
            _level->activate(u);
529 529
          }
530 530
        }
531 531
      }
532 532
      for (InArcIt e(_graph, _source); e != INVALID; ++e) {
533 533
        Value rem = (*_flow)[e];
534 534
        if (_tolerance.positive(rem)) {
535 535
          Node v = _graph.source(e);
536 536
          if ((*_level)[v] == _level->maxLevel()) continue;
537 537
          _flow->set(e, 0);
538 538
          _excess->set(v, (*_excess)[v] + rem);
539 539
          if (v != _target && !_level->active(v)) {
540 540
            _level->activate(v);
541 541
          }
542 542
        }
543 543
      }
544 544
      return true;
545 545
    }
546 546

	
547 547
    /// \brief Starts the first phase of the preflow algorithm.
548 548
    ///
549 549
    /// The preflow algorithm consists of two phases, this method runs
550 550
    /// the first phase. After the first phase the maximum flow value
551 551
    /// and a minimum value cut can already be computed, although a
552 552
    /// maximum flow is not yet obtained. So after calling this method
553 553
    /// \ref flowValue() returns the value of a maximum flow and \ref
554 554
    /// minCut() returns a minimum cut.
555 555
    /// \pre One of the \ref init() functions must be called before
556 556
    /// using this function.
557 557
    void startFirstPhase() {
558 558
      _phase = true;
559 559

	
560 560
      Node n = _level->highestActive();
561 561
      int level = _level->highestActiveLevel();
562 562
      while (n != INVALID) {
563 563
        int num = _node_num;
564 564

	
565 565
        while (num > 0 && n != INVALID) {
566 566
          Value excess = (*_excess)[n];
567 567
          int new_level = _level->maxLevel();
568 568

	
569 569
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
570 570
            Value rem = (*_capacity)[e] - (*_flow)[e];
571 571
            if (!_tolerance.positive(rem)) continue;
572 572
            Node v = _graph.target(e);
573 573
            if ((*_level)[v] < level) {
574 574
              if (!_level->active(v) && v != _target) {
575 575
                _level->activate(v);
576 576
              }
577 577
              if (!_tolerance.less(rem, excess)) {
578 578
                _flow->set(e, (*_flow)[e] + excess);
579 579
                _excess->set(v, (*_excess)[v] + excess);
580 580
                excess = 0;
581 581
                goto no_more_push_1;
582 582
              } else {
583 583
                excess -= rem;
584 584
                _excess->set(v, (*_excess)[v] + rem);
585 585
                _flow->set(e, (*_capacity)[e]);
586 586
              }
587 587
            } else if (new_level > (*_level)[v]) {
588 588
              new_level = (*_level)[v];
589 589
            }
590 590
          }
591 591

	
592 592
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
593 593
            Value rem = (*_flow)[e];
594 594
            if (!_tolerance.positive(rem)) continue;
595 595
            Node v = _graph.source(e);
596 596
            if ((*_level)[v] < level) {
597 597
              if (!_level->active(v) && v != _target) {
598 598
                _level->activate(v);
599 599
              }
600 600
              if (!_tolerance.less(rem, excess)) {
601 601
                _flow->set(e, (*_flow)[e] - excess);
602 602
                _excess->set(v, (*_excess)[v] + excess);
603 603
                excess = 0;
604 604
                goto no_more_push_1;
605 605
              } else {
606 606
                excess -= rem;
607 607
                _excess->set(v, (*_excess)[v] + rem);
608 608
                _flow->set(e, 0);
609 609
              }
610 610
            } else if (new_level > (*_level)[v]) {
611 611
              new_level = (*_level)[v];
612 612
            }
613 613
          }
614 614

	
615 615
        no_more_push_1:
616 616

	
617 617
          _excess->set(n, excess);
618 618

	
619 619
          if (excess != 0) {
620 620
            if (new_level + 1 < _level->maxLevel()) {
621 621
              _level->liftHighestActive(new_level + 1);
622 622
            } else {
623 623
              _level->liftHighestActiveToTop();
624 624
            }
625 625
            if (_level->emptyLevel(level)) {
626 626
              _level->liftToTop(level);
627 627
            }
628 628
          } else {
629 629
            _level->deactivate(n);
630 630
          }
631 631

	
632 632
          n = _level->highestActive();
633 633
          level = _level->highestActiveLevel();
634 634
          --num;
635 635
        }
636 636

	
637 637
        num = _node_num * 20;
638 638
        while (num > 0 && n != INVALID) {
639 639
          Value excess = (*_excess)[n];
640 640
          int new_level = _level->maxLevel();
641 641

	
642 642
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
643 643
            Value rem = (*_capacity)[e] - (*_flow)[e];
644 644
            if (!_tolerance.positive(rem)) continue;
645 645
            Node v = _graph.target(e);
646 646
            if ((*_level)[v] < level) {
647 647
              if (!_level->active(v) && v != _target) {
648 648
                _level->activate(v);
649 649
              }
650 650
              if (!_tolerance.less(rem, excess)) {
651 651
                _flow->set(e, (*_flow)[e] + excess);
652 652
                _excess->set(v, (*_excess)[v] + excess);
653 653
                excess = 0;
654 654
                goto no_more_push_2;
655 655
              } else {
656 656
                excess -= rem;
657 657
                _excess->set(v, (*_excess)[v] + rem);
658 658
                _flow->set(e, (*_capacity)[e]);
659 659
              }
660 660
            } else if (new_level > (*_level)[v]) {
661 661
              new_level = (*_level)[v];
662 662
            }
663 663
          }
664 664

	
665 665
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
666 666
            Value rem = (*_flow)[e];
667 667
            if (!_tolerance.positive(rem)) continue;
668 668
            Node v = _graph.source(e);
669 669
            if ((*_level)[v] < level) {
670 670
              if (!_level->active(v) && v != _target) {
671 671
                _level->activate(v);
672 672
              }
673 673
              if (!_tolerance.less(rem, excess)) {
674 674
                _flow->set(e, (*_flow)[e] - excess);
675 675
                _excess->set(v, (*_excess)[v] + excess);
676 676
                excess = 0;
677 677
                goto no_more_push_2;
678 678
              } else {
679 679
                excess -= rem;
680 680
                _excess->set(v, (*_excess)[v] + rem);
681 681
                _flow->set(e, 0);
682 682
              }
683 683
            } else if (new_level > (*_level)[v]) {
684 684
              new_level = (*_level)[v];
685 685
            }
686 686
          }
687 687

	
688 688
        no_more_push_2:
689 689

	
690 690
          _excess->set(n, excess);
691 691

	
692 692
          if (excess != 0) {
693 693
            if (new_level + 1 < _level->maxLevel()) {
694 694
              _level->liftActiveOn(level, new_level + 1);
695 695
            } else {
696 696
              _level->liftActiveToTop(level);
697 697
            }
698 698
            if (_level->emptyLevel(level)) {
699 699
              _level->liftToTop(level);
700 700
            }
701 701
          } else {
702 702
            _level->deactivate(n);
703 703
          }
704 704

	
705 705
          while (level >= 0 && _level->activeFree(level)) {
706 706
            --level;
707 707
          }
708 708
          if (level == -1) {
709 709
            n = _level->highestActive();
710 710
            level = _level->highestActiveLevel();
711 711
          } else {
712 712
            n = _level->activeOn(level);
713 713
          }
714 714
          --num;
715 715
        }
716 716
      }
717 717
    }
718 718

	
719 719
    /// \brief Starts the second phase of the preflow algorithm.
720 720
    ///
721 721
    /// The preflow algorithm consists of two phases, this method runs
722 722
    /// the second phase. After calling one of the \ref init() functions
723 723
    /// and \ref startFirstPhase() and then \ref startSecondPhase(),
724 724
    /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
725 725
    /// value of a maximum flow, \ref minCut() returns a minimum cut
726 726
    /// \pre One of the \ref init() functions and \ref startFirstPhase()
727 727
    /// must be called before using this function.
728 728
    void startSecondPhase() {
729 729
      _phase = false;
730 730

	
731 731
      typename Digraph::template NodeMap<bool> reached(_graph);
732 732
      for (NodeIt n(_graph); n != INVALID; ++n) {
733 733
        reached.set(n, (*_level)[n] < _level->maxLevel());
734 734
      }
735 735

	
736 736
      _level->initStart();
737 737
      _level->initAddItem(_source);
738 738

	
739 739
      std::vector<Node> queue;
740 740
      queue.push_back(_source);
741 741
      reached.set(_source, true);
742 742

	
743 743
      while (!queue.empty()) {
744 744
        _level->initNewLevel();
745 745
        std::vector<Node> nqueue;
746 746
        for (int i = 0; i < int(queue.size()); ++i) {
747 747
          Node n = queue[i];
748 748
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
749 749
            Node v = _graph.target(e);
750 750
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
751 751
              reached.set(v, true);
752 752
              _level->initAddItem(v);
753 753
              nqueue.push_back(v);
754 754
            }
755 755
          }
756 756
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
757 757
            Node u = _graph.source(e);
758 758
            if (!reached[u] &&
759 759
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
760 760
              reached.set(u, true);
761 761
              _level->initAddItem(u);
762 762
              nqueue.push_back(u);
763 763
            }
764 764
          }
765 765
        }
766 766
        queue.swap(nqueue);
767 767
      }
768 768
      _level->initFinish();
769 769

	
770 770
      for (NodeIt n(_graph); n != INVALID; ++n) {
771 771
        if (!reached[n]) {
772 772
          _level->dirtyTopButOne(n);
773 773
        } else if ((*_excess)[n] > 0 && _target != n) {
774 774
          _level->activate(n);
775 775
        }
776 776
      }
777 777

	
778 778
      Node n;
779 779
      while ((n = _level->highestActive()) != INVALID) {
780 780
        Value excess = (*_excess)[n];
781 781
        int level = _level->highestActiveLevel();
782 782
        int new_level = _level->maxLevel();
783 783

	
784 784
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
785 785
          Value rem = (*_capacity)[e] - (*_flow)[e];
786 786
          if (!_tolerance.positive(rem)) continue;
787 787
          Node v = _graph.target(e);
788 788
          if ((*_level)[v] < level) {
789 789
            if (!_level->active(v) && v != _source) {
790 790
              _level->activate(v);
791 791
            }
792 792
            if (!_tolerance.less(rem, excess)) {
793 793
              _flow->set(e, (*_flow)[e] + excess);
794 794
              _excess->set(v, (*_excess)[v] + excess);
795 795
              excess = 0;
796 796
              goto no_more_push;
797 797
            } else {
798 798
              excess -= rem;
799 799
              _excess->set(v, (*_excess)[v] + rem);
800 800
              _flow->set(e, (*_capacity)[e]);
801 801
            }
802 802
          } else if (new_level > (*_level)[v]) {
803 803
            new_level = (*_level)[v];
804 804
          }
805 805
        }
806 806

	
807 807
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
808 808
          Value rem = (*_flow)[e];
809 809
          if (!_tolerance.positive(rem)) continue;
810 810
          Node v = _graph.source(e);
811 811
          if ((*_level)[v] < level) {
812 812
            if (!_level->active(v) && v != _source) {
813 813
              _level->activate(v);
814 814
            }
815 815
            if (!_tolerance.less(rem, excess)) {
816 816
              _flow->set(e, (*_flow)[e] - excess);
817 817
              _excess->set(v, (*_excess)[v] + excess);
818 818
              excess = 0;
819 819
              goto no_more_push;
820 820
            } else {
821 821
              excess -= rem;
822 822
              _excess->set(v, (*_excess)[v] + rem);
823 823
              _flow->set(e, 0);
824 824
            }
825 825
          } else if (new_level > (*_level)[v]) {
826 826
            new_level = (*_level)[v];
827 827
          }
828 828
        }
829 829

	
830 830
      no_more_push:
831 831

	
832 832
        _excess->set(n, excess);
833 833

	
834 834
        if (excess != 0) {
835 835
          if (new_level + 1 < _level->maxLevel()) {
836 836
            _level->liftHighestActive(new_level + 1);
837 837
          } else {
838 838
            // Calculation error
839 839
            _level->liftHighestActiveToTop();
840 840
          }
841 841
          if (_level->emptyLevel(level)) {
842 842
            // Calculation error
843 843
            _level->liftToTop(level);
844 844
          }
845 845
        } else {
846 846
          _level->deactivate(n);
847 847
        }
848 848

	
849 849
      }
850 850
    }
851 851

	
852 852
    /// \brief Runs the preflow algorithm.
853 853
    ///
854 854
    /// Runs the preflow algorithm.
855 855
    /// \note pf.run() is just a shortcut of the following code.
856 856
    /// \code
857 857
    ///   pf.init();
858 858
    ///   pf.startFirstPhase();
859 859
    ///   pf.startSecondPhase();
860 860
    /// \endcode
861 861
    void run() {
862 862
      init();
863 863
      startFirstPhase();
864 864
      startSecondPhase();
865 865
    }
866 866

	
867 867
    /// \brief Runs the preflow algorithm to compute the minimum cut.
868 868
    ///
869 869
    /// Runs the preflow algorithm to compute the minimum cut.
870 870
    /// \note pf.runMinCut() is just a shortcut of the following code.
871 871
    /// \code
872 872
    ///   pf.init();
873 873
    ///   pf.startFirstPhase();
874 874
    /// \endcode
875 875
    void runMinCut() {
876 876
      init();
877 877
      startFirstPhase();
878 878
    }
879 879

	
880 880
    /// @}
881 881

	
882 882
    /// \name Query Functions
883 883
    /// The results of the preflow algorithm can be obtained using these
884 884
    /// functions.\n
885 885
    /// Either one of the \ref run() "run*()" functions or one of the
886 886
    /// \ref startFirstPhase() "start*()" functions should be called
887 887
    /// before using them.
888 888

	
889 889
    ///@{
890 890

	
891 891
    /// \brief Returns the value of the maximum flow.
892 892
    ///
893 893
    /// Returns the value of the maximum flow by returning the excess
894 894
    /// of the target node. This value equals to the value of
895 895
    /// the maximum flow already after the first phase of the algorithm.
896 896
    ///
897 897
    /// \pre Either \ref run() or \ref init() must be called before
898 898
    /// using this function.
899 899
    Value flowValue() const {
900 900
      return (*_excess)[_target];
901 901
    }
902 902

	
903 903
    /// \brief Returns the flow on the given arc.
904 904
    ///
905 905
    /// Returns the flow on the given arc. This method can
906 906
    /// be called after the second phase of the algorithm.
907 907
    ///
908 908
    /// \pre Either \ref run() or \ref init() must be called before
909 909
    /// using this function.
910 910
    Value flow(const Arc& arc) const {
911 911
      return (*_flow)[arc];
912 912
    }
913 913

	
914 914
    /// \brief Returns a const reference to the flow map.
915 915
    ///
916 916
    /// Returns a const reference to the arc map storing the found flow.
917 917
    /// This method can be called after the second phase of the algorithm.
918 918
    ///
919 919
    /// \pre Either \ref run() or \ref init() must be called before
920 920
    /// using this function.
921 921
    const FlowMap& flowMap() const {
922 922
      return *_flow;
923 923
    }
924 924

	
925 925
    /// \brief Returns \c true when the node is on the source side of the
926 926
    /// minimum cut.
927 927
    ///
928 928
    /// Returns true when the node is on the source side of the found
929 929
    /// minimum cut. This method can be called both after running \ref
930 930
    /// startFirstPhase() and \ref startSecondPhase().
931 931
    ///
932 932
    /// \pre Either \ref run() or \ref init() must be called before
933 933
    /// using this function.
934 934
    bool minCut(const Node& node) const {
935 935
      return ((*_level)[node] == _level->maxLevel()) == _phase;
936 936
    }
937 937

	
938 938
    /// \brief Gives back a minimum value cut.
939 939
    ///
940 940
    /// Sets \c cutMap to the characteristic vector of a minimum value
941 941
    /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
942 942
    /// node map with \c bool (or convertible) value type.
943 943
    ///
944 944
    /// This method can be called both after running \ref startFirstPhase()
945 945
    /// and \ref startSecondPhase(). The result after the second phase
946 946
    /// could be slightly different if inexact computation is used.
947 947
    ///
948 948
    /// \note This function calls \ref minCut() for each node, so it runs in
949 949
    /// \f$O(n)\f$ time.
950 950
    ///
951 951
    /// \pre Either \ref run() or \ref init() must be called before
952 952
    /// using this function.
953 953
    template <typename CutMap>
954 954
    void minCutMap(CutMap& cutMap) const {
955 955
      for (NodeIt n(_graph); n != INVALID; ++n) {
956 956
        cutMap.set(n, minCut(n));
957 957
      }
958 958
    }
959 959

	
960 960
    /// @}
961 961
  };
962 962
}
963 963

	
964 964
#endif
0 comments (0 inline)