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

	
19 19
namespace lemon {
20 20

	
21 21
/**
22 22
@defgroup datas Data Structures
23 23
This group contains the several data structures implemented in LEMON.
24 24
*/
25 25

	
26 26
/**
27 27
@defgroup graphs Graph Structures
28 28
@ingroup datas
29 29
\brief Graph structures implemented in LEMON.
30 30

	
31 31
The implementation of combinatorial algorithms heavily relies on
32 32
efficient graph implementations. LEMON offers data structures which are
33 33
planned to be easily used in an experimental phase of implementation studies,
34 34
and thereafter the program code can be made efficient by small modifications.
35 35

	
36 36
The most efficient implementation of diverse applications require the
37 37
usage of different physical graph implementations. These differences
38 38
appear in the size of graph we require to handle, memory or time usage
39 39
limitations or in the set of operations through which the graph can be
40 40
accessed.  LEMON provides several physical graph structures to meet
41 41
the diverging requirements of the possible users.  In order to save on
42 42
running time or on memory usage, some structures may fail to provide
43 43
some graph features like arc/edge or node deletion.
44 44

	
45 45
Alteration of standard containers need a very limited number of
46 46
operations, these together satisfy the everyday requirements.
47 47
In the case of graph structures, different operations are needed which do
48 48
not alter the physical graph, but gives another view. If some nodes or
49 49
arcs have to be hidden or the reverse oriented graph have to be used, then
50 50
this is the case. It also may happen that in a flow implementation
51 51
the residual graph can be accessed by another algorithm, or a node-set
52 52
is to be shrunk for another algorithm.
53 53
LEMON also provides a variety of graphs for these requirements called
54 54
\ref graph_adaptors "graph adaptors". Adaptors cannot be used alone but only
55 55
in conjunction with other graph representations.
56 56

	
57 57
You are free to use the graph structure that fit your requirements
58 58
the best, most graph algorithms and auxiliary data structures can be used
59 59
with any graph structure.
60 60

	
61 61
<b>See also:</b> \ref graph_concepts "Graph Structure Concepts".
62 62
*/
63 63

	
64 64
/**
65 65
@defgroup graph_adaptors Adaptor Classes for Graphs
66 66
@ingroup graphs
67 67
\brief Adaptor classes for digraphs and graphs
68 68

	
69 69
This group contains several useful adaptor classes for digraphs and graphs.
70 70

	
71 71
The main parts of LEMON are the different graph structures, generic
72 72
graph algorithms, graph concepts, which couple them, and graph
73 73
adaptors. While the previous notions are more or less clear, the
74 74
latter one needs further explanation. Graph adaptors are graph classes
75 75
which serve for considering graph structures in different ways.
76 76

	
77 77
A short example makes this much clearer.  Suppose that we have an
78 78
instance \c g of a directed graph type, say ListDigraph and an algorithm
79 79
\code
80 80
template <typename Digraph>
81 81
int algorithm(const Digraph&);
82 82
\endcode
83 83
is needed to run on the reverse oriented graph.  It may be expensive
84 84
(in time or in memory usage) to copy \c g with the reversed
85 85
arcs.  In this case, an adaptor class is used, which (according
86 86
to LEMON \ref concepts::Digraph "digraph concepts") works as a digraph.
87 87
The adaptor uses the original digraph structure and digraph operations when
88 88
methods of the reversed oriented graph are called.  This means that the adaptor
89 89
have minor memory usage, and do not perform sophisticated algorithmic
90 90
actions.  The purpose of it is to give a tool for the cases when a
91 91
graph have to be used in a specific alteration.  If this alteration is
92 92
obtained by a usual construction like filtering the node or the arc set or
93 93
considering a new orientation, then an adaptor is worthwhile to use.
94 94
To come back to the reverse oriented graph, in this situation
95 95
\code
96 96
template<typename Digraph> class ReverseDigraph;
97 97
\endcode
98 98
template class can be used. The code looks as follows
99 99
\code
100 100
ListDigraph g;
101 101
ReverseDigraph<ListDigraph> rg(g);
102 102
int result = algorithm(rg);
103 103
\endcode
104 104
During running the algorithm, the original digraph \c g is untouched.
105 105
This techniques give rise to an elegant code, and based on stable
106 106
graph adaptors, complex algorithms can be implemented easily.
107 107

	
108 108
In flow, circulation and matching problems, the residual
109 109
graph is of particular importance. Combining an adaptor implementing
110 110
this with shortest path algorithms or minimum mean cycle algorithms,
111 111
a range of weighted and cardinality optimization algorithms can be
112 112
obtained. For other examples, the interested user is referred to the
113 113
detailed documentation of particular adaptors.
114 114

	
115 115
The behavior of graph adaptors can be very different. Some of them keep
116 116
capabilities of the original graph while in other cases this would be
117 117
meaningless. This means that the concepts that they meet depend
118 118
on the graph adaptor, and the wrapped graph.
119 119
For example, if an arc of a reversed digraph is deleted, this is carried
120 120
out by deleting the corresponding arc of the original digraph, thus the
121 121
adaptor modifies the original digraph.
122 122
However in case of a residual digraph, this operation has no sense.
123 123

	
124 124
Let us stand one more example here to simplify your work.
125 125
ReverseDigraph has constructor
126 126
\code
127 127
ReverseDigraph(Digraph& digraph);
128 128
\endcode
129 129
This means that in a situation, when a <tt>const %ListDigraph&</tt>
130 130
reference to a graph is given, then it have to be instantiated with
131 131
<tt>Digraph=const %ListDigraph</tt>.
132 132
\code
133 133
int algorithm1(const ListDigraph& g) {
134 134
  ReverseDigraph<const ListDigraph> rg(g);
135 135
  return algorithm2(rg);
136 136
}
137 137
\endcode
138 138
*/
139 139

	
140 140
/**
141 141
@defgroup maps Maps
142 142
@ingroup datas
143 143
\brief Map structures implemented in LEMON.
144 144

	
145 145
This group contains the map structures implemented in LEMON.
146 146

	
147 147
LEMON provides several special purpose maps and map adaptors that e.g. combine
148 148
new maps from existing ones.
149 149

	
150 150
<b>See also:</b> \ref map_concepts "Map Concepts".
151 151
*/
152 152

	
153 153
/**
154 154
@defgroup graph_maps Graph Maps
155 155
@ingroup maps
156 156
\brief Special graph-related maps.
157 157

	
158 158
This group contains maps that are specifically designed to assign
159 159
values to the nodes and arcs/edges of graphs.
160 160

	
161 161
If you are looking for the standard graph maps (\c NodeMap, \c ArcMap,
162 162
\c EdgeMap), see the \ref graph_concepts "Graph Structure Concepts".
163 163
*/
164 164

	
165 165
/**
166 166
\defgroup map_adaptors Map Adaptors
167 167
\ingroup maps
168 168
\brief Tools to create new maps from existing ones
169 169

	
170 170
This group contains map adaptors that are used to create "implicit"
171 171
maps from other maps.
172 172

	
173 173
Most of them are \ref concepts::ReadMap "read-only maps".
174 174
They can make arithmetic and logical operations between one or two maps
175 175
(negation, shifting, addition, multiplication, logical 'and', 'or',
176 176
'not' etc.) or e.g. convert a map to another one of different Value type.
177 177

	
178 178
The typical usage of this classes is passing implicit maps to
179 179
algorithms.  If a function type algorithm is called then the function
180 180
type map adaptors can be used comfortable. For example let's see the
181 181
usage of map adaptors with the \c graphToEps() function.
182 182
\code
183 183
  Color nodeColor(int deg) {
184 184
    if (deg >= 2) {
185 185
      return Color(0.5, 0.0, 0.5);
186 186
    } else if (deg == 1) {
187 187
      return Color(1.0, 0.5, 1.0);
188 188
    } else {
189 189
      return Color(0.0, 0.0, 0.0);
190 190
    }
191 191
  }
192 192

	
193 193
  Digraph::NodeMap<int> degree_map(graph);
194 194

	
195 195
  graphToEps(graph, "graph.eps")
196 196
    .coords(coords).scaleToA4().undirected()
197 197
    .nodeColors(composeMap(functorToMap(nodeColor), degree_map))
198 198
    .run();
199 199
\endcode
200 200
The \c functorToMap() function makes an \c int to \c Color map from the
201 201
\c nodeColor() function. The \c composeMap() compose the \c degree_map
202 202
and the previously created map. The composed map is a proper function to
203 203
get the color of each node.
204 204

	
205 205
The usage with class type algorithms is little bit harder. In this
206 206
case the function type map adaptors can not be used, because the
207 207
function map adaptors give back temporary objects.
208 208
\code
209 209
  Digraph graph;
210 210

	
211 211
  typedef Digraph::ArcMap<double> DoubleArcMap;
212 212
  DoubleArcMap length(graph);
213 213
  DoubleArcMap speed(graph);
214 214

	
215 215
  typedef DivMap<DoubleArcMap, DoubleArcMap> TimeMap;
216 216
  TimeMap time(length, speed);
217 217

	
218 218
  Dijkstra<Digraph, TimeMap> dijkstra(graph, time);
219 219
  dijkstra.run(source, target);
220 220
\endcode
221 221
We have a length map and a maximum speed map on the arcs of a digraph.
222 222
The minimum time to pass the arc can be calculated as the division of
223 223
the two maps which can be done implicitly with the \c DivMap template
224 224
class. We use the implicit minimum time map as the length map of the
225 225
\c Dijkstra algorithm.
226 226
*/
227 227

	
228 228
/**
229 229
@defgroup matrices Matrices
230 230
@ingroup datas
231 231
\brief Two dimensional data storages implemented in LEMON.
232 232

	
233 233
This group contains two dimensional data storages implemented in LEMON.
234 234
*/
235 235

	
236 236
/**
237 237
@defgroup paths Path Structures
238 238
@ingroup datas
239 239
\brief %Path structures implemented in LEMON.
240 240

	
241 241
This group contains the path structures implemented in LEMON.
242 242

	
243 243
LEMON provides flexible data structures to work with paths.
244 244
All of them have similar interfaces and they can be copied easily with
245 245
assignment operators and copy constructors. This makes it easy and
246 246
efficient to have e.g. the Dijkstra algorithm to store its result in
247 247
any kind of path structure.
248 248

	
249 249
\sa lemon::concepts::Path
250 250
*/
251 251

	
252 252
/**
253 253
@defgroup auxdat Auxiliary Data Structures
254 254
@ingroup datas
255 255
\brief Auxiliary data structures implemented in LEMON.
256 256

	
257 257
This group contains some data structures implemented in LEMON in
258 258
order to make it easier to implement combinatorial algorithms.
259 259
*/
260 260

	
261 261
/**
262 262
@defgroup algs Algorithms
263 263
\brief This group contains the several algorithms
264 264
implemented in LEMON.
265 265

	
266 266
This group contains the several algorithms
267 267
implemented in LEMON.
268 268
*/
269 269

	
270 270
/**
271 271
@defgroup search Graph Search
272 272
@ingroup algs
273 273
\brief Common graph search algorithms.
274 274

	
275 275
This group contains the common graph search algorithms, namely
276 276
\e breadth-first \e search (BFS) and \e depth-first \e search (DFS).
277 277
*/
278 278

	
279 279
/**
280 280
@defgroup shortest_path Shortest Path Algorithms
281 281
@ingroup algs
282 282
\brief Algorithms for finding shortest paths.
283 283

	
284 284
This group contains the algorithms for finding shortest paths in digraphs.
285 285

	
286 286
 - \ref Dijkstra algorithm for finding shortest paths from a source node
287 287
   when all arc lengths are non-negative.
288 288
 - \ref BellmanFord "Bellman-Ford" algorithm for finding shortest paths
289 289
   from a source node when arc lenghts can be either positive or negative,
290 290
   but the digraph should not contain directed cycles with negative total
291 291
   length.
292 292
 - \ref FloydWarshall "Floyd-Warshall" and \ref Johnson "Johnson" algorithms
293 293
   for solving the \e all-pairs \e shortest \e paths \e problem when arc
294 294
   lenghts can be either positive or negative, but the digraph should
295 295
   not contain directed cycles with negative total length.
296 296
 - \ref Suurballe A successive shortest path algorithm for finding
297 297
   arc-disjoint paths between two nodes having minimum total length.
298 298
*/
299 299

	
300 300
/**
301 301
@defgroup max_flow Maximum Flow Algorithms
302 302
@ingroup algs
303 303
\brief Algorithms for finding maximum flows.
304 304

	
305 305
This group contains the algorithms for finding maximum flows and
306 306
feasible circulations.
307 307

	
308 308
The \e maximum \e flow \e problem is to find a flow of maximum value between
309 309
a single source and a single target. Formally, there is a \f$G=(V,A)\f$
310 310
digraph, a \f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function and
311 311
\f$s, t \in V\f$ source and target nodes.
312 312
A maximum flow is an \f$f: A\rightarrow\mathbf{R}^+_0\f$ solution of the
313 313
following optimization problem.
314 314

	
315 315
\f[ \max\sum_{sv\in A} f(sv) - \sum_{vs\in A} f(vs) \f]
316 316
\f[ \sum_{uv\in A} f(uv) = \sum_{vu\in A} f(vu)
317 317
    \quad \forall u\in V\setminus\{s,t\} \f]
318 318
\f[ 0 \leq f(uv) \leq cap(uv) \quad \forall uv\in A \f]
319 319

	
320 320
LEMON contains several algorithms for solving maximum flow problems:
321 321
- \ref EdmondsKarp Edmonds-Karp algorithm.
322 322
- \ref Preflow Goldberg-Tarjan's preflow push-relabel algorithm.
323 323
- \ref DinitzSleatorTarjan Dinitz's blocking flow algorithm with dynamic trees.
324 324
- \ref GoldbergTarjan Preflow push-relabel algorithm with dynamic trees.
325 325

	
326 326
In most cases the \ref Preflow "Preflow" algorithm provides the
327 327
fastest method for computing a maximum flow. All implementations
328 328
also provide functions to query the minimum cut, which is the dual
329 329
problem of maximum flow.
330 330

	
331 331
\ref Circulation is a preflow push-relabel algorithm implemented directly 
332 332
for finding feasible circulations, which is a somewhat different problem,
333 333
but it is strongly related to maximum flow.
334 334
For more information, see \ref Circulation.
335 335
*/
336 336

	
337 337
/**
338 338
@defgroup min_cost_flow_algs Minimum Cost Flow Algorithms
339 339
@ingroup algs
340 340

	
341 341
\brief Algorithms for finding minimum cost flows and circulations.
342 342

	
343 343
This group contains the algorithms for finding minimum cost flows and
344 344
circulations. For more information about this problem and its dual
345 345
solution see \ref min_cost_flow "Minimum Cost Flow Problem".
346 346

	
347 347
LEMON contains several algorithms for this problem.
348 348
 - \ref NetworkSimplex Primal Network Simplex algorithm with various
349 349
   pivot strategies.
350 350
 - \ref CostScaling Push-Relabel and Augment-Relabel algorithms based on
351 351
   cost scaling.
352 352
 - \ref CapacityScaling Successive Shortest %Path algorithm with optional
353 353
   capacity scaling.
354 354
 - \ref CancelAndTighten The Cancel and Tighten algorithm.
355 355
 - \ref CycleCanceling Cycle-Canceling algorithms.
356 356

	
357 357
In general NetworkSimplex is the most efficient implementation,
358 358
but in special cases other algorithms could be faster.
359 359
For example, if the total supply and/or capacities are rather small,
360 360
CapacityScaling is usually the fastest algorithm (without effective scaling).
361 361
*/
362 362

	
363 363
/**
364 364
@defgroup min_cut Minimum Cut Algorithms
365 365
@ingroup algs
366 366

	
367 367
\brief Algorithms for finding minimum cut in graphs.
368 368

	
369 369
This group contains the algorithms for finding minimum cut in graphs.
370 370

	
371 371
The \e minimum \e cut \e problem is to find a non-empty and non-complete
372 372
\f$X\f$ subset of the nodes with minimum overall capacity on
373 373
outgoing arcs. Formally, there is a \f$G=(V,A)\f$ digraph, a
374 374
\f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function. The minimum
375 375
cut is the \f$X\f$ solution of the next optimization problem:
376 376

	
377 377
\f[ \min_{X \subset V, X\not\in \{\emptyset, V\}}
378
    \sum_{uv\in A, u\in X, v\not\in X}cap(uv) \f]
378
    \sum_{uv\in A: u\in X, v\not\in X}cap(uv) \f]
379 379

	
380 380
LEMON contains several algorithms related to minimum cut problems:
381 381

	
382 382
- \ref HaoOrlin "Hao-Orlin algorithm" for calculating minimum cut
383 383
  in directed graphs.
384 384
- \ref NagamochiIbaraki "Nagamochi-Ibaraki algorithm" for
385 385
  calculating minimum cut in undirected graphs.
386 386
- \ref GomoryHu "Gomory-Hu tree computation" for calculating
387 387
  all-pairs minimum cut in undirected graphs.
388 388

	
389 389
If you want to find minimum cut just between two distinict nodes,
390 390
see the \ref max_flow "maximum flow problem".
391 391
*/
392 392

	
393 393
/**
394 394
@defgroup graph_properties Connectivity and Other Graph Properties
395 395
@ingroup algs
396 396
\brief Algorithms for discovering the graph properties
397 397

	
398 398
This group contains the algorithms for discovering the graph properties
399 399
like connectivity, bipartiteness, euler property, simplicity etc.
400 400

	
401
\image html edge_biconnected_components.png
402
\image latex edge_biconnected_components.eps "bi-edge-connected components" width=\textwidth
401
\image html connected_components.png
402
\image latex connected_components.eps "Connected components" width=\textwidth
403 403
*/
404 404

	
405 405
/**
406 406
@defgroup planar Planarity Embedding and Drawing
407 407
@ingroup algs
408 408
\brief Algorithms for planarity checking, embedding and drawing
409 409

	
410 410
This group contains the algorithms for planarity checking,
411 411
embedding and drawing.
412 412

	
413 413
\image html planar.png
414 414
\image latex planar.eps "Plane graph" width=\textwidth
415 415
*/
416 416

	
417 417
/**
418 418
@defgroup matching Matching Algorithms
419 419
@ingroup algs
420 420
\brief Algorithms for finding matchings in graphs and bipartite graphs.
421 421

	
422 422
This group contains the algorithms for calculating
423 423
matchings in graphs and bipartite graphs. The general matching problem is
424 424
finding a subset of the edges for which each node has at most one incident
425 425
edge.
426 426

	
427 427
There are several different algorithms for calculate matchings in
428 428
graphs.  The matching problems in bipartite graphs are generally
429 429
easier than in general graphs. The goal of the matching optimization
430 430
can be finding maximum cardinality, maximum weight or minimum cost
431 431
matching. The search can be constrained to find perfect or
432 432
maximum cardinality matching.
433 433

	
434 434
The matching algorithms implemented in LEMON:
435 435
- \ref MaxBipartiteMatching Hopcroft-Karp augmenting path algorithm
436 436
  for calculating maximum cardinality matching in bipartite graphs.
437 437
- \ref PrBipartiteMatching Push-relabel algorithm
438 438
  for calculating maximum cardinality matching in bipartite graphs.
439 439
- \ref MaxWeightedBipartiteMatching
440 440
  Successive shortest path algorithm for calculating maximum weighted
441 441
  matching and maximum weighted bipartite matching in bipartite graphs.
442 442
- \ref MinCostMaxBipartiteMatching
443 443
  Successive shortest path algorithm for calculating minimum cost maximum
444 444
  matching in bipartite graphs.
445 445
- \ref MaxMatching Edmond's blossom shrinking algorithm for calculating
446 446
  maximum cardinality matching in general graphs.
447 447
- \ref MaxWeightedMatching Edmond's blossom shrinking algorithm for calculating
448 448
  maximum weighted matching in general graphs.
449 449
- \ref MaxWeightedPerfectMatching
450 450
  Edmond's blossom shrinking algorithm for calculating maximum weighted
451 451
  perfect matching in general graphs.
452 452

	
453 453
\image html bipartite_matching.png
454 454
\image latex bipartite_matching.eps "Bipartite Matching" width=\textwidth
455 455
*/
456 456

	
457 457
/**
458 458
@defgroup spantree Minimum Spanning Tree Algorithms
459 459
@ingroup algs
460 460
\brief Algorithms for finding minimum cost spanning trees and arborescences.
461 461

	
462 462
This group contains the algorithms for finding minimum cost spanning
463 463
trees and arborescences.
464 464
*/
465 465

	
466 466
/**
467 467
@defgroup auxalg Auxiliary Algorithms
468 468
@ingroup algs
469 469
\brief Auxiliary algorithms implemented in LEMON.
470 470

	
471 471
This group contains some algorithms implemented in LEMON
472 472
in order to make it easier to implement complex algorithms.
473 473
*/
474 474

	
475 475
/**
476 476
@defgroup approx Approximation Algorithms
477 477
@ingroup algs
478 478
\brief Approximation algorithms.
479 479

	
480 480
This group contains the approximation and heuristic algorithms
481 481
implemented in LEMON.
482 482
*/
483 483

	
484 484
/**
485 485
@defgroup gen_opt_group General Optimization Tools
486 486
\brief This group contains some general optimization frameworks
487 487
implemented in LEMON.
488 488

	
489 489
This group contains some general optimization frameworks
490 490
implemented in LEMON.
491 491
*/
492 492

	
493 493
/**
494 494
@defgroup lp_group Lp and Mip Solvers
495 495
@ingroup gen_opt_group
496 496
\brief Lp and Mip solver interfaces for LEMON.
497 497

	
498 498
This group contains Lp and Mip solver interfaces for LEMON. The
499 499
various LP solvers could be used in the same manner with this
500 500
interface.
501 501
*/
502 502

	
503 503
/**
504 504
@defgroup lp_utils Tools for Lp and Mip Solvers
505 505
@ingroup lp_group
506 506
\brief Helper tools to the Lp and Mip solvers.
507 507

	
508 508
This group adds some helper tools to general optimization framework
509 509
implemented in LEMON.
510 510
*/
511 511

	
512 512
/**
513 513
@defgroup metah Metaheuristics
514 514
@ingroup gen_opt_group
515 515
\brief Metaheuristics for LEMON library.
516 516

	
517 517
This group contains some metaheuristic optimization tools.
518 518
*/
519 519

	
520 520
/**
521 521
@defgroup utils Tools and Utilities
522 522
\brief Tools and utilities for programming in LEMON
523 523

	
524 524
Tools and utilities for programming in LEMON.
525 525
*/
526 526

	
527 527
/**
528 528
@defgroup gutils Basic Graph Utilities
529 529
@ingroup utils
530 530
\brief Simple basic graph utilities.
531 531

	
532 532
This group contains some simple basic graph utilities.
533 533
*/
534 534

	
535 535
/**
536 536
@defgroup misc Miscellaneous Tools
537 537
@ingroup utils
538 538
\brief Tools for development, debugging and testing.
539 539

	
540 540
This group contains several useful tools for development,
541 541
debugging and testing.
542 542
*/
543 543

	
544 544
/**
545 545
@defgroup timecount Time Measuring and Counting
546 546
@ingroup misc
547 547
\brief Simple tools for measuring the performance of algorithms.
548 548

	
549 549
This group contains simple tools for measuring the performance
550 550
of algorithms.
551 551
*/
552 552

	
553 553
/**
554 554
@defgroup exceptions Exceptions
555 555
@ingroup utils
556 556
\brief Exceptions defined in LEMON.
557 557

	
558 558
This group contains the exceptions defined in LEMON.
559 559
*/
560 560

	
561 561
/**
562 562
@defgroup io_group Input-Output
563 563
\brief Graph Input-Output methods
564 564

	
565 565
This group contains the tools for importing and exporting graphs
566 566
and graph related data. Now it supports the \ref lgf-format
567 567
"LEMON Graph Format", the \c DIMACS format and the encapsulated
568 568
postscript (EPS) format.
569 569
*/
570 570

	
571 571
/**
572 572
@defgroup lemon_io LEMON Graph Format
573 573
@ingroup io_group
574 574
\brief Reading and writing LEMON Graph Format.
575 575

	
576 576
This group contains methods for reading and writing
577 577
\ref lgf-format "LEMON Graph Format".
578 578
*/
579 579

	
580 580
/**
581 581
@defgroup eps_io Postscript Exporting
582 582
@ingroup io_group
583 583
\brief General \c EPS drawer and graph exporter
584 584

	
585 585
This group contains general \c EPS drawing methods and special
586 586
graph exporting tools.
587 587
*/
588 588

	
589 589
/**
590 590
@defgroup dimacs_group DIMACS format
591 591
@ingroup io_group
592 592
\brief Read and write files in DIMACS format
593 593

	
594 594
Tools to read a digraph from or write it to a file in DIMACS format data.
595 595
*/
596 596

	
597 597
/**
598 598
@defgroup nauty_group NAUTY Format
599 599
@ingroup io_group
600 600
\brief Read \e Nauty format
601 601

	
602 602
Tool to read graphs from \e Nauty format data.
603 603
*/
604 604

	
605 605
/**
606 606
@defgroup concept Concepts
607 607
\brief Skeleton classes and concept checking classes
608 608

	
609 609
This group contains the data/algorithm skeletons and concept checking
610 610
classes implemented in LEMON.
611 611

	
612 612
The purpose of the classes in this group is fourfold.
613 613

	
614 614
- These classes contain the documentations of the %concepts. In order
615 615
  to avoid document multiplications, an implementation of a concept
616 616
  simply refers to the corresponding concept class.
617 617

	
618 618
- These classes declare every functions, <tt>typedef</tt>s etc. an
619 619
  implementation of the %concepts should provide, however completely
620 620
  without implementations and real data structures behind the
621 621
  interface. On the other hand they should provide nothing else. All
622 622
  the algorithms working on a data structure meeting a certain concept
623 623
  should compile with these classes. (Though it will not run properly,
624 624
  of course.) In this way it is easily to check if an algorithm
625 625
  doesn't use any extra feature of a certain implementation.
626 626

	
627 627
- The concept descriptor classes also provide a <em>checker class</em>
628 628
  that makes it possible to check whether a certain implementation of a
629 629
  concept indeed provides all the required features.
630 630

	
631 631
- Finally, They can serve as a skeleton of a new implementation of a concept.
632 632
*/
633 633

	
634 634
/**
635 635
@defgroup graph_concepts Graph Structure Concepts
636 636
@ingroup concept
637 637
\brief Skeleton and concept checking classes for graph structures
638 638

	
639 639
This group contains the skeletons and concept checking classes of LEMON's
640 640
graph structures and helper classes used to implement these.
641 641
*/
642 642

	
643 643
/**
644 644
@defgroup map_concepts Map Concepts
645 645
@ingroup concept
646 646
\brief Skeleton and concept checking classes for maps
647 647

	
648 648
This group contains the skeletons and concept checking classes of maps.
649 649
*/
650 650

	
651 651
/**
652 652
\anchor demoprograms
653 653

	
654 654
@defgroup demos Demo Programs
655 655

	
656 656
Some demo programs are listed here. Their full source codes can be found in
657 657
the \c demo subdirectory of the source tree.
658 658

	
659 659
In order to compile them, use the <tt>make demo</tt> or the
660 660
<tt>make check</tt> commands.
661 661
*/
662 662

	
663 663
/**
664 664
@defgroup tools Standalone Utility Applications
665 665

	
666 666
Some utility applications are listed here.
667 667

	
668 668
The standard compilation procedure (<tt>./configure;make</tt>) will compile
669 669
them, as well.
670 670
*/
671 671

	
672 672
}
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 52
    ///Instantiates a \c PredMap.
53 53

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

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

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

	
69 69
    ///This function instantiates a \ref ProcessedMap.
70 70
    ///\param g is the digraph, to which
71 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 86
    ///Instantiates a \c ReachedMap.
87 87

	
88 88
    ///This function instantiates a \ref ReachedMap.
89 89
    ///\param g is the digraph, to which
90 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 101
    ///Instantiates a \c DistMap.
102 102

	
103 103
    ///This function instantiates a \ref DistMap.
104 104
    ///\param g is the digraph, to which we would like to define the
105 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 224
    ///\c PredMap type.
225 225
    ///
226 226
    ///\ref named-templ-param "Named parameter" for setting
227 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 244
    ///\c DistMap type.
245 245
    ///
246 246
    ///\ref named-templ-param "Named parameter" for setting
247 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 264
    ///\c ReachedMap type.
265 265
    ///
266 266
    ///\ref named-templ-param "Named parameter" for setting
267 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 284
    ///\c ProcessedMap type.
285 285
    ///
286 286
    ///\ref named-templ-param "Named parameter" for setting
287 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 303
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
304 304
    ///
305 305
    ///\ref named-templ-param "Named parameter" for setting
306 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
    ///If you need more control on the execution, first you have to call
417
    ///\ref init(), then you can add several source nodes with
416
    ///If you need better control on the execution, you have to call
417
    ///\ref init() first, 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 1197
  template <typename GR>
1198 1198
  struct BfsVisitor {
1199 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 1227
  template <typename GR>
1228 1228
  struct BfsVisitor {
1229 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 1257
  /// \tparam GR The type of the digraph the algorithm runs on.
1258 1258
  template<class GR>
1259 1259
  struct BfsVisitDefaultTraits {
1260 1260

	
1261 1261
    /// \brief The type of the digraph the algorithm runs on.
1262 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 1283
  /// \brief BFS algorithm class with visitor interface.
1284 1284
  ///
1285 1285
  /// This class provides an efficient implementation of the BFS algorithm
1286 1286
  /// with visitor interface.
1287 1287
  ///
1288 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 1297
  /// \tparam GR The type of the digraph the algorithm runs on.
1298 1298
  /// The default type is \ref ListDigraph.
1299 1299
  /// The value of GR is not used directly by \ref BfsVisit,
1300 1300
  /// it is only passed to \ref BfsVisitDefaultTraits.
1301 1301
  /// \tparam VS The Visitor type that is used by the algorithm.
1302 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 1305
  /// \tparam TR Traits class to set various data types used by the
1306 1306
  /// algorithm. The default traits class is
1307 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 1311
  template <typename GR, typename VS, typename TR>
1312 1312
#else
1313 1313
  template <typename GR = ListDigraph,
1314 1314
            typename VS = BfsVisitor<GR>,
1315 1315
            typename TR = BfsVisitDefaultTraits<GR> >
1316 1316
#endif
1317 1317
  class BfsVisit {
1318 1318
  public:
1319 1319

	
1320 1320
    ///The traits class.
1321 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 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
    /// If you need more control on the execution, first you have to call
1429
    /// \ref init(), then you can add several source nodes with
1428
    /// If you need better control on the execution, you have to call
1429
    /// \ref init() first, 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_CIRCULATION_H
20 20
#define LEMON_CIRCULATION_H
21 21

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

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

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

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

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

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

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

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

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

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

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

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

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

	
109 116
  };
110 117

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

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

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

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

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

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

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

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

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

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

	
207 214
  private:
208 215

	
209 216
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
210 217

	
211 218
    const Digraph &_g;
212 219
    int _node_num;
213 220

	
214 221
    const LowerMap *_lo;
215 222
    const UpperMap *_up;
216 223
    const SupplyMap *_supply;
217 224

	
218 225
    FlowMap *_flow;
219 226
    bool _local_flow;
220 227

	
221 228
    Elevator* _level;
222 229
    bool _local_level;
223 230

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

	
227 234
    Tolerance _tol;
228 235
    int _el;
229 236

	
230 237
  public:
231 238

	
232 239
    typedef Circulation Create;
233 240

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

	
236 243
    ///@{
237 244

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

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

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

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

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

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

	
314 321
    /// @}
315 322

	
316 323
  protected:
317 324

	
318 325
    Circulation() {}
319 326

	
320 327
  public:
321 328

	
322 329
    /// Constructor.
323 330

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

	
337 344
    /// Destructor.
338 345
    ~Circulation() {
339 346
      destroyStructures();
340 347
    }
341 348

	
342 349

	
343 350
  private:
344 351

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

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

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

	
368 375
    void destroyStructures() {
369 376
      if (_local_flow) {
370 377
        delete _flow;
371 378
      }
372 379
      if (_local_level) {
373 380
        delete _level;
374 381
      }
375 382
      if (_excess) {
376 383
        delete _excess;
377 384
      }
378 385
    }
379 386

	
380 387
  public:
381 388

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

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

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

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

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

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

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

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

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

	
453 460
    /// \brief Sets the tolerance used by algorithm.
454 461
    ///
455 462
    /// Sets the tolerance used by algorithm.
456 463
    Circulation& tolerance(const Tolerance& tolerance) const {
457 464
      _tol = tolerance;
458 465
      return *this;
459 466
    }
460 467

	
461 468
    /// \brief Returns a const reference to the tolerance.
462 469
    ///
463 470
    /// Returns a const reference to the tolerance.
464 471
    const Tolerance& tolerance() const {
465 472
      return tolerance;
466 473
    }
467 474

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

	
474 481
    ///@{
475 482

	
476 483
    /// Initializes the internal data structures.
477 484

	
478 485
    /// Initializes the internal data structures and sets all flow values
479 486
    /// to the lower bound.
480 487
    void init()
481 488
    {
482 489
      LEMON_DEBUG(checkBoundMaps(),
483 490
        "Upper bounds must be greater or equal to the lower bounds");
484 491

	
485 492
      createStructures();
486 493

	
487 494
      for(NodeIt n(_g);n!=INVALID;++n) {
488 495
        (*_excess)[n] = (*_supply)[n];
489 496
      }
490 497

	
491 498
      for (ArcIt e(_g);e!=INVALID;++e) {
492 499
        _flow->set(e, (*_lo)[e]);
493 500
        (*_excess)[_g.target(e)] += (*_flow)[e];
494 501
        (*_excess)[_g.source(e)] -= (*_flow)[e];
495 502
      }
496 503

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

	
508 515
    /// Initializes the internal data structures using a greedy approach.
509 516

	
510 517
    /// Initializes the internal data structures using a greedy approach
511 518
    /// to construct the initial solution.
512 519
    void greedyInit()
513 520
    {
514 521
      LEMON_DEBUG(checkBoundMaps(),
515 522
        "Upper bounds must be greater or equal to the lower bounds");
516 523

	
517 524
      createStructures();
518 525

	
519 526
      for(NodeIt n(_g);n!=INVALID;++n) {
520 527
        (*_excess)[n] = (*_supply)[n];
521 528
      }
522 529

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

	
540 547
      _level->initStart();
541 548
      for(NodeIt n(_g);n!=INVALID;++n)
542 549
        _level->initAddItem(n);
543 550
      _level->initFinish();
544 551
      for(NodeIt n(_g);n!=INVALID;++n)
545 552
        if(_tol.positive((*_excess)[n]))
546 553
          _level->activate(n);
547 554
    }
548 555

	
549 556
    ///Executes the algorithm
550 557

	
551 558
    ///This function executes the algorithm.
552 559
    ///
553 560
    ///\return \c true if a feasible circulation is found.
554 561
    ///
555 562
    ///\sa barrier()
556 563
    ///\sa barrierMap()
557 564
    bool start()
558 565
    {
559 566

	
560 567
      Node act;
561 568
      Node bact=INVALID;
562 569
      Node last_activated=INVALID;
563 570
      while((act=_level->highestActive())!=INVALID) {
564 571
        int actlevel=(*_level)[act];
565 572
        int mlevel=_node_num;
566 573
        Value exc=(*_excess)[act];
567 574

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

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

	
637 644
    /// Runs the algorithm.
638 645

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

	
654 661
    /// @}
655 662

	
656 663
    /// \name Query Functions
657 664
    /// The results of the circulation algorithm can be obtained using
658 665
    /// these functions.\n
659 666
    /// Either \ref run() or \ref start() should be called before
660 667
    /// using them.
661 668

	
662 669
    ///@{
663 670

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

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

	
684 691
    /**
685 692
       \brief Returns \c true if the given node is in a barrier.
686 693

	
687 694
       Barrier is a set \e B of nodes for which
688 695

	
689 696
       \f[ \sum_{uv\in A: u\in B} upper(uv) -
690 697
           \sum_{uv\in A: v\in B} lower(uv) < \sum_{v\in B} sup(v) \f]
691 698

	
692 699
       holds. The existence of a set with this property prooves that a
693 700
       feasible circualtion cannot exist.
694 701

	
695 702
       This function returns \c true if the given node is in the found
696 703
       barrier. If a feasible circulation is found, the function
697 704
       gives back \c false for every node.
698 705

	
699 706
       \pre Either \ref run() or \ref init() must be called before
700 707
       using this function.
701 708

	
702 709
       \sa barrierMap()
703 710
       \sa checkBarrier()
704 711
    */
705 712
    bool barrier(const Node& node) const
706 713
    {
707 714
      return (*_level)[node] >= _el;
708 715
    }
709 716

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

	
734 741
    /// @}
735 742

	
736 743
    /// \name Checker Functions
737 744
    /// The feasibility of the results can be checked using
738 745
    /// these functions.\n
739 746
    /// Either \ref run() or \ref start() should be called before
740 747
    /// using them.
741 748

	
742 749
    ///@{
743 750

	
744 751
    ///Check if the found flow is a feasible circulation
745 752

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

	
761 768
    ///Check whether or not the last execution provides a barrier
762 769

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

	
788 795
    /// @}
789 796

	
790 797
  };
791 798

	
792 799
}
793 800

	
794 801
#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 52
    ///Instantiates a \c PredMap.
53 53

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

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

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

	
69 69
    ///This function instantiates a \ref ProcessedMap.
70 70
    ///\param g is the digraph, to which
71 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 86
    ///Instantiates a \c ReachedMap.
87 87

	
88 88
    ///This function instantiates a \ref ReachedMap.
89 89
    ///\param g is the digraph, to which
90 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 101
    ///Instantiates a \c DistMap.
102 102

	
103 103
    ///This function instantiates a \ref DistMap.
104 104
    ///\param g is the digraph, to which we would like to define the
105 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 223
    ///\c PredMap type.
224 224
    ///
225 225
    ///\ref named-templ-param "Named parameter" for setting
226 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 243
    ///\c DistMap type.
244 244
    ///
245 245
    ///\ref named-templ-param "Named parameter" for setting
246 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 263
    ///\c ReachedMap type.
264 264
    ///
265 265
    ///\ref named-templ-param "Named parameter" for setting
266 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 283
    ///\c ProcessedMap type.
284 284
    ///
285 285
    ///\ref named-templ-param "Named parameter" for setting
286 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 301
    ///\c ProcessedMap type to be <tt>Digraph::NodeMap<bool></tt>.
302 302
    ///
303 303
    ///\ref named-templ-param "Named parameter" for setting
304 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
    ///If you need more control on the execution, first you have to call
415
    ///\ref init(), then you can add a source node with \ref addSource()
414
    ///If you need better control on the execution, you have to call
415
    ///\ref init() first, 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 1129
  template <typename GR>
1130 1130
  struct DfsVisitor {
1131 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 1167
  template <typename GR>
1168 1168
  struct DfsVisitor {
1169 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 1202
  template<class GR>
1203 1203
  struct DfsVisitDefaultTraits {
1204 1204

	
1205 1205
    /// \brief The type of the digraph the algorithm runs on.
1206 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 1227
  /// \brief DFS algorithm class with visitor interface.
1228 1228
  ///
1229 1229
  /// This class provides an efficient implementation of the DFS algorithm
1230 1230
  /// with visitor interface.
1231 1231
  ///
1232 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 1241
  /// \tparam GR The type of the digraph the algorithm runs on.
1242 1242
  /// The default type is \ref ListDigraph.
1243 1243
  /// The value of GR is not used directly by \ref DfsVisit,
1244 1244
  /// it is only passed to \ref DfsVisitDefaultTraits.
1245 1245
  /// \tparam VS The Visitor type that is used by the algorithm.
1246 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 1249
  /// \tparam TR Traits class to set various data types used by the
1250 1250
  /// algorithm. The default traits class is
1251 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 1255
  template <typename GR, typename VS, typename TR>
1256 1256
#else
1257 1257
  template <typename GR = ListDigraph,
1258 1258
            typename VS = DfsVisitor<GR>,
1259 1259
            typename TR = DfsVisitDefaultTraits<GR> >
1260 1260
#endif
1261 1261
  class DfsVisit {
1262 1262
  public:
1263 1263

	
1264 1264
    ///The traits class.
1265 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 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
    /// If you need more control on the execution, first you have to call
1373
    /// \ref init(), then you can add a source node with \ref addSource()
1372
    /// If you need better control on the execution, you have to call
1373
    /// \ref init() first, 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 V>
42 42
  struct DijkstraDefaultOperationTraits {
43 43
    /// \e
44 44
    typedef V Value;
45 45
    /// \brief Gives back the zero value of the type.
46 46
    static Value zero() {
47 47
      return static_cast<Value>(0);
48 48
    }
49 49
    /// \brief Gives back the sum of the given two elements.
50 50
    static Value plus(const Value& left, const Value& right) {
51 51
      return left + right;
52 52
    }
53 53
    /// \brief Gives back true only if the first value is less than the second.
54 54
    static bool less(const Value& left, const Value& right) {
55 55
      return left < right;
56 56
    }
57 57
  };
58 58

	
59 59
  ///Default traits class of Dijkstra class.
60 60

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

	
70 70
    ///The type of the map that stores the arc lengths.
71 71

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

	
78 78
    /// Operation traits for %Dijkstra algorithm.
79 79

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

	
84 84
    /// The cross reference type used by the heap.
85 85

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

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

	
99 99
    ///The heap type used by the %Dijkstra algorithm.
100 100

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

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

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

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

	
131 131
    ///The type of the map that indicates which nodes are processed.
132 132

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

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

	
151 151
    ///The type of the map that stores the distances of the nodes.
152 152

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

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

	
167 167
  ///%Dijkstra algorithm class.
168 168

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

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

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

	
225 225
    ///The \ref DijkstraDefaultTraits "traits class" of the algorithm.
226 226
    typedef TR Traits;
227 227

	
228 228
  private:
229 229

	
230 230
    typedef typename Digraph::Node Node;
231 231
    typedef typename Digraph::NodeIt NodeIt;
232 232
    typedef typename Digraph::Arc Arc;
233 233
    typedef typename Digraph::OutArcIt OutArcIt;
234 234

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

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

	
285 285
  public:
286 286

	
287 287
    typedef Dijkstra Create;
288 288

	
289 289
    ///\name Named Template Parameters
290 290

	
291 291
    ///@{
292 292

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

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

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

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

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

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

	
436 436
    template <class T>
437 437
    struct SetOperationTraitsTraits : public Traits {
438 438
      typedef T OperationTraits;
439 439
    };
440 440

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

	
453 453
    ///@}
454 454

	
455 455
  protected:
456 456

	
457 457
    Dijkstra() {}
458 458

	
459 459
  public:
460 460

	
461 461
    ///Constructor.
462 462

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

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

	
485 485
    ///Sets the length map.
486 486

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

	
495 495
    ///Sets the map that stores the predecessor arcs.
496 496

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

	
513 513
    ///Sets the map that indicates which nodes are processed.
514 514

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

	
531 531
    ///Sets the map that stores the distances of the nodes.
532 532

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

	
550 550
    ///Sets the heap and the cross reference used by algorithm.
551 551

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

	
574 574
  private:
575 575

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

	
582 582
  public:
583 583

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

	
592 592
    ///@{
593 593

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

	
608 608
    ///Adds a new source node.
609 609

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

	
626 626
    ///Processes the next node in the priority heap
627 627

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

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

	
663 663
    ///The next node to be processed.
664 664

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

	
672 672
    ///Returns \c false if there are nodes to be processed.
673 673

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

	
678 678
    ///Returns the number of the nodes to be processed.
679 679

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

	
684 684
    ///Executes the algorithm.
685 685

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

	
709 709
    ///Executes the algorithm until the given target node is processed.
710 710

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

	
731 731
    ///Executes the algorithm until a condition is met.
732 732

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

	
756 756
    ///Runs the algorithm from the given source node.
757 757

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

	
777 777
    ///Finds the shortest path between \c s and \c t.
778 778

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

	
799 799
    ///@}
800 800

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

	
807 807
    ///@{
808 808

	
809 809
    ///The shortest path to a node.
810 810

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

	
819 819
    ///The distance of a node from the root(s).
820 820

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

	
830 830
    ///Returns the 'previous arc' of the shortest path tree for a node.
831 831

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

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

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

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

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

	
879 879
    ///Checks if a node is reached from the root(s).
880 880

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

	
888 888
    ///Checks if a node is processed.
889 889

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

	
898 898
    ///The current distance of a node from the root(s).
899 899

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

	
910 910
    ///@}
911 911
  };
912 912

	
913 913

	
914 914
  ///Default traits class of dijkstra() function.
915 915

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

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

	
932 932
    /// Operation traits for Dijkstra algorithm.
933 933

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

	
938 938
    /// The cross reference type used by the heap.
939 939

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

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

	
953 953
    ///The heap type used by the Dijkstra algorithm.
954 954

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

	
962 962
    ///Instantiates a \ref Heap.
963 963

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

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

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

	
988 988
    ///The type of the map that indicates which nodes are processed.
989 989

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

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

	
1008 1008
    ///The type of the map that stores the distances of the nodes.
1009 1009

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

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

	
1023 1023
    ///The type of the shortest paths.
1024 1024

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

	
1030 1030
  /// Default traits class used by DijkstraWizard
1031 1031

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

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

	
1061 1061
  public:
1062 1062
    /// Constructor.
1063 1063

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

	
1069 1069
    /// Constructor.
1070 1070

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

	
1080 1080
  };
1081 1081

	
1082 1082
  /// Auxiliary class for the function-type interface of Dijkstra algorithm.
1083 1083

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

	
1096 1096
    ///The type of the digraph the algorithm runs on.
1097 1097
    typedef typename TR::Digraph Digraph;
1098 1098

	
1099 1099
    typedef typename Digraph::Node Node;
1100 1100
    typedef typename Digraph::NodeIt NodeIt;
1101 1101
    typedef typename Digraph::Arc Arc;
1102 1102
    typedef typename Digraph::OutArcIt OutArcIt;
1103 1103

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

	
1120 1120
  public:
1121 1121

	
1122 1122
    /// Constructor.
1123 1123
    DijkstraWizard() : TR() {}
1124 1124

	
1125 1125
    /// Constructor that requires parameters.
1126 1126

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

	
1134 1134
    ///Copy constructor
1135 1135
    DijkstraWizard(const TR &b) : TR(b) {}
1136 1136

	
1137 1137
    ~DijkstraWizard() {}
1138 1138

	
1139 1139
    ///Runs Dijkstra algorithm from the given source node.
1140 1140

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

	
1157 1157
    ///Finds the shortest path between \c s and \c t.
1158 1158

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

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

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

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

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

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

	
1265 1265
  };
1266 1266

	
1267 1267
  ///Function-type interface for Dijkstra algorithm.
1268 1268

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

	
1293 1293
} //END OF NAMESPACE LEMON
1294 1294

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

	
19 19
#ifndef LEMON_GOMORY_HU_TREE_H
20 20
#define LEMON_GOMORY_HU_TREE_H
21 21

	
22 22
#include <limits>
23 23

	
24 24
#include <lemon/core.h>
25 25
#include <lemon/preflow.h>
26 26
#include <lemon/concept_check.h>
27 27
#include <lemon/concepts/maps.h>
28 28

	
29 29
/// \ingroup min_cut
30 30
/// \file 
31 31
/// \brief Gomory-Hu cut tree in graphs.
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  /// \ingroup min_cut
36 36
  ///
37 37
  /// \brief Gomory-Hu cut tree algorithm
38 38
  ///
39 39
  /// The Gomory-Hu tree is a tree on the node set of a given graph, but it
40 40
  /// may contain edges which are not in the original graph. It has the
41 41
  /// property that the minimum capacity edge of the path between two nodes 
42 42
  /// in this tree has the same weight as the minimum cut in the graph
43 43
  /// between these nodes. Moreover the components obtained by removing
44 44
  /// this edge from the tree determine the corresponding minimum cut.
45 45
  /// Therefore once this tree is computed, the minimum cut between any pair
46 46
  /// of nodes can easily be obtained.
47 47
  /// 
48 48
  /// The algorithm calculates \e n-1 distinct minimum cuts (currently with
49 49
  /// the \ref Preflow algorithm), thus it has \f$O(n^3\sqrt{e})\f$ overall
50 50
  /// time complexity. It calculates a rooted Gomory-Hu tree.
51 51
  /// The structure of the tree and the edge weights can be
52 52
  /// obtained using \c predNode(), \c predValue() and \c rootDist().
53 53
  /// The functions \c minCutMap() and \c minCutValue() calculate
54 54
  /// the minimum cut and the minimum cut value between any two nodes
55 55
  /// in the graph. You can also list (iterate on) the nodes and the
56 56
  /// edges of the cuts using \c MinCutNodeIt and \c MinCutEdgeIt.
57 57
  ///
58 58
  /// \tparam GR The type of the undirected graph the algorithm runs on.
59 59
  /// \tparam CAP The type of the edge map containing the capacities.
60 60
  /// The default map type is \ref concepts::Graph::EdgeMap "GR::EdgeMap<int>".
61 61
#ifdef DOXYGEN
62 62
  template <typename GR,
63 63
	    typename CAP>
64 64
#else
65 65
  template <typename GR,
66 66
	    typename CAP = typename GR::template EdgeMap<int> >
67 67
#endif
68 68
  class GomoryHu {
69 69
  public:
70 70

	
71 71
    /// The graph type of the algorithm
72 72
    typedef GR Graph;
73 73
    /// The capacity map type of the algorithm
74 74
    typedef CAP Capacity;
75 75
    /// The value type of capacities
76 76
    typedef typename Capacity::Value Value;
77 77
    
78 78
  private:
79 79

	
80 80
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
81 81

	
82 82
    const Graph& _graph;
83 83
    const Capacity& _capacity;
84 84

	
85 85
    Node _root;
86 86
    typename Graph::template NodeMap<Node>* _pred;
87 87
    typename Graph::template NodeMap<Value>* _weight;
88 88
    typename Graph::template NodeMap<int>* _order;
89 89

	
90 90
    void createStructures() {
91 91
      if (!_pred) {
92 92
	_pred = new typename Graph::template NodeMap<Node>(_graph);
93 93
      }
94 94
      if (!_weight) {
95 95
	_weight = new typename Graph::template NodeMap<Value>(_graph);
96 96
      }
97 97
      if (!_order) {
98 98
	_order = new typename Graph::template NodeMap<int>(_graph);
99 99
      }
100 100
    }
101 101

	
102 102
    void destroyStructures() {
103 103
      if (_pred) {
104 104
	delete _pred;
105 105
      }
106 106
      if (_weight) {
107 107
	delete _weight;
108 108
      }
109 109
      if (_order) {
110 110
	delete _order;
111 111
      }
112 112
    }
113 113
  
114 114
  public:
115 115

	
116 116
    /// \brief Constructor
117 117
    ///
118 118
    /// Constructor.
119 119
    /// \param graph The undirected graph the algorithm runs on.
120 120
    /// \param capacity The edge capacity map.
121 121
    GomoryHu(const Graph& graph, const Capacity& capacity) 
122 122
      : _graph(graph), _capacity(capacity),
123 123
	_pred(0), _weight(0), _order(0) 
124 124
    {
125 125
      checkConcept<concepts::ReadMap<Edge, Value>, Capacity>();
126 126
    }
127 127

	
128 128

	
129 129
    /// \brief Destructor
130 130
    ///
131 131
    /// Destructor.
132 132
    ~GomoryHu() {
133 133
      destroyStructures();
134 134
    }
135 135

	
136 136
  private:
137 137
  
138 138
    // Initialize the internal data structures
139 139
    void init() {
140 140
      createStructures();
141 141

	
142 142
      _root = NodeIt(_graph);
143 143
      for (NodeIt n(_graph); n != INVALID; ++n) {
144 144
        (*_pred)[n] = _root;
145 145
        (*_order)[n] = -1;
146 146
      }
147 147
      (*_pred)[_root] = INVALID;
148 148
      (*_weight)[_root] = std::numeric_limits<Value>::max(); 
149 149
    }
150 150

	
151 151

	
152 152
    // Start the algorithm
153 153
    void start() {
154 154
      Preflow<Graph, Capacity> fa(_graph, _capacity, _root, INVALID);
155 155

	
156 156
      for (NodeIt n(_graph); n != INVALID; ++n) {
157 157
	if (n == _root) continue;
158 158

	
159 159
	Node pn = (*_pred)[n];
160 160
	fa.source(n);
161 161
	fa.target(pn);
162 162

	
163 163
	fa.runMinCut();
164 164

	
165 165
	(*_weight)[n] = fa.flowValue();
166 166

	
167 167
	for (NodeIt nn(_graph); nn != INVALID; ++nn) {
168 168
	  if (nn != n && fa.minCut(nn) && (*_pred)[nn] == pn) {
169 169
	    (*_pred)[nn] = n;
170 170
	  }
171 171
	}
172 172
	if ((*_pred)[pn] != INVALID && fa.minCut((*_pred)[pn])) {
173 173
	  (*_pred)[n] = (*_pred)[pn];
174 174
	  (*_pred)[pn] = n;
175 175
	  (*_weight)[n] = (*_weight)[pn];
176 176
	  (*_weight)[pn] = fa.flowValue();
177 177
	}
178 178
      }
179 179

	
180 180
      (*_order)[_root] = 0;
181 181
      int index = 1;
182 182

	
183 183
      for (NodeIt n(_graph); n != INVALID; ++n) {
184 184
	std::vector<Node> st;
185 185
	Node nn = n;
186 186
	while ((*_order)[nn] == -1) {
187 187
	  st.push_back(nn);
188 188
	  nn = (*_pred)[nn];
189 189
	}
190 190
	while (!st.empty()) {
191 191
	  (*_order)[st.back()] = index++;
192 192
	  st.pop_back();
193 193
	}
194 194
      }
195 195
    }
196 196

	
197 197
  public:
198 198

	
199 199
    ///\name Execution Control
200 200
 
201 201
    ///@{
202 202

	
203 203
    /// \brief Run the Gomory-Hu algorithm.
204 204
    ///
205 205
    /// This function runs the Gomory-Hu algorithm.
206 206
    void run() {
207 207
      init();
208 208
      start();
209 209
    }
210 210
    
211 211
    /// @}
212 212

	
213 213
    ///\name Query Functions
214 214
    ///The results of the algorithm can be obtained using these
215 215
    ///functions.\n
216 216
    ///\ref run() should be called before using them.\n
217 217
    ///See also \ref MinCutNodeIt and \ref MinCutEdgeIt.
218 218

	
219 219
    ///@{
220 220

	
221 221
    /// \brief Return the predecessor node in the Gomory-Hu tree.
222 222
    ///
223 223
    /// This function returns the predecessor node of the given node
224 224
    /// in the Gomory-Hu tree.
225 225
    /// If \c node is the root of the tree, then it returns \c INVALID.
226 226
    ///
227 227
    /// \pre \ref run() must be called before using this function.
228 228
    Node predNode(const Node& node) const {
229 229
      return (*_pred)[node];
230 230
    }
231 231

	
232 232
    /// \brief Return the weight of the predecessor edge in the
233 233
    /// Gomory-Hu tree.
234 234
    ///
235 235
    /// This function returns the weight of the predecessor edge of the 
236 236
    /// given node in the Gomory-Hu tree.
237 237
    /// If \c node is the root of the tree, the result is undefined.
238 238
    ///
239 239
    /// \pre \ref run() must be called before using this function.
240 240
    Value predValue(const Node& node) const {
241 241
      return (*_weight)[node];
242 242
    }
243 243

	
244 244
    /// \brief Return the distance from the root node in the Gomory-Hu tree.
245 245
    ///
246 246
    /// This function returns the distance of the given node from the root
247 247
    /// node in the Gomory-Hu tree.
248 248
    ///
249 249
    /// \pre \ref run() must be called before using this function.
250 250
    int rootDist(const Node& node) const {
251 251
      return (*_order)[node];
252 252
    }
253 253

	
254 254
    /// \brief Return the minimum cut value between two nodes
255 255
    ///
256 256
    /// This function returns the minimum cut value between the nodes
257 257
    /// \c s and \c t. 
258 258
    /// It finds the nearest common ancestor of the given nodes in the
259 259
    /// Gomory-Hu tree and calculates the minimum weight edge on the
260 260
    /// paths to the ancestor.
261 261
    ///
262 262
    /// \pre \ref run() must be called before using this function.
263 263
    Value minCutValue(const Node& s, const Node& t) const {
264 264
      Node sn = s, tn = t;
265 265
      Value value = std::numeric_limits<Value>::max();
266 266
      
267 267
      while (sn != tn) {
268 268
	if ((*_order)[sn] < (*_order)[tn]) {
269 269
	  if ((*_weight)[tn] <= value) value = (*_weight)[tn];
270 270
	  tn = (*_pred)[tn];
271 271
	} else {
272 272
	  if ((*_weight)[sn] <= value) value = (*_weight)[sn];
273 273
	  sn = (*_pred)[sn];
274 274
	}
275 275
      }
276 276
      return value;
277 277
    }
278 278

	
279 279
    /// \brief Return the minimum cut between two nodes
280 280
    ///
281 281
    /// This function returns the minimum cut between the nodes \c s and \c t
282 282
    /// in the \c cutMap parameter by setting the nodes in the component of
283 283
    /// \c s to \c true and the other nodes to \c false.
284 284
    ///
285 285
    /// For higher level interfaces see MinCutNodeIt and MinCutEdgeIt.
286 286
    ///
287 287
    /// \param s The base node.
288 288
    /// \param t The node you want to separate from node \c s.
289 289
    /// \param cutMap The cut will be returned in this map.
290 290
    /// It must be a \c bool (or convertible) \ref concepts::ReadWriteMap
291 291
    /// "ReadWriteMap" on the graph nodes.
292 292
    ///
293 293
    /// \return The value of the minimum cut between \c s and \c t.
294 294
    ///
295 295
    /// \pre \ref run() must be called before using this function.
296 296
    template <typename CutMap>
297 297
    Value minCutMap(const Node& s, ///< 
298 298
                    const Node& t,
299 299
                    ///< 
300 300
                    CutMap& cutMap
301 301
                    ///< 
302 302
                    ) const {
303 303
      Node sn = s, tn = t;
304 304
      bool s_root=false;
305 305
      Node rn = INVALID;
306 306
      Value value = std::numeric_limits<Value>::max();
307 307
      
308 308
      while (sn != tn) {
309 309
	if ((*_order)[sn] < (*_order)[tn]) {
310 310
	  if ((*_weight)[tn] <= value) {
311 311
	    rn = tn;
312 312
            s_root = false;
313 313
	    value = (*_weight)[tn];
314 314
	  }
315 315
	  tn = (*_pred)[tn];
316 316
	} else {
317 317
	  if ((*_weight)[sn] <= value) {
318 318
	    rn = sn;
319 319
            s_root = true;
320 320
	    value = (*_weight)[sn];
321 321
	  }
322 322
	  sn = (*_pred)[sn];
323 323
	}
324 324
      }
325 325

	
326 326
      typename Graph::template NodeMap<bool> reached(_graph, false);
327 327
      reached[_root] = true;
328 328
      cutMap.set(_root, !s_root);
329 329
      reached[rn] = true;
330 330
      cutMap.set(rn, s_root);
331 331

	
332 332
      std::vector<Node> st;
333 333
      for (NodeIt n(_graph); n != INVALID; ++n) {
334 334
	st.clear();
335 335
        Node nn = n;
336 336
	while (!reached[nn]) {
337 337
	  st.push_back(nn);
338 338
	  nn = (*_pred)[nn];
339 339
	}
340 340
	while (!st.empty()) {
341 341
	  cutMap.set(st.back(), cutMap[nn]);
342 342
	  st.pop_back();
343 343
	}
344 344
      }
345 345
      
346 346
      return value;
347 347
    }
348 348

	
349 349
    ///@}
350 350

	
351 351
    friend class MinCutNodeIt;
352 352

	
353 353
    /// Iterate on the nodes of a minimum cut
354 354
    
355 355
    /// This iterator class lists the nodes of a minimum cut found by
356 356
    /// GomoryHu. Before using it, you must allocate a GomoryHu class
357 357
    /// and call its \ref GomoryHu::run() "run()" method.
358 358
    ///
359 359
    /// This example counts the nodes in the minimum cut separating \c s from
360 360
    /// \c t.
361 361
    /// \code
362
    /// GomoruHu<Graph> gom(g, capacities);
362
    /// GomoryHu<Graph> gom(g, capacities);
363 363
    /// gom.run();
364 364
    /// int cnt=0;
365
    /// for(GomoruHu<Graph>::MinCutNodeIt n(gom,s,t); n!=INVALID; ++n) ++cnt;
365
    /// for(GomoryHu<Graph>::MinCutNodeIt n(gom,s,t); n!=INVALID; ++n) ++cnt;
366 366
    /// \endcode
367 367
    class MinCutNodeIt
368 368
    {
369 369
      bool _side;
370 370
      typename Graph::NodeIt _node_it;
371 371
      typename Graph::template NodeMap<bool> _cut;
372 372
    public:
373 373
      /// Constructor
374 374

	
375 375
      /// Constructor.
376 376
      ///
377 377
      MinCutNodeIt(GomoryHu const &gomory,
378 378
                   ///< The GomoryHu class. You must call its
379 379
                   ///  run() method
380 380
                   ///  before initializing this iterator.
381 381
                   const Node& s, ///< The base node.
382 382
                   const Node& t,
383 383
                   ///< The node you want to separate from node \c s.
384 384
                   bool side=true
385 385
                   ///< If it is \c true (default) then the iterator lists
386 386
                   ///  the nodes of the component containing \c s,
387 387
                   ///  otherwise it lists the other component.
388 388
                   /// \note As the minimum cut is not always unique,
389 389
                   /// \code
390 390
                   /// MinCutNodeIt(gomory, s, t, true);
391 391
                   /// \endcode
392 392
                   /// and
393 393
                   /// \code
394 394
                   /// MinCutNodeIt(gomory, t, s, false);
395 395
                   /// \endcode
396 396
                   /// does not necessarily give the same set of nodes.
397 397
                   /// However it is ensured that
398 398
                   /// \code
399 399
                   /// MinCutNodeIt(gomory, s, t, true);
400 400
                   /// \endcode
401 401
                   /// and
402 402
                   /// \code
403 403
                   /// MinCutNodeIt(gomory, s, t, false);
404 404
                   /// \endcode
405 405
                   /// together list each node exactly once.
406 406
                   )
407 407
        : _side(side), _cut(gomory._graph)
408 408
      {
409 409
        gomory.minCutMap(s,t,_cut);
410 410
        for(_node_it=typename Graph::NodeIt(gomory._graph);
411 411
            _node_it!=INVALID && _cut[_node_it]!=_side;
412 412
            ++_node_it) {}
413 413
      }
414 414
      /// Conversion to \c Node
415 415

	
416 416
      /// Conversion to \c Node.
417 417
      ///
418 418
      operator typename Graph::Node() const
419 419
      {
420 420
        return _node_it;
421 421
      }
422 422
      bool operator==(Invalid) { return _node_it==INVALID; }
423 423
      bool operator!=(Invalid) { return _node_it!=INVALID; }
424 424
      /// Next node
425 425

	
426 426
      /// Next node.
427 427
      ///
428 428
      MinCutNodeIt &operator++()
429 429
      {
430 430
        for(++_node_it;_node_it!=INVALID&&_cut[_node_it]!=_side;++_node_it) {}
431 431
        return *this;
432 432
      }
433 433
      /// Postfix incrementation
434 434

	
435 435
      /// Postfix incrementation.
436 436
      ///
437 437
      /// \warning This incrementation
438 438
      /// returns a \c Node, not a \c MinCutNodeIt, as one may
439 439
      /// expect.
440 440
      typename Graph::Node operator++(int)
441 441
      {
442 442
        typename Graph::Node n=*this;
443 443
        ++(*this);
444 444
        return n;
445 445
      }
446 446
    };
447 447
    
448 448
    friend class MinCutEdgeIt;
449 449
    
450 450
    /// Iterate on the edges of a minimum cut
451 451
    
452 452
    /// This iterator class lists the edges of a minimum cut found by
453 453
    /// GomoryHu. Before using it, you must allocate a GomoryHu class
454 454
    /// and call its \ref GomoryHu::run() "run()" method.
455 455
    ///
456 456
    /// This example computes the value of the minimum cut separating \c s from
457 457
    /// \c t.
458 458
    /// \code
459
    /// GomoruHu<Graph> gom(g, capacities);
459
    /// GomoryHu<Graph> gom(g, capacities);
460 460
    /// gom.run();
461 461
    /// int value=0;
462
    /// for(GomoruHu<Graph>::MinCutEdgeIt e(gom,s,t); e!=INVALID; ++e)
462
    /// for(GomoryHu<Graph>::MinCutEdgeIt e(gom,s,t); e!=INVALID; ++e)
463 463
    ///   value+=capacities[e];
464 464
    /// \endcode
465 465
    /// The result will be the same as the value returned by
466 466
    /// \ref GomoryHu::minCutValue() "gom.minCutValue(s,t)".
467 467
    class MinCutEdgeIt
468 468
    {
469 469
      bool _side;
470 470
      const Graph &_graph;
471 471
      typename Graph::NodeIt _node_it;
472 472
      typename Graph::OutArcIt _arc_it;
473 473
      typename Graph::template NodeMap<bool> _cut;
474 474
      void step()
475 475
      {
476 476
        ++_arc_it;
477 477
        while(_node_it!=INVALID && _arc_it==INVALID)
478 478
          {
479 479
            for(++_node_it;_node_it!=INVALID&&!_cut[_node_it];++_node_it) {}
480 480
            if(_node_it!=INVALID)
481 481
              _arc_it=typename Graph::OutArcIt(_graph,_node_it);
482 482
          }
483 483
      }
484 484
      
485 485
    public:
486 486
      /// Constructor
487 487

	
488 488
      /// Constructor.
489 489
      ///
490 490
      MinCutEdgeIt(GomoryHu const &gomory,
491 491
                   ///< The GomoryHu class. You must call its
492 492
                   ///  run() method
493 493
                   ///  before initializing this iterator.
494 494
                   const Node& s,  ///< The base node.
495 495
                   const Node& t,
496 496
                   ///< The node you want to separate from node \c s.
497 497
                   bool side=true
498 498
                   ///< If it is \c true (default) then the listed arcs
499 499
                   ///  will be oriented from the
500 500
                   ///  nodes of the component containing \c s,
501 501
                   ///  otherwise they will be oriented in the opposite
502 502
                   ///  direction.
503 503
                   )
504 504
        : _graph(gomory._graph), _cut(_graph)
505 505
      {
506 506
        gomory.minCutMap(s,t,_cut);
507 507
        if(!side)
508 508
          for(typename Graph::NodeIt n(_graph);n!=INVALID;++n)
509 509
            _cut[n]=!_cut[n];
510 510

	
511 511
        for(_node_it=typename Graph::NodeIt(_graph);
512 512
            _node_it!=INVALID && !_cut[_node_it];
513 513
            ++_node_it) {}
514 514
        _arc_it = _node_it!=INVALID ?
515 515
          typename Graph::OutArcIt(_graph,_node_it) : INVALID;
516 516
        while(_node_it!=INVALID && _arc_it == INVALID)
517 517
          {
518 518
            for(++_node_it; _node_it!=INVALID&&!_cut[_node_it]; ++_node_it) {}
519 519
            if(_node_it!=INVALID)
520 520
              _arc_it= typename Graph::OutArcIt(_graph,_node_it);
521 521
          }
522 522
        while(_arc_it!=INVALID && _cut[_graph.target(_arc_it)]) step();
523 523
      }
524 524
      /// Conversion to \c Arc
525 525

	
526 526
      /// Conversion to \c Arc.
527 527
      ///
528 528
      operator typename Graph::Arc() const
529 529
      {
530 530
        return _arc_it;
531 531
      }
532 532
      /// Conversion to \c Edge
533 533

	
534 534
      /// Conversion to \c Edge.
535 535
      ///
536 536
      operator typename Graph::Edge() const
537 537
      {
538 538
        return _arc_it;
539 539
      }
540 540
      bool operator==(Invalid) { return _node_it==INVALID; }
541 541
      bool operator!=(Invalid) { return _node_it!=INVALID; }
542 542
      /// Next edge
543 543

	
544 544
      /// Next edge.
545 545
      ///
546 546
      MinCutEdgeIt &operator++()
547 547
      {
548 548
        step();
549 549
        while(_arc_it!=INVALID && _cut[_graph.target(_arc_it)]) step();
550 550
        return *this;
551 551
      }
552 552
      /// Postfix incrementation
553 553
      
554 554
      /// Postfix incrementation.
555 555
      ///
556 556
      /// \warning This incrementation
557 557
      /// returns an \c Arc, not a \c MinCutEdgeIt, as one may expect.
558 558
      typename Graph::Arc operator++(int)
559 559
      {
560 560
        typename Graph::Arc e=*this;
561 561
        ++(*this);
562 562
        return e;
563 563
      }
564 564
    };
565 565

	
566 566
  };
567 567

	
568 568
}
569 569

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

	
19 19
#ifndef LEMON_MIN_COST_ARBORESCENCE_H
20 20
#define LEMON_MIN_COST_ARBORESCENCE_H
21 21

	
22 22
///\ingroup spantree
23 23
///\file
24 24
///\brief Minimum Cost Arborescence algorithm.
25 25

	
26 26
#include <vector>
27 27

	
28 28
#include <lemon/list_graph.h>
29 29
#include <lemon/bin_heap.h>
30 30
#include <lemon/assert.h>
31 31

	
32 32
namespace lemon {
33 33

	
34 34

	
35 35
  /// \brief Default traits class for MinCostArborescence class.
36 36
  ///
37 37
  /// Default traits class for MinCostArborescence class.
38 38
  /// \param GR Digraph type.
39 39
  /// \param CM Type of the cost map.
40 40
  template <class GR, class CM>
41 41
  struct MinCostArborescenceDefaultTraits{
42 42

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

	
46 46
    /// \brief The type of the map that stores the arc costs.
47 47
    ///
48 48
    /// The type of the map that stores the arc costs.
49 49
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
50 50
    typedef CM CostMap;
51 51

	
52 52
    /// \brief The value type of the costs.
53 53
    ///
54 54
    /// The value type of the costs.
55 55
    typedef typename CostMap::Value Value;
56 56

	
57 57
    /// \brief The type of the map that stores which arcs are in the
58 58
    /// arborescence.
59 59
    ///
60 60
    /// The type of the map that stores which arcs are in the
61 61
    /// arborescence.  It must conform to the \ref concepts::WriteMap
62 62
    /// "WriteMap" concept, and its value type must be \c bool
63 63
    /// (or convertible). Initially it will be set to \c false on each
64 64
    /// arc, then it will be set on each arborescence arc once.
65 65
    typedef typename Digraph::template ArcMap<bool> ArborescenceMap;
66 66

	
67 67
    /// \brief Instantiates a \c ArborescenceMap.
68 68
    ///
69 69
    /// This function instantiates a \c ArborescenceMap.
70 70
    /// \param digraph The digraph to which we would like to calculate
71 71
    /// the \c ArborescenceMap.
72 72
    static ArborescenceMap *createArborescenceMap(const Digraph &digraph){
73 73
      return new ArborescenceMap(digraph);
74 74
    }
75 75

	
76 76
    /// \brief The type of the \c PredMap
77 77
    ///
78 78
    /// The type of the \c PredMap. It must confrom to the
79 79
    /// \ref concepts::WriteMap "WriteMap" concept, and its value type
80 80
    /// must be the \c Arc type of the digraph.
81 81
    typedef typename Digraph::template NodeMap<typename Digraph::Arc> PredMap;
82 82

	
83 83
    /// \brief Instantiates a \c PredMap.
84 84
    ///
85 85
    /// This function instantiates a \c PredMap.
86 86
    /// \param digraph The digraph to which we would like to define the
87 87
    /// \c PredMap.
88 88
    static PredMap *createPredMap(const Digraph &digraph){
89 89
      return new PredMap(digraph);
90 90
    }
91 91

	
92 92
  };
93 93

	
94 94
  /// \ingroup spantree
95 95
  ///
96 96
  /// \brief Minimum Cost Arborescence algorithm class.
97 97
  ///
98 98
  /// This class provides an efficient implementation of the
99 99
  /// Minimum Cost Arborescence algorithm. The arborescence is a tree
100 100
  /// which is directed from a given source node of the digraph. One or
101 101
  /// more sources should be given to the algorithm and it will calculate
102 102
  /// the minimum cost subgraph that is the union of arborescences with the
103 103
  /// given sources and spans all the nodes which are reachable from the
104 104
  /// sources. The time complexity of the algorithm is O(n<sup>2</sup>+e).
105 105
  ///
106 106
  /// The algorithm also provides an optimal dual solution, therefore
107 107
  /// the optimality of the solution can be checked.
108 108
  ///
109 109
  /// \param GR The digraph type the algorithm runs on.
110 110
  /// \param CM A read-only arc map storing the costs of the
111 111
  /// arcs. It is read once for each arc, so the map may involve in
112 112
  /// relatively time consuming process to compute the arc costs if
113 113
  /// it is necessary. The default map type is \ref
114 114
  /// concepts::Digraph::ArcMap "Digraph::ArcMap<int>".
115 115
  /// \param TR Traits class to set various data types used
116 116
  /// by the algorithm. The default traits class is
117 117
  /// \ref MinCostArborescenceDefaultTraits
118 118
  /// "MinCostArborescenceDefaultTraits<GR, CM>".
119 119
#ifndef DOXYGEN
120 120
  template <typename GR,
121 121
            typename CM = typename GR::template ArcMap<int>,
122 122
            typename TR =
123 123
              MinCostArborescenceDefaultTraits<GR, CM> >
124 124
#else
125 125
  template <typename GR, typename CM, typedef TR>
126 126
#endif
127 127
  class MinCostArborescence {
128 128
  public:
129 129

	
130 130
    /// \brief The \ref MinCostArborescenceDefaultTraits "traits class" 
131 131
    /// of the algorithm. 
132 132
    typedef TR Traits;
133 133
    /// The type of the underlying digraph.
134 134
    typedef typename Traits::Digraph Digraph;
135 135
    /// The type of the map that stores the arc costs.
136 136
    typedef typename Traits::CostMap CostMap;
137 137
    ///The type of the costs of the arcs.
138 138
    typedef typename Traits::Value Value;
139 139
    ///The type of the predecessor map.
140 140
    typedef typename Traits::PredMap PredMap;
141 141
    ///The type of the map that stores which arcs are in the arborescence.
142 142
    typedef typename Traits::ArborescenceMap ArborescenceMap;
143 143

	
144 144
    typedef MinCostArborescence Create;
145 145

	
146 146
  private:
147 147

	
148 148
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
149 149

	
150 150
    struct CostArc {
151 151

	
152 152
      Arc arc;
153 153
      Value value;
154 154

	
155 155
      CostArc() {}
156 156
      CostArc(Arc _arc, Value _value) : arc(_arc), value(_value) {}
157 157

	
158 158
    };
159 159

	
160 160
    const Digraph *_digraph;
161 161
    const CostMap *_cost;
162 162

	
163 163
    PredMap *_pred;
164 164
    bool local_pred;
165 165

	
166 166
    ArborescenceMap *_arborescence;
167 167
    bool local_arborescence;
168 168

	
169 169
    typedef typename Digraph::template ArcMap<int> ArcOrder;
170 170
    ArcOrder *_arc_order;
171 171

	
172 172
    typedef typename Digraph::template NodeMap<int> NodeOrder;
173 173
    NodeOrder *_node_order;
174 174

	
175 175
    typedef typename Digraph::template NodeMap<CostArc> CostArcMap;
176 176
    CostArcMap *_cost_arcs;
177 177

	
178 178
    struct StackLevel {
179 179

	
180 180
      std::vector<CostArc> arcs;
181 181
      int node_level;
182 182

	
183 183
    };
184 184

	
185 185
    std::vector<StackLevel> level_stack;
186 186
    std::vector<Node> queue;
187 187

	
188 188
    typedef std::vector<typename Digraph::Node> DualNodeList;
189 189

	
190 190
    DualNodeList _dual_node_list;
191 191

	
192 192
    struct DualVariable {
193 193
      int begin, end;
194 194
      Value value;
195 195

	
196 196
      DualVariable(int _begin, int _end, Value _value)
197 197
        : begin(_begin), end(_end), value(_value) {}
198 198

	
199 199
    };
200 200

	
201 201
    typedef std::vector<DualVariable> DualVariables;
202 202

	
203 203
    DualVariables _dual_variables;
204 204

	
205 205
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
206 206

	
207 207
    HeapCrossRef *_heap_cross_ref;
208 208

	
209 209
    typedef BinHeap<int, HeapCrossRef> Heap;
210 210

	
211 211
    Heap *_heap;
212 212

	
213 213
  protected:
214 214

	
215 215
    MinCostArborescence() {}
216 216

	
217 217
  private:
218 218

	
219 219
    void createStructures() {
220 220
      if (!_pred) {
221 221
        local_pred = true;
222 222
        _pred = Traits::createPredMap(*_digraph);
223 223
      }
224 224
      if (!_arborescence) {
225 225
        local_arborescence = true;
226 226
        _arborescence = Traits::createArborescenceMap(*_digraph);
227 227
      }
228 228
      if (!_arc_order) {
229 229
        _arc_order = new ArcOrder(*_digraph);
230 230
      }
231 231
      if (!_node_order) {
232 232
        _node_order = new NodeOrder(*_digraph);
233 233
      }
234 234
      if (!_cost_arcs) {
235 235
        _cost_arcs = new CostArcMap(*_digraph);
236 236
      }
237 237
      if (!_heap_cross_ref) {
238 238
        _heap_cross_ref = new HeapCrossRef(*_digraph, -1);
239 239
      }
240 240
      if (!_heap) {
241 241
        _heap = new Heap(*_heap_cross_ref);
242 242
      }
243 243
    }
244 244

	
245 245
    void destroyStructures() {
246 246
      if (local_arborescence) {
247 247
        delete _arborescence;
248 248
      }
249 249
      if (local_pred) {
250 250
        delete _pred;
251 251
      }
252 252
      if (_arc_order) {
253 253
        delete _arc_order;
254 254
      }
255 255
      if (_node_order) {
256 256
        delete _node_order;
257 257
      }
258 258
      if (_cost_arcs) {
259 259
        delete _cost_arcs;
260 260
      }
261 261
      if (_heap) {
262 262
        delete _heap;
263 263
      }
264 264
      if (_heap_cross_ref) {
265 265
        delete _heap_cross_ref;
266 266
      }
267 267
    }
268 268

	
269 269
    Arc prepare(Node node) {
270 270
      std::vector<Node> nodes;
271 271
      (*_node_order)[node] = _dual_node_list.size();
272 272
      StackLevel level;
273 273
      level.node_level = _dual_node_list.size();
274 274
      _dual_node_list.push_back(node);
275 275
      for (InArcIt it(*_digraph, node); it != INVALID; ++it) {
276 276
        Arc arc = it;
277 277
        Node source = _digraph->source(arc);
278 278
        Value value = (*_cost)[it];
279 279
        if (source == node || (*_node_order)[source] == -3) continue;
280 280
        if ((*_cost_arcs)[source].arc == INVALID) {
281 281
          (*_cost_arcs)[source].arc = arc;
282 282
          (*_cost_arcs)[source].value = value;
283 283
          nodes.push_back(source);
284 284
        } else {
285 285
          if ((*_cost_arcs)[source].value > value) {
286 286
            (*_cost_arcs)[source].arc = arc;
287 287
            (*_cost_arcs)[source].value = value;
288 288
          }
289 289
        }
290 290
      }
291 291
      CostArc minimum = (*_cost_arcs)[nodes[0]];
292 292
      for (int i = 1; i < int(nodes.size()); ++i) {
293 293
        if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
294 294
          minimum = (*_cost_arcs)[nodes[i]];
295 295
        }
296 296
      }
297 297
      (*_arc_order)[minimum.arc] = _dual_variables.size();
298 298
      DualVariable var(_dual_node_list.size() - 1,
299 299
                       _dual_node_list.size(), minimum.value);
300 300
      _dual_variables.push_back(var);
301 301
      for (int i = 0; i < int(nodes.size()); ++i) {
302 302
        (*_cost_arcs)[nodes[i]].value -= minimum.value;
303 303
        level.arcs.push_back((*_cost_arcs)[nodes[i]]);
304 304
        (*_cost_arcs)[nodes[i]].arc = INVALID;
305 305
      }
306 306
      level_stack.push_back(level);
307 307
      return minimum.arc;
308 308
    }
309 309

	
310 310
    Arc contract(Node node) {
311 311
      int node_bottom = bottom(node);
312 312
      std::vector<Node> nodes;
313 313
      while (!level_stack.empty() &&
314 314
             level_stack.back().node_level >= node_bottom) {
315 315
        for (int i = 0; i < int(level_stack.back().arcs.size()); ++i) {
316 316
          Arc arc = level_stack.back().arcs[i].arc;
317 317
          Node source = _digraph->source(arc);
318 318
          Value value = level_stack.back().arcs[i].value;
319 319
          if ((*_node_order)[source] >= node_bottom) continue;
320 320
          if ((*_cost_arcs)[source].arc == INVALID) {
321 321
            (*_cost_arcs)[source].arc = arc;
322 322
            (*_cost_arcs)[source].value = value;
323 323
            nodes.push_back(source);
324 324
          } else {
325 325
            if ((*_cost_arcs)[source].value > value) {
326 326
              (*_cost_arcs)[source].arc = arc;
327 327
              (*_cost_arcs)[source].value = value;
328 328
            }
329 329
          }
330 330
        }
331 331
        level_stack.pop_back();
332 332
      }
333 333
      CostArc minimum = (*_cost_arcs)[nodes[0]];
334 334
      for (int i = 1; i < int(nodes.size()); ++i) {
335 335
        if ((*_cost_arcs)[nodes[i]].value < minimum.value) {
336 336
          minimum = (*_cost_arcs)[nodes[i]];
337 337
        }
338 338
      }
339 339
      (*_arc_order)[minimum.arc] = _dual_variables.size();
340 340
      DualVariable var(node_bottom, _dual_node_list.size(), minimum.value);
341 341
      _dual_variables.push_back(var);
342 342
      StackLevel level;
343 343
      level.node_level = node_bottom;
344 344
      for (int i = 0; i < int(nodes.size()); ++i) {
345 345
        (*_cost_arcs)[nodes[i]].value -= minimum.value;
346 346
        level.arcs.push_back((*_cost_arcs)[nodes[i]]);
347 347
        (*_cost_arcs)[nodes[i]].arc = INVALID;
348 348
      }
349 349
      level_stack.push_back(level);
350 350
      return minimum.arc;
351 351
    }
352 352

	
353 353
    int bottom(Node node) {
354 354
      int k = level_stack.size() - 1;
355 355
      while (level_stack[k].node_level > (*_node_order)[node]) {
356 356
        --k;
357 357
      }
358 358
      return level_stack[k].node_level;
359 359
    }
360 360

	
361 361
    void finalize(Arc arc) {
362 362
      Node node = _digraph->target(arc);
363 363
      _heap->push(node, (*_arc_order)[arc]);
364 364
      _pred->set(node, arc);
365 365
      while (!_heap->empty()) {
366 366
        Node source = _heap->top();
367 367
        _heap->pop();
368 368
        (*_node_order)[source] = -1;
369 369
        for (OutArcIt it(*_digraph, source); it != INVALID; ++it) {
370 370
          if ((*_arc_order)[it] < 0) continue;
371 371
          Node target = _digraph->target(it);
372 372
          switch(_heap->state(target)) {
373 373
          case Heap::PRE_HEAP:
374 374
            _heap->push(target, (*_arc_order)[it]);
375 375
            _pred->set(target, it);
376 376
            break;
377 377
          case Heap::IN_HEAP:
378 378
            if ((*_arc_order)[it] < (*_heap)[target]) {
379 379
              _heap->decrease(target, (*_arc_order)[it]);
380 380
              _pred->set(target, it);
381 381
            }
382 382
            break;
383 383
          case Heap::POST_HEAP:
384 384
            break;
385 385
          }
386 386
        }
387 387
        _arborescence->set((*_pred)[source], true);
388 388
      }
389 389
    }
390 390

	
391 391

	
392 392
  public:
393 393

	
394 394
    /// \name Named Template Parameters
395 395

	
396 396
    /// @{
397 397

	
398 398
    template <class T>
399 399
    struct SetArborescenceMapTraits : public Traits {
400 400
      typedef T ArborescenceMap;
401 401
      static ArborescenceMap *createArborescenceMap(const Digraph &)
402 402
      {
403 403
        LEMON_ASSERT(false, "ArborescenceMap is not initialized");
404 404
        return 0; // ignore warnings
405 405
      }
406 406
    };
407 407

	
408 408
    /// \brief \ref named-templ-param "Named parameter" for
409 409
    /// setting \c ArborescenceMap type
410 410
    ///
411 411
    /// \ref named-templ-param "Named parameter" for setting
412 412
    /// \c ArborescenceMap type.
413 413
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept,
414 414
    /// and its value type must be \c bool (or convertible).
415 415
    /// Initially it will be set to \c false on each arc,
416 416
    /// then it will be set on each arborescence arc once.
417 417
    template <class T>
418 418
    struct SetArborescenceMap
419 419
      : public MinCostArborescence<Digraph, CostMap,
420 420
                                   SetArborescenceMapTraits<T> > {
421 421
    };
422 422

	
423 423
    template <class T>
424 424
    struct SetPredMapTraits : public Traits {
425 425
      typedef T PredMap;
426 426
      static PredMap *createPredMap(const Digraph &)
427 427
      {
428 428
        LEMON_ASSERT(false, "PredMap is not initialized");
429 429
        return 0; // ignore warnings
430 430
      }
431 431
    };
432 432

	
433 433
    /// \brief \ref named-templ-param "Named parameter" for
434 434
    /// setting \c PredMap type
435 435
    ///
436 436
    /// \ref named-templ-param "Named parameter" for setting
437 437
    /// \c PredMap type.
438 438
    /// It must meet the \ref concepts::WriteMap "WriteMap" concept, 
439 439
    /// and its value type must be the \c Arc type of the digraph.
440 440
    template <class T>
441 441
    struct SetPredMap
442 442
      : public MinCostArborescence<Digraph, CostMap, SetPredMapTraits<T> > {
443 443
    };
444 444

	
445 445
    /// @}
446 446

	
447 447
    /// \brief Constructor.
448 448
    ///
449 449
    /// \param digraph The digraph the algorithm will run on.
450 450
    /// \param cost The cost map used by the algorithm.
451 451
    MinCostArborescence(const Digraph& digraph, const CostMap& cost)
452 452
      : _digraph(&digraph), _cost(&cost), _pred(0), local_pred(false),
453 453
        _arborescence(0), local_arborescence(false),
454 454
        _arc_order(0), _node_order(0), _cost_arcs(0),
455 455
        _heap_cross_ref(0), _heap(0) {}
456 456

	
457 457
    /// \brief Destructor.
458 458
    ~MinCostArborescence() {
459 459
      destroyStructures();
460 460
    }
461 461

	
462 462
    /// \brief Sets the arborescence map.
463 463
    ///
464 464
    /// Sets the arborescence map.
465 465
    /// \return <tt>(*this)</tt>
466 466
    MinCostArborescence& arborescenceMap(ArborescenceMap& m) {
467 467
      if (local_arborescence) {
468 468
        delete _arborescence;
469 469
      }
470 470
      local_arborescence = false;
471 471
      _arborescence = &m;
472 472
      return *this;
473 473
    }
474 474

	
475 475
    /// \brief Sets the predecessor map.
476 476
    ///
477 477
    /// Sets the predecessor map.
478 478
    /// \return <tt>(*this)</tt>
479 479
    MinCostArborescence& predMap(PredMap& m) {
480 480
      if (local_pred) {
481 481
        delete _pred;
482 482
      }
483 483
      local_pred = false;
484 484
      _pred = &m;
485 485
      return *this;
486 486
    }
487 487

	
488 488
    /// \name Execution Control
489 489
    /// The simplest way to execute the algorithm is to use
490 490
    /// one of the member functions called \c run(...). \n
491
    /// If you need more control on the execution,
492
    /// first you must call \ref init(), then you can add several
491
    /// If you need better control on the execution,
492
    /// you have to call \ref init() first, then you can add several
493 493
    /// source nodes with \ref addSource().
494 494
    /// Finally \ref start() will perform the arborescence
495 495
    /// computation.
496 496

	
497 497
    ///@{
498 498

	
499 499
    /// \brief Initializes the internal data structures.
500 500
    ///
501 501
    /// Initializes the internal data structures.
502 502
    ///
503 503
    void init() {
504 504
      createStructures();
505 505
      _heap->clear();
506 506
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
507 507
        (*_cost_arcs)[it].arc = INVALID;
508 508
        (*_node_order)[it] = -3;
509 509
        (*_heap_cross_ref)[it] = Heap::PRE_HEAP;
510 510
        _pred->set(it, INVALID);
511 511
      }
512 512
      for (ArcIt it(*_digraph); it != INVALID; ++it) {
513 513
        _arborescence->set(it, false);
514 514
        (*_arc_order)[it] = -1;
515 515
      }
516 516
      _dual_node_list.clear();
517 517
      _dual_variables.clear();
518 518
    }
519 519

	
520 520
    /// \brief Adds a new source node.
521 521
    ///
522 522
    /// Adds a new source node to the algorithm.
523 523
    void addSource(Node source) {
524 524
      std::vector<Node> nodes;
525 525
      nodes.push_back(source);
526 526
      while (!nodes.empty()) {
527 527
        Node node = nodes.back();
528 528
        nodes.pop_back();
529 529
        for (OutArcIt it(*_digraph, node); it != INVALID; ++it) {
530 530
          Node target = _digraph->target(it);
531 531
          if ((*_node_order)[target] == -3) {
532 532
            (*_node_order)[target] = -2;
533 533
            nodes.push_back(target);
534 534
            queue.push_back(target);
535 535
          }
536 536
        }
537 537
      }
538 538
      (*_node_order)[source] = -1;
539 539
    }
540 540

	
541 541
    /// \brief Processes the next node in the priority queue.
542 542
    ///
543 543
    /// Processes the next node in the priority queue.
544 544
    ///
545 545
    /// \return The processed node.
546 546
    ///
547 547
    /// \warning The queue must not be empty.
548 548
    Node processNextNode() {
549 549
      Node node = queue.back();
550 550
      queue.pop_back();
551 551
      if ((*_node_order)[node] == -2) {
552 552
        Arc arc = prepare(node);
553 553
        Node source = _digraph->source(arc);
554 554
        while ((*_node_order)[source] != -1) {
555 555
          if ((*_node_order)[source] >= 0) {
556 556
            arc = contract(source);
557 557
          } else {
558 558
            arc = prepare(source);
559 559
          }
560 560
          source = _digraph->source(arc);
561 561
        }
562 562
        finalize(arc);
563 563
        level_stack.clear();
564 564
      }
565 565
      return node;
566 566
    }
567 567

	
568 568
    /// \brief Returns the number of the nodes to be processed.
569 569
    ///
570 570
    /// Returns the number of the nodes to be processed in the priority
571 571
    /// queue.
572 572
    int queueSize() const {
573 573
      return queue.size();
574 574
    }
575 575

	
576 576
    /// \brief Returns \c false if there are nodes to be processed.
577 577
    ///
578 578
    /// Returns \c false if there are nodes to be processed.
579 579
    bool emptyQueue() const {
580 580
      return queue.empty();
581 581
    }
582 582

	
583 583
    /// \brief Executes the algorithm.
584 584
    ///
585 585
    /// Executes the algorithm.
586 586
    ///
587 587
    /// \pre init() must be called and at least one node should be added
588 588
    /// with addSource() before using this function.
589 589
    ///
590 590
    ///\note mca.start() is just a shortcut of the following code.
591 591
    ///\code
592 592
    ///while (!mca.emptyQueue()) {
593 593
    ///  mca.processNextNode();
594 594
    ///}
595 595
    ///\endcode
596 596
    void start() {
597 597
      while (!emptyQueue()) {
598 598
        processNextNode();
599 599
      }
600 600
    }
601 601

	
602 602
    /// \brief Runs %MinCostArborescence algorithm from node \c s.
603 603
    ///
604 604
    /// This method runs the %MinCostArborescence algorithm from
605 605
    /// a root node \c s.
606 606
    ///
607 607
    /// \note mca.run(s) is just a shortcut of the following code.
608 608
    /// \code
609 609
    /// mca.init();
610 610
    /// mca.addSource(s);
611 611
    /// mca.start();
612 612
    /// \endcode
613 613
    void run(Node s) {
614 614
      init();
615 615
      addSource(s);
616 616
      start();
617 617
    }
618 618

	
619 619
    ///@}
620 620

	
621 621
    /// \name Query Functions
622 622
    /// The result of the %MinCostArborescence algorithm can be obtained
623 623
    /// using these functions.\n
624 624
    /// Either run() or start() must be called before using them.
625 625

	
626 626
    /// @{
627 627

	
628 628
    /// \brief Returns the cost of the arborescence.
629 629
    ///
630 630
    /// Returns the cost of the arborescence.
631 631
    Value arborescenceCost() const {
632 632
      Value sum = 0;
633 633
      for (ArcIt it(*_digraph); it != INVALID; ++it) {
634 634
        if (arborescence(it)) {
635 635
          sum += (*_cost)[it];
636 636
        }
637 637
      }
638 638
      return sum;
639 639
    }
640 640

	
641 641
    /// \brief Returns \c true if the arc is in the arborescence.
642 642
    ///
643 643
    /// Returns \c true if the given arc is in the arborescence.
644 644
    /// \param arc An arc of the digraph.
645 645
    /// \pre \ref run() must be called before using this function.
646 646
    bool arborescence(Arc arc) const {
647 647
      return (*_pred)[_digraph->target(arc)] == arc;
648 648
    }
649 649

	
650 650
    /// \brief Returns a const reference to the arborescence map.
651 651
    ///
652 652
    /// Returns a const reference to the arborescence map.
653 653
    /// \pre \ref run() must be called before using this function.
654 654
    const ArborescenceMap& arborescenceMap() const {
655 655
      return *_arborescence;
656 656
    }
657 657

	
658 658
    /// \brief Returns the predecessor arc of the given node.
659 659
    ///
660 660
    /// Returns the predecessor arc of the given node.
661 661
    /// \pre \ref run() must be called before using this function.
662 662
    Arc pred(Node node) const {
663 663
      return (*_pred)[node];
664 664
    }
665 665

	
666 666
    /// \brief Returns a const reference to the pred map.
667 667
    ///
668 668
    /// Returns a const reference to the pred map.
669 669
    /// \pre \ref run() must be called before using this function.
670 670
    const PredMap& predMap() const {
671 671
      return *_pred;
672 672
    }
673 673

	
674 674
    /// \brief Indicates that a node is reachable from the sources.
675 675
    ///
676 676
    /// Indicates that a node is reachable from the sources.
677 677
    bool reached(Node node) const {
678 678
      return (*_node_order)[node] != -3;
679 679
    }
680 680

	
681 681
    /// \brief Indicates that a node is processed.
682 682
    ///
683 683
    /// Indicates that a node is processed. The arborescence path exists
684 684
    /// from the source to the given node.
685 685
    bool processed(Node node) const {
686 686
      return (*_node_order)[node] == -1;
687 687
    }
688 688

	
689 689
    /// \brief Returns the number of the dual variables in basis.
690 690
    ///
691 691
    /// Returns the number of the dual variables in basis.
692 692
    int dualNum() const {
693 693
      return _dual_variables.size();
694 694
    }
695 695

	
696 696
    /// \brief Returns the value of the dual solution.
697 697
    ///
698 698
    /// Returns the value of the dual solution. It should be
699 699
    /// equal to the arborescence value.
700 700
    Value dualValue() const {
701 701
      Value sum = 0;
702 702
      for (int i = 0; i < int(_dual_variables.size()); ++i) {
703 703
        sum += _dual_variables[i].value;
704 704
      }
705 705
      return sum;
706 706
    }
707 707

	
708 708
    /// \brief Returns the number of the nodes in the dual variable.
709 709
    ///
710 710
    /// Returns the number of the nodes in the dual variable.
711 711
    int dualSize(int k) const {
712 712
      return _dual_variables[k].end - _dual_variables[k].begin;
713 713
    }
714 714

	
715 715
    /// \brief Returns the value of the dual variable.
716 716
    ///
717 717
    /// Returns the the value of the dual variable.
718 718
    Value dualValue(int k) const {
719 719
      return _dual_variables[k].value;
720 720
    }
721 721

	
722 722
    /// \brief LEMON iterator for getting a dual variable.
723 723
    ///
724 724
    /// This class provides a common style LEMON iterator for getting a
725 725
    /// dual variable of \ref MinCostArborescence algorithm.
726 726
    /// It iterates over a subset of the nodes.
727 727
    class DualIt {
728 728
    public:
729 729

	
730 730
      /// \brief Constructor.
731 731
      ///
732 732
      /// Constructor for getting the nodeset of the dual variable
733 733
      /// of \ref MinCostArborescence algorithm.
734 734
      DualIt(const MinCostArborescence& algorithm, int variable)
735 735
        : _algorithm(&algorithm)
736 736
      {
737 737
        _index = _algorithm->_dual_variables[variable].begin;
738 738
        _last = _algorithm->_dual_variables[variable].end;
739 739
      }
740 740

	
741 741
      /// \brief Conversion to \c Node.
742 742
      ///
743 743
      /// Conversion to \c Node.
744 744
      operator Node() const {
745 745
        return _algorithm->_dual_node_list[_index];
746 746
      }
747 747

	
748 748
      /// \brief Increment operator.
749 749
      ///
750 750
      /// Increment operator.
751 751
      DualIt& operator++() {
752 752
        ++_index;
753 753
        return *this;
754 754
      }
755 755

	
756 756
      /// \brief Validity checking
757 757
      ///
758 758
      /// Checks whether the iterator is invalid.
759 759
      bool operator==(Invalid) const {
760 760
        return _index == _last;
761 761
      }
762 762

	
763 763
      /// \brief Validity checking
764 764
      ///
765 765
      /// Checks whether the iterator is valid.
766 766
      bool operator!=(Invalid) const {
767 767
        return _index != _last;
768 768
      }
769 769

	
770 770
    private:
771 771
      const MinCostArborescence* _algorithm;
772 772
      int _index, _last;
773 773
    };
774 774

	
775 775
    /// @}
776 776

	
777 777
  };
778 778

	
779 779
  /// \ingroup spantree
780 780
  ///
781 781
  /// \brief Function type interface for MinCostArborescence algorithm.
782 782
  ///
783 783
  /// Function type interface for MinCostArborescence algorithm.
784 784
  /// \param digraph The digraph the algorithm runs on.
785 785
  /// \param cost An arc map storing the costs.
786 786
  /// \param source The source node of the arborescence.
787 787
  /// \retval arborescence An arc map with \c bool (or convertible) value
788 788
  /// type that stores the arborescence.
789 789
  /// \return The total cost of the arborescence.
790 790
  ///
791 791
  /// \sa MinCostArborescence
792 792
  template <typename Digraph, typename CostMap, typename ArborescenceMap>
793 793
  typename CostMap::Value minCostArborescence(const Digraph& digraph,
794 794
                                              const CostMap& cost,
795 795
                                              typename Digraph::Node source,
796 796
                                              ArborescenceMap& arborescence) {
797 797
    typename MinCostArborescence<Digraph, CostMap>
798 798
      ::template SetArborescenceMap<ArborescenceMap>
799 799
      ::Create mca(digraph, cost);
800 800
    mca.arborescenceMap(arborescence);
801 801
    mca.run(source);
802 802
    return mca.arborescenceCost();
803 803
  }
804 804

	
805 805
}
806 806

	
807 807
#endif

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

0 comments (0 inline)