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

	
19 19
/*!
20 20

	
21 21
\page coding_style LEMON Coding Style
22 22

	
23 23
\section naming_conv Naming Conventions
24 24

	
25 25
In order to make development easier we have made some conventions
26 26
according to coding style. These include names of types, classes,
27 27
functions, variables, constants and exceptions. If these conventions
28 28
are met in one's code then it is easier to read and maintain
29 29
it. Please comply with these conventions if you want to contribute
30 30
developing LEMON library.
31 31

	
32 32
\note When the coding style requires the capitalization of an abbreviation,
33 33
only the first letter should be upper case.
34 34

	
35 35
\code
36 36
XmlReader
37 37
\endcode
38 38

	
39 39

	
40 40
\warning In some cases we diverge from these rules.
41 41
This is primary done because STL uses different naming convention and
42 42
in certain cases
43 43
it is beneficial to provide STL compatible interface.
44 44

	
45 45
\subsection cs-files File Names
46 46

	
47 47
The header file names should look like the following.
48 48

	
49 49
\code
50 50
header_file.h
51 51
\endcode
52 52

	
53 53
Note that all standard LEMON headers are located in the \c lemon subdirectory,
54 54
so you should include them from C++ source like this:
55 55

	
56 56
\code
57 57
#include <lemon/header_file.h>
58 58
\endcode
59 59

	
60 60
The source code files use the same style and they have '.cc' extension.
61 61

	
62 62
\code
63 63
source_code.cc
64 64
\endcode
65 65

	
66 66
\subsection cs-class Classes and other types
67 67

	
68 68
The name of a class or any type should look like the following.
69 69

	
70 70
\code
71 71
AllWordsCapitalizedWithoutUnderscores
72 72
\endcode
73 73

	
74 74
\subsection cs-func Methods and other functions
75 75

	
76 76
The name of a function should look like the following.
77 77

	
78 78
\code
79 79
firstWordLowerCaseRestCapitalizedWithoutUnderscores
80 80
\endcode
81 81

	
82 82
\subsection cs-funcs Constants, Macros
83 83

	
84 84
The names of constants and macros should look like the following.
85 85

	
86 86
\code
87 87
ALL_UPPER_CASE_WITH_UNDERSCORES
88 88
\endcode
89 89

	
90 90
\subsection cs-loc-var Class and instance member variables, auto variables
91 91

	
92
The names of class and instance member variables and auto variables (=variables used locally in methods) should look like the following.
92
The names of class and instance member variables and auto variables
93
(=variables used locally in methods) should look like the following.
93 94

	
94 95
\code
95 96
all_lower_case_with_underscores
96 97
\endcode
97 98

	
98 99
\subsection pri-loc-var Private member variables
99 100

	
100 101
Private member variables should start with underscore
101 102

	
102 103
\code
103 104
_start_with_underscores
104 105
\endcode
105 106

	
106 107
\subsection cs-excep Exceptions
107 108

	
108 109
When writing exceptions please comply the following naming conventions.
109 110

	
110 111
\code
111 112
ClassNameEndsWithException
112 113
\endcode
113 114

	
114 115
or
115 116

	
116 117
\code
117 118
ClassNameEndsWithError
118 119
\endcode
119 120

	
120 121
\section header-template Template Header File
121 122

	
122 123
Each LEMON header file should look like this:
123 124

	
124 125
\include template.h
125 126

	
126 127
*/
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
/**
20 20
@defgroup datas Data Structures
21 21
This group describes the several data structures implemented in LEMON.
22 22
*/
23 23

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

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

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

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

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

	
60 60
/**
61 61
@defgroup semi_adaptors Semi-Adaptor Classes for Graphs
62 62
@ingroup graphs
63 63
\brief Graph types between real graphs and graph adaptors.
64 64

	
65 65
This group describes some graph types between real graphs and graph adaptors.
66 66
These classes wrap graphs to give new functionality as the adaptors do it.
67 67
On the other hand they are not light-weight structures as the adaptors.
68 68
*/
69 69

	
70 70
/**
71 71
@defgroup maps Maps
72 72
@ingroup datas
73 73
\brief Map structures implemented in LEMON.
74 74

	
75 75
This group describes the map structures implemented in LEMON.
76 76

	
77 77
LEMON provides several special purpose maps that e.g. combine
78 78
new maps from existing ones.
79 79
*/
80 80

	
81 81
/**
82 82
@defgroup graph_maps Graph Maps
83 83
@ingroup maps
84 84
\brief Special graph-related maps.
85 85

	
86 86
This group describes maps that are specifically designed to assign
87 87
values to the nodes and arcs of graphs.
88 88
*/
89 89

	
90 90

	
91 91
/**
92 92
\defgroup map_adaptors Map Adaptors
93 93
\ingroup maps
94 94
\brief Tools to create new maps from existing ones
95 95

	
96 96
This group describes map adaptors that are used to create "implicit"
97 97
maps from other maps.
98 98

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

	
104 104
The typical usage of this classes is passing implicit maps to
105 105
algorithms.  If a function type algorithm is called then the function
106 106
type map adaptors can be used comfortable. For example let's see the
107 107
usage of map adaptors with the \c digraphToEps() function.
108 108
\code
109 109
  Color nodeColor(int deg) {
110 110
    if (deg >= 2) {
111 111
      return Color(0.5, 0.0, 0.5);
112 112
    } else if (deg == 1) {
113 113
      return Color(1.0, 0.5, 1.0);
114 114
    } else {
115 115
      return Color(0.0, 0.0, 0.0);
116 116
    }
117 117
  }
118 118

	
119 119
  Digraph::NodeMap<int> degree_map(graph);
120 120

	
121 121
  digraphToEps(graph, "graph.eps")
122 122
    .coords(coords).scaleToA4().undirected()
123 123
    .nodeColors(composeMap(functorToMap(nodeColor), degree_map))
124 124
    .run();
125 125
\endcode
126 126
The \c functorToMap() function makes an \c int to \c Color map from the
127 127
\e nodeColor() function. The \c composeMap() compose the \e degree_map
128 128
and the previously created map. The composed map is a proper function to
129 129
get the color of each node.
130 130

	
131 131
The usage with class type algorithms is little bit harder. In this
132 132
case the function type map adaptors can not be used, because the
133 133
function map adaptors give back temporary objects.
134 134
\code
135 135
  Digraph graph;
136 136

	
137 137
  typedef Digraph::ArcMap<double> DoubleArcMap;
138 138
  DoubleArcMap length(graph);
139 139
  DoubleArcMap speed(graph);
140 140

	
141 141
  typedef DivMap<DoubleArcMap, DoubleArcMap> TimeMap;
142 142
  TimeMap time(length, speed);
143 143

	
144 144
  Dijkstra<Digraph, TimeMap> dijkstra(graph, time);
145 145
  dijkstra.run(source, target);
146 146
\endcode
147 147
We have a length map and a maximum speed map on the arcs of a digraph.
148 148
The minimum time to pass the arc can be calculated as the division of
149 149
the two maps which can be done implicitly with the \c DivMap template
150 150
class. We use the implicit minimum time map as the length map of the
151 151
\c Dijkstra algorithm.
152 152
*/
153 153

	
154 154
/**
155 155
@defgroup matrices Matrices
156 156
@ingroup datas
157 157
\brief Two dimensional data storages implemented in LEMON.
158 158

	
159 159
This group describes two dimensional data storages implemented in LEMON.
160 160
*/
161 161

	
162 162
/**
163 163
@defgroup paths Path Structures
164 164
@ingroup datas
165 165
\brief Path structures implemented in LEMON.
166 166

	
167 167
This group describes the path structures implemented in LEMON.
168 168

	
169 169
LEMON provides flexible data structures to work with paths.
170 170
All of them have similar interfaces and they can be copied easily with
171 171
assignment operators and copy constructors. This makes it easy and
172 172
efficient to have e.g. the Dijkstra algorithm to store its result in
173 173
any kind of path structure.
174 174

	
175 175
\sa lemon::concepts::Path
176 176

	
177 177
*/
178 178

	
179 179
/**
180 180
@defgroup auxdat Auxiliary Data Structures
181 181
@ingroup datas
182 182
\brief Auxiliary data structures implemented in LEMON.
183 183

	
184 184
This group describes some data structures implemented in LEMON in
185 185
order to make it easier to implement combinatorial algorithms.
186 186
*/
187 187

	
188 188

	
189 189
/**
190 190
@defgroup algs Algorithms
191 191
\brief This group describes the several algorithms
192 192
implemented in LEMON.
193 193

	
194 194
This group describes the several algorithms
195 195
implemented in LEMON.
196 196
*/
197 197

	
198 198
/**
199 199
@defgroup search Graph Search
200 200
@ingroup algs
201 201
\brief Common graph search algorithms.
202 202

	
203 203
This group describes the common graph search algorithms like
204 204
Breadth-first search (Bfs) and Depth-first search (Dfs).
205 205
*/
206 206

	
207 207
/**
208 208
@defgroup shortest_path Shortest Path algorithms
209 209
@ingroup algs
210 210
\brief Algorithms for finding shortest paths.
211 211

	
212 212
This group describes the algorithms for finding shortest paths in graphs.
213 213
*/
214 214

	
215 215
/**
216 216
@defgroup max_flow Maximum Flow algorithms
217 217
@ingroup algs
218 218
\brief Algorithms for finding maximum flows.
219 219

	
220 220
This group describes the algorithms for finding maximum flows and
221 221
feasible circulations.
222 222

	
223 223
The maximum flow problem is to find a flow between a single source and
224 224
a single target that is maximum. Formally, there is a \f$G=(V,A)\f$
225 225
directed graph, an \f$c_a:A\rightarrow\mathbf{R}^+_0\f$ capacity
226 226
function and given \f$s, t \in V\f$ source and target node. The
227 227
maximum flow is the \f$f_a\f$ solution of the next optimization problem:
228 228

	
229 229
\f[ 0 \le f_a \le c_a \f]
230
\f[ \sum_{v\in\delta^{-}(u)}f_{vu}=\sum_{v\in\delta^{+}(u)}f_{uv} \qquad \forall u \in V \setminus \{s,t\}\f]
230
\f[ \sum_{v\in\delta^{-}(u)}f_{vu}=\sum_{v\in\delta^{+}(u)}f_{uv}
231
\qquad \forall u \in V \setminus \{s,t\}\f]
231 232
\f[ \max \sum_{v\in\delta^{+}(s)}f_{uv} - \sum_{v\in\delta^{-}(s)}f_{vu}\f]
232 233

	
233 234
LEMON contains several algorithms for solving maximum flow problems:
234 235
- \ref lemon::EdmondsKarp "Edmonds-Karp"
235 236
- \ref lemon::Preflow "Goldberg's Preflow algorithm"
236 237
- \ref lemon::DinitzSleatorTarjan "Dinitz's blocking flow algorithm with dynamic trees"
237 238
- \ref lemon::GoldbergTarjan "Preflow algorithm with dynamic trees"
238 239

	
239 240
In most cases the \ref lemon::Preflow "Preflow" algorithm provides the
240 241
fastest method to compute the maximum flow. All impelementations
241 242
provides functions to query the minimum cut, which is the dual linear
242 243
programming problem of the maximum flow.
243 244

	
244 245
*/
245 246

	
246 247
/**
247 248
@defgroup min_cost_flow Minimum Cost Flow algorithms
248 249
@ingroup algs
249 250

	
250 251
\brief Algorithms for finding minimum cost flows and circulations.
251 252

	
252 253
This group describes the algorithms for finding minimum cost flows and
253 254
circulations.
254 255
*/
255 256

	
256 257
/**
257 258
@defgroup min_cut Minimum Cut algorithms
258 259
@ingroup algs
259 260

	
260 261
\brief Algorithms for finding minimum cut in graphs.
261 262

	
262 263
This group describes the algorithms for finding minimum cut in graphs.
263 264

	
264 265
The minimum cut problem is to find a non-empty and non-complete
265 266
\f$X\f$ subset of the vertices with minimum overall capacity on
266 267
outgoing arcs. Formally, there is \f$G=(V,A)\f$ directed graph, an
267 268
\f$c_a:A\rightarrow\mathbf{R}^+_0\f$ capacity function. The minimum
268 269
cut is the \f$X\f$ solution of the next optimization problem:
269 270

	
270
\f[ \min_{X \subset V, X\not\in \{\emptyset, V\}}\sum_{uv\in A, u\in X, v\not\in X}c_{uv}\f]
271
\f[ \min_{X \subset V, X\not\in \{\emptyset, V\}}
272
\sum_{uv\in A, u\in X, v\not\in X}c_{uv}\f]
271 273

	
272 274
LEMON contains several algorithms related to minimum cut problems:
273 275

	
274 276
- \ref lemon::HaoOrlin "Hao-Orlin algorithm" to calculate minimum cut
275 277
  in directed graphs
276 278
- \ref lemon::NagamochiIbaraki "Nagamochi-Ibaraki algorithm" to
277 279
  calculate minimum cut in undirected graphs
278 280
- \ref lemon::GomoryHuTree "Gomory-Hu tree computation" to calculate all
279 281
  pairs minimum cut in undirected graphs
280 282

	
281 283
If you want to find minimum cut just between two distinict nodes,
282 284
please see the \ref max_flow "Maximum Flow page".
283 285

	
284 286
*/
285 287

	
286 288
/**
287 289
@defgroup graph_prop Connectivity and other graph properties
288 290
@ingroup algs
289 291
\brief Algorithms for discovering the graph properties
290 292

	
291 293
This group describes the algorithms for discovering the graph properties
292 294
like connectivity, bipartiteness, euler property, simplicity etc.
293 295

	
294 296
\image html edge_biconnected_components.png
295 297
\image latex edge_biconnected_components.eps "bi-edge-connected components" width=\textwidth
296 298
*/
297 299

	
298 300
/**
299 301
@defgroup planar Planarity embedding and drawing
300 302
@ingroup algs
301 303
\brief Algorithms for planarity checking, embedding and drawing
302 304

	
303
This group describes the algorithms for planarity checking, embedding and drawing.
305
This group describes the algorithms for planarity checking,
306
embedding and drawing.
304 307

	
305 308
\image html planar.png
306 309
\image latex planar.eps "Plane graph" width=\textwidth
307 310
*/
308 311

	
309 312
/**
310 313
@defgroup matching Matching algorithms
311 314
@ingroup algs
312 315
\brief Algorithms for finding matchings in graphs and bipartite graphs.
313 316

	
314 317
This group contains algorithm objects and functions to calculate
315 318
matchings in graphs and bipartite graphs. The general matching problem is
316 319
finding a subset of the arcs which does not shares common endpoints.
317 320

	
318 321
There are several different algorithms for calculate matchings in
319 322
graphs.  The matching problems in bipartite graphs are generally
320 323
easier than in general graphs. The goal of the matching optimization
321 324
can be the finding maximum cardinality, maximum weight or minimum cost
322 325
matching. The search can be constrained to find perfect or
323 326
maximum cardinality matching.
324 327

	
325 328
Lemon contains the next algorithms:
326 329
- \ref lemon::MaxBipartiteMatching "MaxBipartiteMatching" Hopcroft-Karp
327 330
  augmenting path algorithm for calculate maximum cardinality matching in
328 331
  bipartite graphs
329 332
- \ref lemon::PrBipartiteMatching "PrBipartiteMatching" Push-Relabel
330 333
  algorithm for calculate maximum cardinality matching in bipartite graphs
331 334
- \ref lemon::MaxWeightedBipartiteMatching "MaxWeightedBipartiteMatching"
332 335
  Successive shortest path algorithm for calculate maximum weighted matching
333 336
  and maximum weighted bipartite matching in bipartite graph
334 337
- \ref lemon::MinCostMaxBipartiteMatching "MinCostMaxBipartiteMatching"
335 338
  Successive shortest path algorithm for calculate minimum cost maximum
336 339
  matching in bipartite graph
337 340
- \ref lemon::MaxMatching "MaxMatching" Edmond's blossom shrinking algorithm
338 341
  for calculate maximum cardinality matching in general graph
339 342
- \ref lemon::MaxWeightedMatching "MaxWeightedMatching" Edmond's blossom
340 343
  shrinking algorithm for calculate maximum weighted matching in general
341 344
  graph
342 345
- \ref lemon::MaxWeightedPerfectMatching "MaxWeightedPerfectMatching"
343 346
  Edmond's blossom shrinking algorithm for calculate maximum weighted
344 347
  perfect matching in general graph
345 348

	
346 349
\image html bipartite_matching.png
347 350
\image latex bipartite_matching.eps "Bipartite Matching" width=\textwidth
348 351

	
349 352
*/
350 353

	
351 354
/**
352 355
@defgroup spantree Minimum Spanning Tree algorithms
353 356
@ingroup algs
354 357
\brief Algorithms for finding a minimum cost spanning tree in a graph.
355 358

	
356 359
This group describes the algorithms for finding a minimum cost spanning
357 360
tree in a graph
358 361
*/
359 362

	
360 363

	
361 364
/**
362 365
@defgroup auxalg Auxiliary algorithms
363 366
@ingroup algs
364 367
\brief Auxiliary algorithms implemented in LEMON.
365 368

	
366 369
This group describes some algorithms implemented in LEMON
367 370
in order to make it easier to implement complex algorithms.
368 371
*/
369 372

	
370 373
/**
371 374
@defgroup approx Approximation algorithms
372 375
\brief Approximation algorithms.
373 376

	
374 377
This group describes the approximation and heuristic algorithms
375 378
implemented in LEMON.
376 379
*/
377 380

	
378 381
/**
379 382
@defgroup gen_opt_group General Optimization Tools
380 383
\brief This group describes some general optimization frameworks
381 384
implemented in LEMON.
382 385

	
383 386
This group describes some general optimization frameworks
384 387
implemented in LEMON.
385 388

	
386 389
*/
387 390

	
388 391
/**
389 392
@defgroup lp_group Lp and Mip solvers
390 393
@ingroup gen_opt_group
391 394
\brief Lp and Mip solver interfaces for LEMON.
392 395

	
393 396
This group describes Lp and Mip solver interfaces for LEMON. The
394 397
various LP solvers could be used in the same manner with this
395 398
interface.
396 399

	
397 400
*/
398 401

	
399 402
/**
400 403
@defgroup lp_utils Tools for Lp and Mip solvers
401 404
@ingroup lp_group
402 405
\brief Helper tools to the Lp and Mip solvers.
403 406

	
404 407
This group adds some helper tools to general optimization framework
405 408
implemented in LEMON.
406 409
*/
407 410

	
408 411
/**
409 412
@defgroup metah Metaheuristics
410 413
@ingroup gen_opt_group
411 414
\brief Metaheuristics for LEMON library.
412 415

	
413 416
This group describes some metaheuristic optimization tools.
414 417
*/
415 418

	
416 419
/**
417 420
@defgroup utils Tools and Utilities
418 421
\brief Tools and utilities for programming in LEMON
419 422

	
420 423
Tools and utilities for programming in LEMON.
421 424
*/
422 425

	
423 426
/**
424 427
@defgroup gutils Basic Graph Utilities
425 428
@ingroup utils
426 429
\brief Simple basic graph utilities.
427 430

	
428 431
This group describes some simple basic graph utilities.
429 432
*/
430 433

	
431 434
/**
432 435
@defgroup misc Miscellaneous Tools
433 436
@ingroup utils
434 437
\brief Tools for development, debugging and testing.
435 438

	
436 439
This group describes several useful tools for development,
437 440
debugging and testing.
438 441
*/
439 442

	
440 443
/**
441 444
@defgroup timecount Time measuring and Counting
442 445
@ingroup misc
443 446
\brief Simple tools for measuring the performance of algorithms.
444 447

	
445 448
This group describes simple tools for measuring the performance
446 449
of algorithms.
447 450
*/
448 451

	
449 452
/**
450 453
@defgroup graphbits Tools for Graph Implementation
451 454
@ingroup utils
452 455
\brief Tools to make it easier to create graphs.
453 456

	
454 457
This group describes the tools that makes it easier to create graphs and
455 458
the maps that dynamically update with the graph changes.
456 459
*/
457 460

	
458 461
/**
459 462
@defgroup exceptions Exceptions
460 463
@ingroup utils
461 464
\brief Exceptions defined in LEMON.
462 465

	
463 466
This group describes the exceptions defined in LEMON.
464 467
*/
465 468

	
466 469
/**
467 470
@defgroup io_group Input-Output
468 471
\brief Graph Input-Output methods
469 472

	
470 473
This group describes the tools for importing and exporting graphs
471 474
and graph related data. Now it supports the LEMON format, the
472 475
\c DIMACS format and the encapsulated postscript (EPS) format.
473 476
*/
474 477

	
475 478
/**
476 479
@defgroup lemon_io Lemon Input-Output
477 480
@ingroup io_group
478 481
\brief Reading and writing \ref lgf-format "Lemon Graph Format".
479 482

	
480
This group describes methods for reading and writing \ref lgf-format "Lemon Graph Format".
483
This group describes methods for reading and writing
484
\ref lgf-format "Lemon Graph Format".
481 485
*/
482 486

	
483 487
/**
484 488
@defgroup eps_io Postscript exporting
485 489
@ingroup io_group
486 490
\brief General \c EPS drawer and graph exporter
487 491

	
488 492
This group describes general \c EPS drawing methods and special
489 493
graph exporting tools.
490 494
*/
491 495

	
492 496

	
493 497
/**
494 498
@defgroup concept Concepts
495 499
\brief Skeleton classes and concept checking classes
496 500

	
497 501
This group describes the data/algorithm skeletons and concept checking
498 502
classes implemented in LEMON.
499 503

	
500 504
The purpose of the classes in this group is fourfold.
501 505

	
502 506
- These classes contain the documentations of the concepts. In order
503 507
  to avoid document multiplications, an implementation of a concept
504 508
  simply refers to the corresponding concept class.
505 509

	
506 510
- These classes declare every functions, <tt>typedef</tt>s etc. an
507 511
  implementation of the concepts should provide, however completely
508 512
  without implementations and real data structures behind the
509 513
  interface. On the other hand they should provide nothing else. All
510 514
  the algorithms working on a data structure meeting a certain concept
511 515
  should compile with these classes. (Though it will not run properly,
512 516
  of course.) In this way it is easily to check if an algorithm
513 517
  doesn't use any extra feature of a certain implementation.
514 518

	
515 519
- The concept descriptor classes also provide a <em>checker class</em>
516 520
  that makes it possible to check whether a certain implementation of a
517 521
  concept indeed provides all the required features.
518 522

	
519 523
- Finally, They can serve as a skeleton of a new implementation of a concept.
520 524

	
521 525
*/
522 526

	
523 527

	
524 528
/**
525 529
@defgroup graph_concepts Graph Structure Concepts
526 530
@ingroup concept
527 531
\brief Skeleton and concept checking classes for graph structures
528 532

	
529 533
This group describes the skeletons and concept checking classes of LEMON's
530 534
graph structures and helper classes used to implement these.
531 535
*/
532 536

	
533 537
/* --- Unused group
534 538
@defgroup experimental Experimental Structures and Algorithms
535 539
This group describes some Experimental structures and algorithms.
536 540
The stuff here is subject to change.
537 541
*/
538 542

	
539 543
/**
540 544
\anchor demoprograms
541 545

	
542 546
@defgroup demos Demo programs
543 547

	
544 548
Some demo programs are listed here. Their full source codes can be found in
545 549
the \c demo subdirectory of the source tree.
546 550

	
547 551
It order to compile them, use <tt>--enable-demo</tt> configure option when
548 552
build the library.
549 553
*/
550 554

	
551 555
/**
552 556
@defgroup tools Standalone utility applications
553 557

	
554 558
Some utility applications are listed here.
555 559

	
556 560
The standard compilation procedure (<tt>./configure;make</tt>) will compile
557 561
them, as well.
558 562
*/
559 563

	
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
#include <lemon/arg_parser.h>
20 20

	
21 21
namespace lemon {
22 22

	
23 23
  void ArgParser::_showHelp(void *p)
24 24
  {
25 25
    (static_cast<ArgParser*>(p))->showHelp();
26 26
    exit(1);
27 27
  }
28 28

	
29 29
  ArgParser::ArgParser(int argc, const char **argv) :_argc(argc), _argv(argv),
30 30
                                                     _command_name(argv[0]) {
31 31
    funcOption("-help","Print a short help message",_showHelp,this);
32 32
    synonym("help","-help");
33 33
    synonym("h","-help");
34 34

	
35 35
  }
36 36

	
37 37
  ArgParser::~ArgParser()
38 38
  {
39 39
    for(Opts::iterator i=_opts.begin();i!=_opts.end();++i)
40 40
      if(i->second.self_delete)
41 41
        switch(i->second.type) {
42 42
        case BOOL:
43 43
          delete i->second.bool_p;
44 44
          break;
45 45
        case STRING:
46 46
          delete i->second.string_p;
47 47
          break;
48 48
        case DOUBLE:
49 49
          delete i->second.double_p;
50 50
          break;
51 51
        case INTEGER:
52 52
          delete i->second.int_p;
53 53
          break;
54 54
        case UNKNOWN:
55 55
          break;
56 56
        case FUNC:
57 57
          break;
58 58
        }
59 59
  }
60 60

	
61 61

	
62 62
  ArgParser &ArgParser::intOption(const std::string &name,
63 63
                               const std::string &help,
64 64
                               int value, bool obl)
65 65
  {
66 66
    ParData p;
67 67
    p.int_p=new int(value);
68 68
    p.self_delete=true;
69 69
    p.help=help;
70 70
    p.type=INTEGER;
71 71
    p.mandatory=obl;
72 72
    _opts[name]=p;
73 73
    return *this;
74 74
  }
75 75

	
76 76
  ArgParser &ArgParser::doubleOption(const std::string &name,
77 77
                               const std::string &help,
78 78
                               double value, bool obl)
79 79
  {
80 80
    ParData p;
81 81
    p.double_p=new double(value);
82 82
    p.self_delete=true;
83 83
    p.help=help;
84 84
    p.type=DOUBLE;
85 85
    p.mandatory=obl;
86 86
    _opts[name]=p;
87 87
    return *this;
88 88
  }
89 89

	
90 90
  ArgParser &ArgParser::boolOption(const std::string &name,
91 91
                               const std::string &help,
92 92
                               bool value, bool obl)
93 93
  {
94 94
    ParData p;
95 95
    p.bool_p=new bool(value);
96 96
    p.self_delete=true;
97 97
    p.help=help;
98 98
    p.type=BOOL;
99 99
    p.mandatory=obl;
100 100
    _opts[name]=p;
101 101
    return *this;
102 102
  }
103 103

	
104 104
  ArgParser &ArgParser::stringOption(const std::string &name,
105 105
                               const std::string &help,
106 106
                               std::string value, bool obl)
107 107
  {
108 108
    ParData p;
109 109
    p.string_p=new std::string(value);
110 110
    p.self_delete=true;
111 111
    p.help=help;
112 112
    p.type=STRING;
113 113
    p.mandatory=obl;
114 114
    _opts[name]=p;
115 115
    return *this;
116 116
  }
117 117

	
118 118
  ArgParser &ArgParser::refOption(const std::string &name,
119 119
                               const std::string &help,
120 120
                               int &ref, bool obl)
121 121
  {
122 122
    ParData p;
123 123
    p.int_p=&ref;
124 124
    p.self_delete=false;
125 125
    p.help=help;
126 126
    p.type=INTEGER;
127 127
    p.mandatory=obl;
128 128
    _opts[name]=p;
129 129
    return *this;
130 130
  }
131 131

	
132 132
  ArgParser &ArgParser::refOption(const std::string &name,
133 133
                                  const std::string &help,
134 134
                                  double &ref, bool obl)
135 135
  {
136 136
    ParData p;
137 137
    p.double_p=&ref;
138 138
    p.self_delete=false;
139 139
    p.help=help;
140 140
    p.type=DOUBLE;
141 141
    p.mandatory=obl;
142 142
    _opts[name]=p;
143 143
    return *this;
144 144
  }
145 145

	
146 146
  ArgParser &ArgParser::refOption(const std::string &name,
147 147
                                  const std::string &help,
148 148
                                  bool &ref, bool obl)
149 149
  {
150 150
    ParData p;
151 151
    p.bool_p=&ref;
152 152
    p.self_delete=false;
153 153
    p.help=help;
154 154
    p.type=BOOL;
155 155
    p.mandatory=obl;
156 156
    _opts[name]=p;
157 157

	
158 158
    ref = false;
159 159

	
160 160
    return *this;
161 161
  }
162 162

	
163 163
  ArgParser &ArgParser::refOption(const std::string &name,
164 164
                               const std::string &help,
165 165
                               std::string &ref, bool obl)
166 166
  {
167 167
    ParData p;
168 168
    p.string_p=&ref;
169 169
    p.self_delete=false;
170 170
    p.help=help;
171 171
    p.type=STRING;
172 172
    p.mandatory=obl;
173 173
    _opts[name]=p;
174 174
    return *this;
175 175
  }
176 176

	
177 177
  ArgParser &ArgParser::funcOption(const std::string &name,
178 178
                               const std::string &help,
179 179
                               void (*func)(void *),void *data)
180 180
  {
181 181
    ParData p;
182 182
    p.func_p.p=func;
183 183
    p.func_p.data=data;
184 184
    p.self_delete=false;
185 185
    p.help=help;
186 186
    p.type=FUNC;
187 187
    p.mandatory=false;
188 188
    _opts[name]=p;
189 189
    return *this;
190 190
  }
191 191

	
192 192
  ArgParser &ArgParser::optionGroup(const std::string &group,
193 193
                                    const std::string &opt)
194 194
  {
195 195
    Opts::iterator i = _opts.find(opt);
196 196
    LEMON_ASSERT(i!=_opts.end(), "Unknown option: '"+opt+"'");
197 197
    LEMON_ASSERT(!(i->second.ingroup),
198 198
                 "Option already in option group: '"+opt+"'");
199 199
    GroupData &g=_groups[group];
200 200
    g.opts.push_back(opt);
201 201
    i->second.ingroup=true;
202 202
    return *this;
203 203
  }
204 204

	
205 205
  ArgParser &ArgParser::onlyOneGroup(const std::string &group)
206 206
  {
207 207
    GroupData &g=_groups[group];
208 208
    g.only_one=true;
209 209
    return *this;
210 210
  }
211 211

	
212 212
  ArgParser &ArgParser::synonym(const std::string &syn,
213 213
                                const std::string &opt)
214 214
  {
215 215
    Opts::iterator o = _opts.find(opt);
216 216
    Opts::iterator s = _opts.find(syn);
217 217
    LEMON_ASSERT(o!=_opts.end(), "Unknown option: '"+opt+"'");
218 218
    LEMON_ASSERT(s==_opts.end(), "Option already used: '"+syn+"'");
219 219
    ParData p;
220 220
    p.help=opt;
221 221
    p.mandatory=false;
222 222
    p.syn=true;
223 223
    _opts[syn]=p;
224 224
    o->second.has_syn=true;
225 225
    return *this;
226 226
  }
227 227

	
228 228
  ArgParser &ArgParser::mandatoryGroup(const std::string &group)
229 229
  {
230 230
    GroupData &g=_groups[group];
231 231
    g.mandatory=true;
232 232
    return *this;
233 233
  }
234 234

	
235 235
  ArgParser &ArgParser::other(const std::string &name,
236 236
                              const std::string &help)
237 237
  {
238 238
    _others_help.push_back(OtherArg(name,help));
239 239
    return *this;
240 240
  }
241 241

	
242 242
  void ArgParser::show(std::ostream &os,Opts::iterator i)
243 243
  {
244 244
    os << "-" << i->first;
245 245
    if(i->second.has_syn)
246 246
      for(Opts::iterator j=_opts.begin();j!=_opts.end();++j)
247 247
        if(j->second.syn&&j->second.help==i->first)
248 248
          os << "|-" << j->first;
249 249
    switch(i->second.type) {
250 250
    case STRING:
251 251
      os << " str";
252 252
      break;
253 253
    case INTEGER:
254 254
      os << " int";
255 255
      break;
256 256
    case DOUBLE:
257 257
      os << " num";
258 258
      break;
259 259
    default:
260 260
      break;
261 261
    }
262 262
  }
263 263

	
264 264
  void ArgParser::show(std::ostream &os,Groups::iterator i)
265 265
  {
266 266
    GroupData::Opts::iterator o=i->second.opts.begin();
267 267
    while(o!=i->second.opts.end()) {
268 268
      show(os,_opts.find(*o));
269 269
      ++o;
270 270
      if(o!=i->second.opts.end()) os<<'|';
271 271
    }
272 272
  }
273 273

	
274 274
  void ArgParser::showHelp(Opts::iterator i)
275 275
  {
276 276
    if(i->second.help.size()==0||i->second.syn) return;
277 277
    std::cerr << "  ";
278 278
    show(std::cerr,i);
279 279
    std::cerr << std::endl;
280 280
    std::cerr << "     " << i->second.help << std::endl;
281 281
  }
282 282
  void ArgParser::showHelp(std::vector<ArgParser::OtherArg>::iterator i)
283 283
  {
284 284
    if(i->help.size()==0) return;
285 285
    std::cerr << "  " << i->name << std::endl
286 286
              << "     " << i->help << std::endl;
287 287
  }
288 288

	
289 289
  void ArgParser::shortHelp()
290 290
  {
291 291
    const unsigned int LINE_LEN=77;
292 292
    const std::string indent("    ");
293 293
    std::cerr << "Usage:\n  " << _command_name;
294 294
    int pos=_command_name.size()+2;
295 295
    for(Groups::iterator g=_groups.begin();g!=_groups.end();++g) {
296 296
      std::ostringstream cstr;
297 297
      cstr << ' ';
298 298
      if(!g->second.mandatory) cstr << '[';
299 299
      show(cstr,g);
300 300
      if(!g->second.mandatory) cstr << ']';
301 301
      if(pos+cstr.str().size()>LINE_LEN) {
302 302
        std::cerr << std::endl << indent;
303 303
        pos=indent.size();
304 304
      }
305 305
      std::cerr << cstr.str();
306 306
      pos+=cstr.str().size();
307 307
    }
308 308
    for(Opts::iterator i=_opts.begin();i!=_opts.end();++i)
309 309
      if(!i->second.ingroup&&!i->second.syn) {
310 310
        std::ostringstream cstr;
311 311
        cstr << ' ';
312 312
        if(!i->second.mandatory) cstr << '[';
313 313
        show(cstr,i);
314 314
        if(!i->second.mandatory) cstr << ']';
315 315
        if(pos+cstr.str().size()>LINE_LEN) {
316 316
          std::cerr << std::endl << indent;
317 317
          pos=indent.size();
318 318
        }
319 319
        std::cerr << cstr.str();
320 320
        pos+=cstr.str().size();
321 321
      }
322 322
    for(std::vector<OtherArg>::iterator i=_others_help.begin();
323 323
        i!=_others_help.end();++i)
324 324
      {
325 325
        std::ostringstream cstr;
326 326
        cstr << ' ' << i->name;
327 327

	
328 328
        if(pos+cstr.str().size()>LINE_LEN) {
329 329
          std::cerr << std::endl << indent;
330 330
          pos=indent.size();
331 331
        }
332 332
        std::cerr << cstr.str();
333 333
        pos+=cstr.str().size();
334 334
      }
335 335
    std::cerr << std::endl;
336 336
  }
337 337

	
338 338
  void ArgParser::showHelp()
339 339
  {
340 340
    shortHelp();
341 341
    std::cerr << "Where:\n";
342 342
    for(std::vector<OtherArg>::iterator i=_others_help.begin();
343 343
        i!=_others_help.end();++i) showHelp(i);
344 344
    for(Opts::iterator i=_opts.begin();i!=_opts.end();++i) showHelp(i);
345 345
    exit(1);
346 346
  }
347 347

	
348 348

	
349 349
  void ArgParser::unknownOpt(std::string arg)
350 350
  {
351 351
    std::cerr << "\nUnknown option: " << arg << "\n";
352 352
    std::cerr << "\nType '" << _command_name <<
353 353
      " --help' to obtain a short summary on the usage.\n\n";
354 354
    exit(1);
355 355
  }
356 356

	
357 357
  void ArgParser::requiresValue(std::string arg, OptType t)
358 358
  {
359 359
    std::cerr << "Argument '" << arg << "' requires a";
360 360
    switch(t) {
361 361
    case STRING:
362 362
      std::cerr << " string";
363 363
      break;
364 364
    case INTEGER:
365 365
      std::cerr << "n integer";
366 366
      break;
367 367
    case DOUBLE:
368 368
      std::cerr << " floating point";
369 369
      break;
370 370
    default:
371 371
      break;
372 372
    }
373 373
    std::cerr << " value\n\n";
374 374
    showHelp();
375 375
  }
376 376

	
377 377

	
378 378
  void ArgParser::checkMandatories()
379 379
  {
380 380
    bool ok=true;
381 381
    for(Opts::iterator i=_opts.begin();i!=_opts.end();++i)
382 382
      if(i->second.mandatory&&!i->second.set)
383 383
        {
384 384
          if(ok)
385 385
            std::cerr << _command_name
386 386
                      << ": The following mandatory arguments are missing.\n";
387 387
          ok=false;
388 388
          showHelp(i);
389 389
        }
390 390
    for(Groups::iterator i=_groups.begin();i!=_groups.end();++i)
391 391
      if(i->second.mandatory||i->second.only_one)
392 392
        {
393 393
          int set=0;
394 394
          for(GroupData::Opts::iterator o=i->second.opts.begin();
395 395
              o!=i->second.opts.end();++o)
396 396
            if(_opts.find(*o)->second.set) ++set;
397 397
          if(i->second.mandatory&&!set) {
398
            std::cerr << _command_name
399
                      << ": At least one of the following arguments is mandatory.\n";
398
            std::cerr << _command_name <<
399
              ": At least one of the following arguments is mandatory.\n";
400 400
            ok=false;
401 401
            for(GroupData::Opts::iterator o=i->second.opts.begin();
402 402
                o!=i->second.opts.end();++o)
403 403
              showHelp(_opts.find(*o));
404 404
          }
405 405
          if(i->second.only_one&&set>1) {
406
            std::cerr << _command_name
407
                      << ": At most one of the following arguments can be given.\n";
406
            std::cerr << _command_name <<
407
              ": At most one of the following arguments can be given.\n";
408 408
            ok=false;
409 409
            for(GroupData::Opts::iterator o=i->second.opts.begin();
410 410
                o!=i->second.opts.end();++o)
411 411
              showHelp(_opts.find(*o));
412 412
          }
413 413
        }
414 414
    if(!ok) {
415 415
      std::cerr << "\nType '" << _command_name <<
416 416
        " --help' to obtain a short summary on the usage.\n\n";
417 417
      exit(1);
418 418
    }
419 419
  }
420 420

	
421 421
  ArgParser &ArgParser::parse()
422 422
  {
423 423
    for(int ar=1; ar<_argc; ++ar) {
424 424
      std::string arg(_argv[ar]);
425 425
      if (arg[0] != '-' || arg.size() == 1) {
426 426
        _file_args.push_back(arg);
427 427
      }
428 428
      else {
429 429
        Opts::iterator i = _opts.find(arg.substr(1));
430 430
        if(i==_opts.end()) unknownOpt(arg);
431 431
        else {
432 432
          if(i->second.syn) i=_opts.find(i->second.help);
433 433
          ParData &p(i->second);
434 434
          if (p.type==BOOL) *p.bool_p=true;
435 435
          else if (p.type==FUNC) p.func_p.p(p.func_p.data);
436 436
          else if(++ar==_argc) requiresValue(arg, p.type);
437 437
          else {
438 438
            std::string val(_argv[ar]);
439 439
            std::istringstream vals(val);
440 440
            switch(p.type) {
441 441
            case STRING:
442 442
              *p.string_p=val;
443 443
              break;
444 444
            case INTEGER:
445 445
              vals >> *p.int_p;
446 446
              break;
447 447
            case DOUBLE:
448 448
              vals >> *p.double_p;
449 449
              break;
450 450
            default:
451 451
              break;
452 452
            }
453 453
            if(p.type!=STRING&&(!vals||!vals.eof()))
454 454
              requiresValue(arg, p.type);
455 455
          }
456 456
          p.set = true;
457 457
        }
458 458
      }
459 459
    }
460 460
    checkMandatories();
461 461

	
462 462
    return *this;
463 463
  }
464 464

	
465 465
}
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_ASSERT_H
20 20
#define LEMON_ASSERT_H
21 21

	
22 22
/// \ingroup exceptions
23 23
/// \file
24 24
/// \brief Extended assertion handling
25 25

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

	
28 28
namespace lemon {
29 29

	
30 30
  inline void assert_fail_log(const char *file, int line, const char *function,
31 31
                              const char *message, const char *assertion)
32 32
  {
33 33
    std::cerr << file << ":" << line << ": ";
34 34
    if (function)
35 35
      std::cerr << function << ": ";
36 36
    std::cerr << message;
37 37
    if (assertion)
38 38
      std::cerr << " (assertion '" << assertion << "' failed)";
39 39
    std::cerr << std::endl;
40 40
  }
41 41

	
42 42
  inline void assert_fail_abort(const char *file, int line,
43 43
                                const char *function, const char* message,
44 44
                                const char *assertion)
45 45
  {
46 46
    assert_fail_log(file, line, function, message, assertion);
47 47
    std::abort();
48 48
  }
49 49

	
50 50
  namespace _assert_bits {
51 51

	
52 52

	
53 53
    inline const char* cstringify(const std::string& str) {
54 54
      return str.c_str();
55 55
    }
56 56

	
57 57
    inline const char* cstringify(const char* str) {
58 58
      return str;
59 59
    }
60 60
  }
61 61
}
62 62

	
63 63
#endif // LEMON_ASSERT_H
64 64

	
65 65
#undef LEMON_ASSERT
66 66
#undef LEMON_FIXME
67 67
#undef LEMON_DEBUG
68 68

	
69 69
#if (defined(LEMON_ASSERT_LOG) ? 1 : 0) +                \
70 70
  (defined(LEMON_ASSERT_ABORT) ? 1 : 0) +                \
71 71
  (defined(LEMON_ASSERT_CUSTOM) ? 1 : 0) > 1
72 72
#error "LEMON assertion system is not set properly"
73 73
#endif
74 74

	
75 75
#if ((defined(LEMON_ASSERT_LOG) ? 1 : 0) +                \
76 76
     (defined(LEMON_ASSERT_ABORT) ? 1 : 0) +                \
77 77
     (defined(LEMON_ASSERT_CUSTOM) ? 1 : 0) == 1 ||        \
78 78
     defined(LEMON_ENABLE_ASSERTS)) &&                        \
79 79
  (defined(LEMON_DISABLE_ASSERTS) ||                        \
80 80
   defined(NDEBUG))
81 81
#error "LEMON assertion system is not set properly"
82 82
#endif
83 83

	
84 84

	
85 85
#if defined LEMON_ASSERT_LOG
86 86
#  undef LEMON_ASSERT_HANDLER
87 87
#  define LEMON_ASSERT_HANDLER ::lemon::assert_fail_log
88 88
#elif defined LEMON_ASSERT_ABORT
89 89
#  undef LEMON_ASSERT_HANDLER
90 90
#  define LEMON_ASSERT_HANDLER ::lemon::assert_fail_abort
91 91
#elif defined LEMON_ASSERT_CUSTOM
92 92
#  undef LEMON_ASSERT_HANDLER
93 93
#  ifndef LEMON_CUSTOM_ASSERT_HANDLER
94 94
#    error "LEMON_CUSTOM_ASSERT_HANDLER is not set"
95 95
#  endif
96 96
#  define LEMON_ASSERT_HANDLER LEMON_CUSTOM_ASSERT_HANDLER
97 97
#elif defined LEMON_DISABLE_ASSERTS
98 98
#  undef LEMON_ASSERT_HANDLER
99 99
#elif defined NDEBUG
100 100
#  undef LEMON_ASSERT_HANDLER
101 101
#else
102 102
#  define LEMON_ASSERT_HANDLER ::lemon::assert_fail_abort
103 103
#endif
104 104

	
105 105
#ifndef LEMON_FUNCTION_NAME
106 106
#  if defined __GNUC__
107 107
#    define LEMON_FUNCTION_NAME (__PRETTY_FUNCTION__)
108 108
#  elif defined _MSC_VER
109 109
#    define LEMON_FUNCTION_NAME (__FUNCSIG__)
110 110
#  else
111 111
#    define LEMON_FUNCTION_NAME (__func__)
112 112
#  endif
113 113
#endif
114 114

	
115 115
#ifdef DOXYGEN
116 116

	
117 117
/// \ingroup exceptions
118 118
///
119 119
/// \brief Macro for assertion with customizable message
120 120
///
121 121
/// Macro for assertion with customizable message.  \param exp An
122 122
/// expression that must be convertible to \c bool.  If it is \c
123 123
/// false, then an assertion is raised. The concrete behaviour depends
124 124
/// on the settings of the assertion system.  \param msg A <tt>const
125 125
/// char*</tt> parameter, which can be used to provide information
126 126
/// about the circumstances of the failed assertion.
127 127
///
128 128
/// The assertions are enabled in the default behaviour.
129 129
/// You can disable them with the following code:
130 130
/// \code
131 131
/// #define LEMON_DISABLE_ASSERTS
132 132
/// \endcode
133 133
/// or with compilation parameters:
134 134
/// \code
135 135
/// g++ -DLEMON_DISABLE_ASSERTS
136 136
/// make CXXFLAGS='-DLEMON_DISABLE_ASSERTS'
137 137
/// \endcode
138 138
/// The checking is also disabled when the standard macro \c NDEBUG is defined.
139 139
///
140 140
/// The LEMON assertion system has a wide range of customization
141 141
/// properties. As a default behaviour the failed assertion prints a
142 142
/// short log message to the standard error and aborts the execution.
143 143
///
144 144
/// The following modes can be used in the assertion system:
145 145
///
146 146
/// - \c LEMON_ASSERT_LOG The failed assertion prints a short log
147 147
///   message to the standard error and continues the execution.
148 148
/// - \c LEMON_ASSERT_ABORT This mode is similar to the \c
149 149
///   LEMON_ASSERT_LOG, but it aborts the program. It is the default
150 150
///   behaviour.
151 151
/// - \c LEMON_ASSERT_CUSTOM The user can define own assertion handler
152 152
///   function.
153 153
///   \code
154
///     void custom_assert_handler(const char* file, int line, const char* function,
155
///                                const char* message, const char* assertion);
154
///     void custom_assert_handler(const char* file, int line,
155
///                                const char* function, const char* message,
156
///                                const char* assertion);
156 157
///   \endcode
157 158
///   The name of the function should be defined as the \c
158 159
///   LEMON_CUSTOM_ASSERT_HANDLER macro name.
159 160
///   \code
160 161
///     #define LEMON_CUSTOM_ASSERT_HANDLER custom_assert_handler
161 162
///   \endcode
162 163
///   Whenever an assertion is occured, the custom assertion
163 164
///   handler is called with appropiate parameters.
164 165
///
165 166
/// The assertion mode can also be changed within one compilation unit.
166 167
/// If the macros are redefined with other settings and the
167 168
/// \ref lemon/assert.h "assert.h" file is reincluded, then the
168 169
/// behaviour is changed appropiately to the new settings.
169 170
#  define LEMON_ASSERT(exp, msg)                                        \
170 171
  (static_cast<void> (!!(exp) ? 0 : (                                        \
171 172
    LEMON_ASSERT_HANDLER(__FILE__, __LINE__,                                \
172 173
                         LEMON_FUNCTION_NAME,                                \
173 174
                         ::lemon::_assert_bits::cstringify(msg), #exp), 0)))
174 175

	
175 176
/// \ingroup exceptions
176 177
///
177 178
/// \brief Macro for mark not yet implemented features.
178 179
///
179 180
/// Macro for mark not yet implemented features and outstanding bugs.
180 181
/// It is close to be the shortcut of the following code:
181 182
/// \code
182 183
///   LEMON_ASSERT(false, msg);
183 184
/// \endcode
184 185
///
185 186
/// \see LEMON_ASSERT
186 187
#  define LEMON_FIXME(msg)                                                \
187 188
  (LEMON_ASSERT_HANDLER(__FILE__, __LINE__, LEMON_FUNCTION_NAME,        \
188
                        ::lemon::_assert_bits::cstringify(msg),                \
189
                        ::lemon::_assert_bits::cstringify(msg),          \
189 190
                        static_cast<const char*>(0)))
190 191

	
191 192
/// \ingroup exceptions
192 193
///
193 194
/// \brief Macro for internal assertions
194 195
///
195 196
/// Macro for internal assertions, it is used in the library to check
196 197
/// the consistency of results of algorithms, several pre- and
197 198
/// postconditions and invariants. The checking is disabled by
198 199
/// default, but it can be turned on with the macro \c
199 200
/// LEMON_ENABLE_DEBUG.
200 201
/// \code
201 202
/// #define LEMON_ENABLE_DEBUG
202 203
/// \endcode
203 204
/// or with compilation parameters:
204 205
/// \code
205 206
/// g++ -DLEMON_ENABLE_DEBUG
206 207
/// make CXXFLAGS='-DLEMON_ENABLE_DEBUG'
207 208
/// \endcode
208 209
///
209 210
/// This macro works like the \c LEMON_ASSERT macro, therefore the
210 211
/// current behaviour depends on the settings of \c LEMON_ASSERT
211 212
/// macro.
212 213
///
213 214
/// \see LEMON_ASSERT
214 215
#  define LEMON_DEBUG(exp, msg)                                                \
215 216
  (static_cast<void> (!!(exp) ? 0 : (                                        \
216 217
    LEMON_ASSERT_HANDLER(__FILE__, __LINE__,                            \
217 218
                         LEMON_FUNCTION_NAME,                                \
218 219
                         ::lemon::_assert_bits::cstringify(msg), #exp), 0)))
219 220

	
220 221
#else
221 222

	
222 223
#  ifndef LEMON_ASSERT_HANDLER
223 224
#    define LEMON_ASSERT(exp, msg)  (static_cast<void>(0))
224 225
#    define LEMON_FIXME(msg) (static_cast<void>(0))
225 226
#    define LEMON_DEBUG(exp, msg) (static_cast<void>(0))
226 227
#  else
227 228
#    define LEMON_ASSERT(exp, msg)                                        \
228 229
       (static_cast<void> (!!(exp) ? 0 : (                                \
229 230
        LEMON_ASSERT_HANDLER(__FILE__, __LINE__,                        \
230 231
                             LEMON_FUNCTION_NAME,                        \
231 232
                             ::lemon::_assert_bits::cstringify(msg),        \
232 233
                             #exp), 0)))
233 234
#    define LEMON_FIXME(msg)                                                \
234 235
       (LEMON_ASSERT_HANDLER(__FILE__, __LINE__, LEMON_FUNCTION_NAME,        \
235 236
                             ::lemon::_assert_bits::cstringify(msg),        \
236 237
                             static_cast<const char*>(0)))
237 238

	
238 239
#    if LEMON_ENABLE_DEBUG
239 240
#      define LEMON_DEBUG(exp, msg)
240 241
         (static_cast<void> (!!(exp) ? 0 : (         \
241 242
           LEMON_ASSERT_HANDLER(__FILE__, __LINE__,  \
242 243
                                LEMON_FUNCTION_NAME, \
243
                                ::lemon::_assert_bits::cstringify(msg),        \
244
                                ::lemon::_assert_bits::cstringify(msg),     \
244 245
                                #exp), 0)))
245 246
#    else
246 247
#      define LEMON_DEBUG(exp, msg) (static_cast<void>(0))
247 248
#    endif
248 249
#  endif
249 250

	
250 251
#endif
251 252

	
252 253
#ifdef DOXYGEN
253 254

	
254 255

	
255 256
#else
256 257

	
257 258

	
258 259
#endif
259 260

	
260 261

	
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_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/graph_utils.h>
28 28
#include <lemon/bits/path_dump.h>
29 29
#include <lemon/bits/invalid.h>
30 30
#include <lemon/error.h>
31 31
#include <lemon/maps.h>
32 32

	
33 33
namespace lemon {
34 34

	
35 35

	
36 36

	
37 37
  ///Default traits class of Bfs class.
38 38

	
39 39
  ///Default traits class of Bfs class.
40 40
  ///\tparam GR Digraph type.
41 41
  template<class GR>
42 42
  struct BfsDefaultTraits
43 43
  {
44 44
    ///The digraph type the algorithm runs on.
45 45
    typedef GR Digraph;
46 46
    ///\brief The type of the map that stores the last
47 47
    ///arcs of the shortest paths.
48 48
    ///
49 49
    ///The type of the map that stores the last
50 50
    ///arcs of the shortest paths.
51 51
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
52 52
    ///
53 53
    typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap;
54 54
    ///Instantiates a PredMap.
55 55

	
56 56
    ///This function instantiates a \ref PredMap.
57 57
    ///\param G is the digraph, to which we would like to define the PredMap.
58 58
    ///\todo The digraph alone may be insufficient to initialize
59 59
    static PredMap *createPredMap(const GR &G)
60 60
    {
61 61
      return new PredMap(G);
62 62
    }
63 63
    ///The type of the map that indicates which nodes are processed.
64 64

	
65 65
    ///The type of the map that indicates which nodes are processed.
66 66
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
67 67
    ///\todo named parameter to set this type, function to read and write.
68 68
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
69 69
    ///Instantiates a ProcessedMap.
70 70

	
71 71
    ///This function instantiates a \ref ProcessedMap.
72 72
    ///\param g is the digraph, to which
73 73
    ///we would like to define the \ref ProcessedMap
74 74
#ifdef DOXYGEN
75 75
    static ProcessedMap *createProcessedMap(const GR &g)
76 76
#else
77 77
    static ProcessedMap *createProcessedMap(const GR &)
78 78
#endif
79 79
    {
80 80
      return new ProcessedMap();
81 81
    }
82 82
    ///The type of the map that indicates which nodes are reached.
83 83

	
84 84
    ///The type of the map that indicates which nodes are reached.
85 85
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
86 86
    ///\todo named parameter to set this type, function to read and write.
87 87
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
88 88
    ///Instantiates a ReachedMap.
89 89

	
90 90
    ///This function instantiates a \ref ReachedMap.
91 91
    ///\param G is the digraph, to which
92 92
    ///we would like to define the \ref ReachedMap.
93 93
    static ReachedMap *createReachedMap(const GR &G)
94 94
    {
95 95
      return new ReachedMap(G);
96 96
    }
97 97
    ///The type of the map that stores the dists of the nodes.
98 98

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

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

	
113 114
  ///%BFS algorithm class.
114 115

	
115 116
  ///\ingroup search
116 117
  ///This class provides an efficient implementation of the %BFS algorithm.
117 118
  ///
118 119
  ///\tparam GR The digraph type the algorithm runs on. The default value is
119 120
  ///\ref ListDigraph. The value of GR is not used directly by Bfs, it
120 121
  ///is only passed to \ref BfsDefaultTraits.
121 122
  ///\tparam TR Traits class to set various data types used by the algorithm.
122 123
  ///The default traits class is
123 124
  ///\ref BfsDefaultTraits "BfsDefaultTraits<GR>".
124 125
  ///See \ref BfsDefaultTraits for the documentation of
125 126
  ///a Bfs traits class.
126 127

	
127 128
#ifdef DOXYGEN
128 129
  template <typename GR,
129 130
            typename TR>
130 131
#else
131 132
  template <typename GR=ListDigraph,
132 133
            typename TR=BfsDefaultTraits<GR> >
133 134
#endif
134 135
  class Bfs {
135 136
  public:
136 137
    /**
137 138
     * \brief \ref Exception for uninitialized parameters.
138 139
     *
139 140
     * This error represents problems in the initialization
140 141
     * of the parameters of the algorithms.
141 142
     */
142 143
    class UninitializedParameter : public lemon::UninitializedParameter {
143 144
    public:
144 145
      virtual const char* what() const throw() {
145 146
        return "lemon::Bfs::UninitializedParameter";
146 147
      }
147 148
    };
148 149

	
149 150
    typedef TR Traits;
150 151
    ///The type of the underlying digraph.
151 152
    typedef typename TR::Digraph Digraph;
152 153

	
153 154
    ///\brief The type of the map that stores the last
154 155
    ///arcs of the shortest paths.
155 156
    typedef typename TR::PredMap PredMap;
156 157
    ///The type of the map indicating which nodes are reached.
157 158
    typedef typename TR::ReachedMap ReachedMap;
158 159
    ///The type of the map indicating which nodes are processed.
159 160
    typedef typename TR::ProcessedMap ProcessedMap;
160 161
    ///The type of the map that stores the dists of the nodes.
161 162
    typedef typename TR::DistMap DistMap;
162 163
  private:
163 164

	
164 165
    typedef typename Digraph::Node Node;
165 166
    typedef typename Digraph::NodeIt NodeIt;
166 167
    typedef typename Digraph::Arc Arc;
167 168
    typedef typename Digraph::OutArcIt OutArcIt;
168 169

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

	
188 189
    std::vector<typename Digraph::Node> _queue;
189 190
    int _queue_head,_queue_tail,_queue_next_dist;
190 191
    int _curr_dist;
191 192

	
192 193
    ///Creates the maps if necessary.
193 194

	
194 195
    ///\todo Better memory allocation (instead of new).
195 196
    void create_maps()
196 197
    {
197 198
      if(!_pred) {
198 199
        local_pred = true;
199 200
        _pred = Traits::createPredMap(*G);
200 201
      }
201 202
      if(!_dist) {
202 203
        local_dist = true;
203 204
        _dist = Traits::createDistMap(*G);
204 205
      }
205 206
      if(!_reached) {
206 207
        local_reached = true;
207 208
        _reached = Traits::createReachedMap(*G);
208 209
      }
209 210
      if(!_processed) {
210 211
        local_processed = true;
211 212
        _processed = Traits::createProcessedMap(*G);
212 213
      }
213 214
    }
214 215

	
215 216
  protected:
216 217

	
217 218
    Bfs() {}
218 219

	
219 220
  public:
220 221

	
221 222
    typedef Bfs Create;
222 223

	
223 224
    ///\name Named template parameters
224 225

	
225 226
    ///@{
226 227

	
227 228
    template <class T>
228 229
    struct DefPredMapTraits : public Traits {
229 230
      typedef T PredMap;
230 231
      static PredMap *createPredMap(const Digraph &)
231 232
      {
232 233
        throw UninitializedParameter();
233 234
      }
234 235
    };
235 236
    ///\brief \ref named-templ-param "Named parameter" for setting
236 237
    ///PredMap type
237 238
    ///
238 239
    ///\ref named-templ-param "Named parameter" for setting PredMap type
239 240
    ///
240 241
    template <class T>
241 242
    struct DefPredMap : public Bfs< Digraph, DefPredMapTraits<T> > {
242 243
      typedef Bfs< Digraph, DefPredMapTraits<T> > Create;
243 244
    };
244 245

	
245 246
    template <class T>
246 247
    struct DefDistMapTraits : public Traits {
247 248
      typedef T DistMap;
248 249
      static DistMap *createDistMap(const Digraph &)
249 250
      {
250 251
        throw UninitializedParameter();
251 252
      }
252 253
    };
253 254
    ///\brief \ref named-templ-param "Named parameter" for setting
254 255
    ///DistMap type
255 256
    ///
256 257
    ///\ref named-templ-param "Named parameter" for setting DistMap type
257 258
    ///
258 259
    template <class T>
259 260
    struct DefDistMap : public Bfs< Digraph, DefDistMapTraits<T> > {
260 261
      typedef Bfs< Digraph, DefDistMapTraits<T> > Create;
261 262
    };
262 263

	
263 264
    template <class T>
264 265
    struct DefReachedMapTraits : public Traits {
265 266
      typedef T ReachedMap;
266 267
      static ReachedMap *createReachedMap(const Digraph &)
267 268
      {
268 269
        throw UninitializedParameter();
269 270
      }
270 271
    };
271 272
    ///\brief \ref named-templ-param "Named parameter" for setting
272 273
    ///ReachedMap type
273 274
    ///
274 275
    ///\ref named-templ-param "Named parameter" for setting ReachedMap type
275 276
    ///
276 277
    template <class T>
277 278
    struct DefReachedMap : public Bfs< Digraph, DefReachedMapTraits<T> > {
278 279
      typedef Bfs< Digraph, DefReachedMapTraits<T> > Create;
279 280
    };
280 281

	
281 282
    template <class T>
282 283
    struct DefProcessedMapTraits : public Traits {
283 284
      typedef T ProcessedMap;
284 285
      static ProcessedMap *createProcessedMap(const Digraph &)
285 286
      {
286 287
        throw UninitializedParameter();
287 288
      }
288 289
    };
289 290
    ///\brief \ref named-templ-param "Named parameter" for setting
290 291
    ///ProcessedMap type
291 292
    ///
292 293
    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
293 294
    ///
294 295
    template <class T>
295 296
    struct DefProcessedMap : public Bfs< Digraph, DefProcessedMapTraits<T> > {
296 297
      typedef Bfs< Digraph, DefProcessedMapTraits<T> > Create;
297 298
    };
298 299

	
299 300
    struct DefDigraphProcessedMapTraits : public Traits {
300 301
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
301 302
      static ProcessedMap *createProcessedMap(const Digraph &G)
302 303
      {
303 304
        return new ProcessedMap(G);
304 305
      }
305 306
    };
306 307
    ///\brief \ref named-templ-param "Named parameter"
307 308
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
308 309
    ///
309 310
    ///\ref named-templ-param "Named parameter"
310 311
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
311 312
    ///If you don't set it explicitly, it will be automatically allocated.
312 313
    template <class T>
313 314
    struct DefProcessedMapToBeDefaultMap :
314 315
      public Bfs< Digraph, DefDigraphProcessedMapTraits> {
315 316
      typedef Bfs< Digraph, DefDigraphProcessedMapTraits> Create;
316 317
    };
317 318

	
318 319
    ///@}
319 320

	
320 321
  public:
321 322

	
322 323
    ///Constructor.
323 324

	
324 325
    ///\param _G the digraph the algorithm will run on.
325 326
    ///
326 327
    Bfs(const Digraph& _G) :
327 328
      G(&_G),
328 329
      _pred(NULL), local_pred(false),
329 330
      _dist(NULL), local_dist(false),
330 331
      _reached(NULL), local_reached(false),
331 332
      _processed(NULL), local_processed(false)
332 333
    { }
333 334

	
334 335
    ///Destructor.
335 336
    ~Bfs()
336 337
    {
337 338
      if(local_pred) delete _pred;
338 339
      if(local_dist) delete _dist;
339 340
      if(local_reached) delete _reached;
340 341
      if(local_processed) delete _processed;
341 342
    }
342 343

	
343 344
    ///Sets the map storing the predecessor arcs.
344 345

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

	
360 361
    ///Sets the map indicating the reached nodes.
361 362

	
362 363
    ///Sets the map indicating the reached nodes.
363 364
    ///If you don't use this function before calling \ref run(),
364 365
    ///it will allocate one. The destructor deallocates this
365 366
    ///automatically allocated map, of course.
366 367
    ///\return <tt> (*this) </tt>
367 368
    Bfs &reachedMap(ReachedMap &m)
368 369
    {
369 370
      if(local_reached) {
370 371
        delete _reached;
371 372
        local_reached=false;
372 373
      }
373 374
      _reached = &m;
374 375
      return *this;
375 376
    }
376 377

	
377 378
    ///Sets the map indicating the processed nodes.
378 379

	
379 380
    ///Sets the map indicating the processed nodes.
380 381
    ///If you don't use this function before calling \ref run(),
381 382
    ///it will allocate one. The destructor deallocates this
382 383
    ///automatically allocated map, of course.
383 384
    ///\return <tt> (*this) </tt>
384 385
    Bfs &processedMap(ProcessedMap &m)
385 386
    {
386 387
      if(local_processed) {
387 388
        delete _processed;
388 389
        local_processed=false;
389 390
      }
390 391
      _processed = &m;
391 392
      return *this;
392 393
    }
393 394

	
394 395
    ///Sets the map storing the distances calculated by the algorithm.
395 396

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

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

	
422 423
    ///@{
423 424

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

	
441 442
    ///Adds a new source node.
442 443

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

	
457 458
    ///Processes the next node.
458 459

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

	
483 484
    ///Processes the next node.
484 485

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

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

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

	
548 549
    ///Next node to be processed.
549 550

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

	
559 560
    ///\brief Returns \c false if there are nodes
560 561
    ///to be processed in the queue
561 562
    ///
562 563
    ///Returns \c false if there are nodes
563 564
    ///to be processed in the queue
564 565
    bool emptyQueue() { return _queue_tail==_queue_head; }
565 566
    ///Returns the number of the nodes to be processed.
566 567

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

	
570 571
    ///Executes the algorithm.
571 572

	
572 573
    ///Executes the algorithm.
573 574
    ///
574 575
    ///\pre init() must be called and at least one node should be added
575 576
    ///with addSource() before using this function.
576 577
    ///
577 578
    ///This method runs the %BFS algorithm from the root node(s)
578 579
    ///in order to
579 580
    ///compute the
580 581
    ///shortest path to each node. The algorithm computes
581 582
    ///- The shortest path tree.
582 583
    ///- The distance of each node from the root(s).
583 584
    void start()
584 585
    {
585 586
      while ( !emptyQueue() ) processNextNode();
586 587
    }
587 588

	
588 589
    ///Executes the algorithm until \c dest is reached.
589 590

	
590 591
    ///Executes the algorithm until \c dest is reached.
591 592
    ///
592 593
    ///\pre init() must be called and at least one node should be added
593 594
    ///with addSource() before using this function.
594 595
    ///
595 596
    ///This method runs the %BFS algorithm from the root node(s)
596 597
    ///in order to compute the shortest path to \c dest.
597 598
    ///The algorithm computes
598 599
    ///- The shortest path to \c  dest.
599 600
    ///- The distance of \c dest from the root(s).
600 601
    void start(Node dest)
601 602
    {
602 603
      bool reach = false;
603 604
      while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
604 605
    }
605 606

	
606 607
    ///Executes the algorithm until a condition is met.
607 608

	
608 609
    ///Executes the algorithm until a condition is met.
609 610
    ///
610 611
    ///\pre init() must be called and at least one node should be added
611 612
    ///with addSource() before using this function.
612 613
    ///
613 614
    ///\param nm must be a bool (or convertible) node map. The
614 615
    ///algorithm will stop when it reaches a node \c v with
615 616
    /// <tt>nm[v]</tt> true.
616 617
    ///
617 618
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
618 619
    ///\c INVALID if no such node was found.
619 620
    template<class NM>
620 621
    Node start(const NM &nm)
621 622
    {
622 623
      Node rnode = INVALID;
623 624
      while ( !emptyQueue() && rnode == INVALID ) {
624 625
        processNextNode(nm, rnode);
625 626
      }
626 627
      return rnode;
627 628
    }
628 629

	
629 630
    ///Runs %BFS algorithm from node \c s.
630 631

	
631 632
    ///This method runs the %BFS algorithm from a root node \c s
632 633
    ///in order to
633 634
    ///compute the
634 635
    ///shortest path to each node. The algorithm computes
635 636
    ///- The shortest path tree.
636 637
    ///- The distance of each node from the root.
637 638
    ///
638 639
    ///\note b.run(s) is just a shortcut of the following code.
639 640
    ///\code
640 641
    ///  b.init();
641 642
    ///  b.addSource(s);
642 643
    ///  b.start();
643 644
    ///\endcode
644 645
    void run(Node s) {
645 646
      init();
646 647
      addSource(s);
647 648
      start();
648 649
    }
649 650

	
650 651
    ///Finds the shortest path between \c s and \c t.
651 652

	
652 653
    ///Finds the shortest path between \c s and \c t.
653 654
    ///
654 655
    ///\return The length of the shortest s---t path if there exists one,
655 656
    ///0 otherwise.
656 657
    ///\note Apart from the return value, b.run(s) is
657 658
    ///just a shortcut of the following code.
658 659
    ///\code
659 660
    ///  b.init();
660 661
    ///  b.addSource(s);
661 662
    ///  b.start(t);
662 663
    ///\endcode
663 664
    int run(Node s,Node t) {
664 665
      init();
665 666
      addSource(s);
666 667
      start(t);
667 668
      return reached(t) ? _curr_dist : 0;
668 669
    }
669 670

	
670 671
    ///@}
671 672

	
672 673
    ///\name Query Functions
673 674
    ///The result of the %BFS algorithm can be obtained using these
674 675
    ///functions.\n
675 676
    ///Before the use of these functions,
676 677
    ///either run() or start() must be calleb.
677 678

	
678 679
    ///@{
679 680

	
680 681
    typedef PredMapPath<Digraph, PredMap> Path;
681 682

	
682 683
    ///Gives back the shortest path.
683 684

	
684 685
    ///Gives back the shortest path.
685 686
    ///\pre The \c t should be reachable from the source.
686 687
    Path path(Node t)
687 688
    {
688 689
      return Path(*G, *_pred, t);
689 690
    }
690 691

	
691 692
    ///The distance of a node from the root(s).
692 693

	
693 694
    ///Returns the distance of a node from the root(s).
694 695
    ///\pre \ref run() must be called before using this function.
695 696
    ///\warning If node \c v in unreachable from the root(s) the return value
696 697
    ///of this function is undefined.
697 698
    int dist(Node v) const { return (*_dist)[v]; }
698 699

	
699 700
    ///Returns the 'previous arc' of the shortest path tree.
700 701

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

	
712 713
    ///Returns the 'previous node' of the shortest path tree.
713 714

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

	
727 728
    ///Returns a reference to the NodeMap of distances.
728 729

	
729 730
    ///Returns a reference to the NodeMap of distances.
730 731
    ///\pre Either \ref run() or \ref init() must
731 732
    ///be called before using this function.
732 733
    const DistMap &distMap() const { return *_dist;}
733 734

	
734 735
    ///Returns a reference to the shortest path tree map.
735 736

	
736 737
    ///Returns a reference to the NodeMap of the arcs of the
737 738
    ///shortest path tree.
738 739
    ///\pre Either \ref run() or \ref init()
739 740
    ///must be called before using this function.
740 741
    const PredMap &predMap() const { return *_pred;}
741 742

	
742 743
    ///Checks if a node is reachable from the root.
743 744

	
744 745
    ///Returns \c true if \c v is reachable from the root.
745 746
    ///\warning The source nodes are indicated as unreached.
746 747
    ///\pre Either \ref run() or \ref start()
747 748
    ///must be called before using this function.
748 749
    ///
749 750
    bool reached(Node v) { return (*_reached)[v]; }
750 751

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

	
754 755
  ///Default traits class of Bfs function.
755 756

	
756 757
  ///Default traits class of Bfs function.
757 758
  ///\tparam GR Digraph type.
758 759
  template<class GR>
759 760
  struct BfsWizardDefaultTraits
760 761
  {
761 762
    ///The digraph type the algorithm runs on.
762 763
    typedef GR Digraph;
763 764
    ///\brief The type of the map that stores the last
764 765
    ///arcs of the shortest paths.
765 766
    ///
766 767
    ///The type of the map that stores the last
767 768
    ///arcs of the shortest paths.
768 769
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
769 770
    ///
770 771
    typedef NullMap<typename Digraph::Node,typename GR::Arc> PredMap;
771 772
    ///Instantiates a PredMap.
772 773

	
773 774
    ///This function instantiates a \ref PredMap.
774 775
    ///\param g is the digraph, to which we would like to define the PredMap.
775 776
    ///\todo The digraph alone may be insufficient to initialize
776 777
#ifdef DOXYGEN
777 778
    static PredMap *createPredMap(const GR &g)
778 779
#else
779 780
    static PredMap *createPredMap(const GR &)
780 781
#endif
781 782
    {
782 783
      return new PredMap();
783 784
    }
784 785

	
785 786
    ///The type of the map that indicates which nodes are processed.
786 787

	
787 788
    ///The type of the map that indicates which nodes are processed.
788 789
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
789 790
    ///\todo named parameter to set this type, function to read and write.
790 791
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
791 792
    ///Instantiates a ProcessedMap.
792 793

	
793 794
    ///This function instantiates a \ref ProcessedMap.
794 795
    ///\param g is the digraph, to which
795 796
    ///we would like to define the \ref ProcessedMap
796 797
#ifdef DOXYGEN
797 798
    static ProcessedMap *createProcessedMap(const GR &g)
798 799
#else
799 800
    static ProcessedMap *createProcessedMap(const GR &)
800 801
#endif
801 802
    {
802 803
      return new ProcessedMap();
803 804
    }
804 805
    ///The type of the map that indicates which nodes are reached.
805 806

	
806 807
    ///The type of the map that indicates which nodes are reached.
807 808
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
808 809
    ///\todo named parameter to set this type, function to read and write.
809 810
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
810 811
    ///Instantiates a ReachedMap.
811 812

	
812 813
    ///This function instantiates a \ref ReachedMap.
813 814
    ///\param G is the digraph, to which
814 815
    ///we would like to define the \ref ReachedMap.
815 816
    static ReachedMap *createReachedMap(const GR &G)
816 817
    {
817 818
      return new ReachedMap(G);
818 819
    }
819 820
    ///The type of the map that stores the dists of the nodes.
820 821

	
821 822
    ///The type of the map that stores the dists of the nodes.
822 823
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
823 824
    ///
824 825
    typedef NullMap<typename Digraph::Node,int> DistMap;
825 826
    ///Instantiates a DistMap.
826 827

	
827 828
    ///This function instantiates a \ref DistMap.
828
    ///\param g is the digraph, to which we would like to define the \ref DistMap
829
    ///\param g is the digraph, to which we would like to define
830
    ///the \ref DistMap
829 831
#ifdef DOXYGEN
830 832
    static DistMap *createDistMap(const GR &g)
831 833
#else
832 834
    static DistMap *createDistMap(const GR &)
833 835
#endif
834 836
    {
835 837
      return new DistMap();
836 838
    }
837 839
  };
838 840

	
839 841
  /// Default traits used by \ref BfsWizard
840 842

	
841 843
  /// To make it easier to use Bfs algorithm
842 844
  ///we have created a wizard class.
843 845
  /// This \ref BfsWizard class needs default traits,
844 846
  ///as well as the \ref Bfs class.
845 847
  /// The \ref BfsWizardBase is a class to be the default traits of the
846 848
  /// \ref BfsWizard class.
847 849
  template<class GR>
848 850
  class BfsWizardBase : public BfsWizardDefaultTraits<GR>
849 851
  {
850 852

	
851 853
    typedef BfsWizardDefaultTraits<GR> Base;
852 854
  protected:
853 855
    /// Type of the nodes in the digraph.
854 856
    typedef typename Base::Digraph::Node Node;
855 857

	
856 858
    /// Pointer to the underlying digraph.
857 859
    void *_g;
858 860
    ///Pointer to the map of reached nodes.
859 861
    void *_reached;
860 862
    ///Pointer to the map of processed nodes.
861 863
    void *_processed;
862 864
    ///Pointer to the map of predecessors arcs.
863 865
    void *_pred;
864 866
    ///Pointer to the map of distances.
865 867
    void *_dist;
866 868
    ///Pointer to the source node.
867 869
    Node _source;
868 870

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

	
872 874
    /// This constructor does not require parameters, therefore it initiates
873 875
    /// all of the attributes to default values (0, INVALID).
874 876
    BfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
875 877
                           _dist(0), _source(INVALID) {}
876 878

	
877 879
    /// Constructor.
878 880

	
879 881
    /// This constructor requires some parameters,
880 882
    /// listed in the parameters list.
881 883
    /// Others are initiated to 0.
882 884
    /// \param g is the initial value of  \ref _g
883 885
    /// \param s is the initial value of  \ref _source
884 886
    BfsWizardBase(const GR &g, Node s=INVALID) :
885 887
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
886 888
      _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
887 889

	
888 890
  };
889 891

	
890 892
  /// A class to make the usage of Bfs algorithm easier
891 893

	
892 894
  /// This class is created to make it easier to use Bfs algorithm.
893 895
  /// It uses the functions and features of the plain \ref Bfs,
894 896
  /// but it is much simpler to use it.
895 897
  ///
896 898
  /// Simplicity means that the way to change the types defined
897 899
  /// in the traits class is based on functions that returns the new class
898 900
  /// and not on templatable built-in classes.
899 901
  /// When using the plain \ref Bfs
900 902
  /// the new class with the modified type comes from
901 903
  /// the original class by using the ::
902 904
  /// operator. In the case of \ref BfsWizard only
903 905
  /// a function have to be called and it will
904 906
  /// return the needed class.
905 907
  ///
906 908
  /// It does not have own \ref run method. When its \ref run method is called
907 909
  /// it initiates a plain \ref Bfs class, and calls the \ref Bfs::run
908 910
  /// method of it.
909 911
  template<class TR>
910 912
  class BfsWizard : public TR
911 913
  {
912 914
    typedef TR Base;
913 915

	
914 916
    ///The type of the underlying digraph.
915 917
    typedef typename TR::Digraph Digraph;
916 918
    //\e
917 919
    typedef typename Digraph::Node Node;
918 920
    //\e
919 921
    typedef typename Digraph::NodeIt NodeIt;
920 922
    //\e
921 923
    typedef typename Digraph::Arc Arc;
922 924
    //\e
923 925
    typedef typename Digraph::OutArcIt OutArcIt;
924 926

	
925 927
    ///\brief The type of the map that stores
926 928
    ///the reached nodes
927 929
    typedef typename TR::ReachedMap ReachedMap;
928 930
    ///\brief The type of the map that stores
929 931
    ///the processed nodes
930 932
    typedef typename TR::ProcessedMap ProcessedMap;
931 933
    ///\brief The type of the map that stores the last
932 934
    ///arcs of the shortest paths.
933 935
    typedef typename TR::PredMap PredMap;
934 936
    ///The type of the map that stores the dists of the nodes.
935 937
    typedef typename TR::DistMap DistMap;
936 938

	
937 939
  public:
938 940
    /// Constructor.
939 941
    BfsWizard() : TR() {}
940 942

	
941 943
    /// Constructor that requires parameters.
942 944

	
943 945
    /// Constructor that requires parameters.
944 946
    /// These parameters will be the default values for the traits class.
945 947
    BfsWizard(const Digraph &g, Node s=INVALID) :
946 948
      TR(g,s) {}
947 949

	
948 950
    ///Copy constructor
949 951
    BfsWizard(const TR &b) : TR(b) {}
950 952

	
951 953
    ~BfsWizard() {}
952 954

	
953 955
    ///Runs Bfs algorithm from a given node.
954 956

	
955 957
    ///Runs Bfs algorithm from a given node.
956 958
    ///The node can be given by the \ref source function.
957 959
    void run()
958 960
    {
959 961
      if(Base::_source==INVALID) throw UninitializedParameter();
960 962
      Bfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
961 963
      if(Base::_reached)
962 964
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
963 965
      if(Base::_processed)
964 966
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
965 967
      if(Base::_pred)
966 968
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
967 969
      if(Base::_dist)
968 970
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
969 971
      alg.run(Base::_source);
970 972
    }
971 973

	
972 974
    ///Runs Bfs algorithm from the given node.
973 975

	
974 976
    ///Runs Bfs algorithm from the given node.
975 977
    ///\param s is the given source.
976 978
    void run(Node s)
977 979
    {
978 980
      Base::_source=s;
979 981
      run();
980 982
    }
981 983

	
982 984
    template<class T>
983 985
    struct DefPredMapBase : public Base {
984 986
      typedef T PredMap;
985 987
      static PredMap *createPredMap(const Digraph &) { return 0; };
986 988
      DefPredMapBase(const TR &b) : TR(b) {}
987 989
    };
988 990

	
989 991
    ///\brief \ref named-templ-param "Named parameter"
990 992
    ///function for setting PredMap
991 993
    ///
992 994
    /// \ref named-templ-param "Named parameter"
993 995
    ///function for setting PredMap
994 996
    ///
995 997
    template<class T>
996 998
    BfsWizard<DefPredMapBase<T> > predMap(const T &t)
997 999
    {
998 1000
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
999 1001
      return BfsWizard<DefPredMapBase<T> >(*this);
1000 1002
    }
1001 1003

	
1002 1004

	
1003 1005
    template<class T>
1004 1006
    struct DefReachedMapBase : public Base {
1005 1007
      typedef T ReachedMap;
1006 1008
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
1007 1009
      DefReachedMapBase(const TR &b) : TR(b) {}
1008 1010
    };
1009 1011

	
1010 1012
    ///\brief \ref named-templ-param "Named parameter"
1011 1013
    ///function for setting ReachedMap
1012 1014
    ///
1013 1015
    /// \ref named-templ-param "Named parameter"
1014 1016
    ///function for setting ReachedMap
1015 1017
    ///
1016 1018
    template<class T>
1017 1019
    BfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1018 1020
    {
1019 1021
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1020 1022
      return BfsWizard<DefReachedMapBase<T> >(*this);
1021 1023
    }
1022 1024

	
1023 1025

	
1024 1026
    template<class T>
1025 1027
    struct DefProcessedMapBase : public Base {
1026 1028
      typedef T ProcessedMap;
1027 1029
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1028 1030
      DefProcessedMapBase(const TR &b) : TR(b) {}
1029 1031
    };
1030 1032

	
1031 1033
    ///\brief \ref named-templ-param "Named parameter"
1032 1034
    ///function for setting ProcessedMap
1033 1035
    ///
1034 1036
    /// \ref named-templ-param "Named parameter"
1035 1037
    ///function for setting ProcessedMap
1036 1038
    ///
1037 1039
    template<class T>
1038 1040
    BfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1039 1041
    {
1040 1042
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1041 1043
      return BfsWizard<DefProcessedMapBase<T> >(*this);
1042 1044
    }
1043 1045

	
1044 1046

	
1045 1047
    template<class T>
1046 1048
    struct DefDistMapBase : public Base {
1047 1049
      typedef T DistMap;
1048 1050
      static DistMap *createDistMap(const Digraph &) { return 0; };
1049 1051
      DefDistMapBase(const TR &b) : TR(b) {}
1050 1052
    };
1051 1053

	
1052 1054
    ///\brief \ref named-templ-param "Named parameter"
1053 1055
    ///function for setting DistMap type
1054 1056
    ///
1055 1057
    /// \ref named-templ-param "Named parameter"
1056 1058
    ///function for setting DistMap type
1057 1059
    ///
1058 1060
    template<class T>
1059 1061
    BfsWizard<DefDistMapBase<T> > distMap(const T &t)
1060 1062
    {
1061 1063
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1062 1064
      return BfsWizard<DefDistMapBase<T> >(*this);
1063 1065
    }
1064 1066

	
1065 1067
    /// Sets the source node, from which the Bfs algorithm runs.
1066 1068

	
1067 1069
    /// Sets the source node, from which the Bfs algorithm runs.
1068 1070
    /// \param s is the source node.
1069 1071
    BfsWizard<TR> &source(Node s)
1070 1072
    {
1071 1073
      Base::_source=s;
1072 1074
      return *this;
1073 1075
    }
1074 1076

	
1075 1077
  };
1076 1078

	
1077 1079
  ///Function type interface for Bfs algorithm.
1078 1080

	
1079 1081
  /// \ingroup search
1080 1082
  ///Function type interface for Bfs algorithm.
1081 1083
  ///
1082 1084
  ///This function also has several
1083 1085
  ///\ref named-templ-func-param "named parameters",
1084 1086
  ///they are declared as the members of class \ref BfsWizard.
1085 1087
  ///The following
1086 1088
  ///example shows how to use these parameters.
1087 1089
  ///\code
1088 1090
  ///  bfs(g,source).predMap(preds).run();
1089 1091
  ///\endcode
1090 1092
  ///\warning Don't forget to put the \ref BfsWizard::run() "run()"
1091 1093
  ///to the end of the parameter list.
1092 1094
  ///\sa BfsWizard
1093 1095
  ///\sa Bfs
1094 1096
  template<class GR>
1095 1097
  BfsWizard<BfsWizardBase<GR> >
1096 1098
  bfs(const GR &g,typename GR::Node s=INVALID)
1097 1099
  {
1098 1100
    return BfsWizard<BfsWizardBase<GR> >(g,s);
1099 1101
  }
1100 1102

	
1101 1103
#ifdef DOXYGEN
1102 1104
  /// \brief Visitor class for bfs.
1103 1105
  ///
1104 1106
  /// This class defines the interface of the BfsVisit events, and
1105 1107
  /// it could be the base of a real Visitor class.
1106 1108
  template <typename _Digraph>
1107 1109
  struct BfsVisitor {
1108 1110
    typedef _Digraph Digraph;
1109 1111
    typedef typename Digraph::Arc Arc;
1110 1112
    typedef typename Digraph::Node Node;
1111 1113
    /// \brief Called when the arc reach a node.
1112 1114
    ///
1113 1115
    /// It is called when the bfs find an arc which target is not
1114 1116
    /// reached yet.
1115 1117
    void discover(const Arc& arc) {}
1116 1118
    /// \brief Called when the node reached first time.
1117 1119
    ///
1118 1120
    /// It is Called when the node reached first time.
1119 1121
    void reach(const Node& node) {}
1120 1122
    /// \brief Called when the arc examined but target of the arc
1121 1123
    /// already discovered.
1122 1124
    ///
1123 1125
    /// It called when the arc examined but the target of the arc
1124 1126
    /// already discovered.
1125 1127
    void examine(const Arc& arc) {}
1126 1128
    /// \brief Called for the source node of the bfs.
1127 1129
    ///
1128 1130
    /// It is called for the source node of the bfs.
1129 1131
    void start(const Node& node) {}
1130 1132
    /// \brief Called when the node processed.
1131 1133
    ///
1132 1134
    /// It is Called when the node processed.
1133 1135
    void process(const Node& node) {}
1134 1136
  };
1135 1137
#else
1136 1138
  template <typename _Digraph>
1137 1139
  struct BfsVisitor {
1138 1140
    typedef _Digraph Digraph;
1139 1141
    typedef typename Digraph::Arc Arc;
1140 1142
    typedef typename Digraph::Node Node;
1141 1143
    void discover(const Arc&) {}
1142 1144
    void reach(const Node&) {}
1143 1145
    void examine(const Arc&) {}
1144 1146
    void start(const Node&) {}
1145 1147
    void process(const Node&) {}
1146 1148

	
1147 1149
    template <typename _Visitor>
1148 1150
    struct Constraints {
1149 1151
      void constraints() {
1150 1152
        Arc arc;
1151 1153
        Node node;
1152 1154
        visitor.discover(arc);
1153 1155
        visitor.reach(node);
1154 1156
        visitor.examine(arc);
1155 1157
        visitor.start(node);
1156 1158
        visitor.process(node);
1157 1159
      }
1158 1160
      _Visitor& visitor;
1159 1161
    };
1160 1162
  };
1161 1163
#endif
1162 1164

	
1163 1165
  /// \brief Default traits class of BfsVisit class.
1164 1166
  ///
1165 1167
  /// Default traits class of BfsVisit class.
1166 1168
  /// \tparam _Digraph Digraph type.
1167 1169
  template<class _Digraph>
1168 1170
  struct BfsVisitDefaultTraits {
1169 1171

	
1170 1172
    /// \brief The digraph type the algorithm runs on.
1171 1173
    typedef _Digraph Digraph;
1172 1174

	
1173 1175
    /// \brief The type of the map that indicates which nodes are reached.
1174 1176
    ///
1175 1177
    /// The type of the map that indicates which nodes are reached.
1176 1178
    /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
1177 1179
    /// \todo named parameter to set this type, function to read and write.
1178 1180
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1179 1181

	
1180 1182
    /// \brief Instantiates a ReachedMap.
1181 1183
    ///
1182 1184
    /// This function instantiates a \ref ReachedMap.
1183 1185
    /// \param digraph is the digraph, to which
1184 1186
    /// we would like to define the \ref ReachedMap.
1185 1187
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1186 1188
      return new ReachedMap(digraph);
1187 1189
    }
1188 1190

	
1189 1191
  };
1190 1192

	
1191 1193
  /// \ingroup search
1192 1194
  ///
1193 1195
  /// \brief %BFS Visit algorithm class.
1194 1196
  ///
1195 1197
  /// This class provides an efficient implementation of the %BFS algorithm
1196 1198
  /// with visitor interface.
1197 1199
  ///
1198 1200
  /// The %BfsVisit class provides an alternative interface to the Bfs
1199 1201
  /// class. It works with callback mechanism, the BfsVisit object calls
1200 1202
  /// on every bfs event the \c Visitor class member functions.
1201 1203
  ///
1202
  /// \tparam _Digraph The digraph type the algorithm runs on. The default value is
1204
  /// \tparam _Digraph The digraph type the algorithm runs on.
1205
  /// The default value is
1203 1206
  /// \ref ListDigraph. The value of _Digraph is not used directly by Bfs, it
1204 1207
  /// is only passed to \ref BfsDefaultTraits.
1205 1208
  /// \tparam _Visitor The Visitor object for the algorithm. The
1206 1209
  /// \ref BfsVisitor "BfsVisitor<_Digraph>" is an empty Visitor which
1207 1210
  /// does not observe the Bfs events. If you want to observe the bfs
1208 1211
  /// events you should implement your own Visitor class.
1209 1212
  /// \tparam _Traits Traits class to set various data types used by the
1210 1213
  /// algorithm. The default traits class is
1211 1214
  /// \ref BfsVisitDefaultTraits "BfsVisitDefaultTraits<_Digraph>".
1212 1215
  /// See \ref BfsVisitDefaultTraits for the documentation of
1213 1216
  /// a Bfs visit traits class.
1214 1217
#ifdef DOXYGEN
1215 1218
  template <typename _Digraph, typename _Visitor, typename _Traits>
1216 1219
#else
1217 1220
  template <typename _Digraph = ListDigraph,
1218 1221
            typename _Visitor = BfsVisitor<_Digraph>,
1219 1222
            typename _Traits = BfsDefaultTraits<_Digraph> >
1220 1223
#endif
1221 1224
  class BfsVisit {
1222 1225
  public:
1223 1226

	
1224 1227
    /// \brief \ref Exception for uninitialized parameters.
1225 1228
    ///
1226 1229
    /// This error represents problems in the initialization
1227 1230
    /// of the parameters of the algorithms.
1228 1231
    class UninitializedParameter : public lemon::UninitializedParameter {
1229 1232
    public:
1230 1233
      virtual const char* what() const throw()
1231 1234
      {
1232 1235
        return "lemon::BfsVisit::UninitializedParameter";
1233 1236
      }
1234 1237
    };
1235 1238

	
1236 1239
    typedef _Traits Traits;
1237 1240

	
1238 1241
    typedef typename Traits::Digraph Digraph;
1239 1242

	
1240 1243
    typedef _Visitor Visitor;
1241 1244

	
1242 1245
    ///The type of the map indicating which nodes are reached.
1243 1246
    typedef typename Traits::ReachedMap ReachedMap;
1244 1247

	
1245 1248
  private:
1246 1249

	
1247 1250
    typedef typename Digraph::Node Node;
1248 1251
    typedef typename Digraph::NodeIt NodeIt;
1249 1252
    typedef typename Digraph::Arc Arc;
1250 1253
    typedef typename Digraph::OutArcIt OutArcIt;
1251 1254

	
1252 1255
    /// Pointer to the underlying digraph.
1253 1256
    const Digraph *_digraph;
1254 1257
    /// Pointer to the visitor object.
1255 1258
    Visitor *_visitor;
1256 1259
    ///Pointer to the map of reached status of the nodes.
1257 1260
    ReachedMap *_reached;
1258 1261
    ///Indicates if \ref _reached is locally allocated (\c true) or not.
1259 1262
    bool local_reached;
1260 1263

	
1261 1264
    std::vector<typename Digraph::Node> _list;
1262 1265
    int _list_front, _list_back;
1263 1266

	
1264 1267
    /// \brief Creates the maps if necessary.
1265 1268
    ///
1266 1269
    /// Creates the maps if necessary.
1267 1270
    void create_maps() {
1268 1271
      if(!_reached) {
1269 1272
        local_reached = true;
1270 1273
        _reached = Traits::createReachedMap(*_digraph);
1271 1274
      }
1272 1275
    }
1273 1276

	
1274 1277
  protected:
1275 1278

	
1276 1279
    BfsVisit() {}
1277 1280

	
1278 1281
  public:
1279 1282

	
1280 1283
    typedef BfsVisit Create;
1281 1284

	
1282 1285
    /// \name Named template parameters
1283 1286

	
1284 1287
    ///@{
1285 1288
    template <class T>
1286 1289
    struct DefReachedMapTraits : public Traits {
1287 1290
      typedef T ReachedMap;
1288 1291
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1289 1292
        throw UninitializedParameter();
1290 1293
      }
1291 1294
    };
1292 1295
    /// \brief \ref named-templ-param "Named parameter" for setting
1293 1296
    /// ReachedMap type
1294 1297
    ///
1295 1298
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1296 1299
    template <class T>
1297 1300
    struct DefReachedMap : public BfsVisit< Digraph, Visitor,
1298 1301
                                            DefReachedMapTraits<T> > {
1299 1302
      typedef BfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create;
1300 1303
    };
1301 1304
    ///@}
1302 1305

	
1303 1306
  public:
1304 1307

	
1305 1308
    /// \brief Constructor.
1306 1309
    ///
1307 1310
    /// Constructor.
1308 1311
    ///
1309 1312
    /// \param digraph the digraph the algorithm will run on.
1310 1313
    /// \param visitor The visitor of the algorithm.
1311 1314
    ///
1312 1315
    BfsVisit(const Digraph& digraph, Visitor& visitor)
1313 1316
      : _digraph(&digraph), _visitor(&visitor),
1314 1317
        _reached(0), local_reached(false) {}
1315 1318

	
1316 1319
    /// \brief Destructor.
1317 1320
    ///
1318 1321
    /// Destructor.
1319 1322
    ~BfsVisit() {
1320 1323
      if(local_reached) delete _reached;
1321 1324
    }
1322 1325

	
1323 1326
    /// \brief Sets the map indicating if a node is reached.
1324 1327
    ///
1325 1328
    /// Sets the map indicating if a node is reached.
1326 1329
    /// If you don't use this function before calling \ref run(),
1327 1330
    /// it will allocate one. The destuctor deallocates this
1328 1331
    /// automatically allocated map, of course.
1329 1332
    /// \return <tt> (*this) </tt>
1330 1333
    BfsVisit &reachedMap(ReachedMap &m) {
1331 1334
      if(local_reached) {
1332 1335
        delete _reached;
1333 1336
        local_reached = false;
1334 1337
      }
1335 1338
      _reached = &m;
1336 1339
      return *this;
1337 1340
    }
1338 1341

	
1339 1342
  public:
1340 1343
    /// \name Execution control
1341 1344
    /// The simplest way to execute the algorithm is to use
1342 1345
    /// one of the member functions called \c run(...).
1343 1346
    /// \n
1344 1347
    /// If you need more control on the execution,
1345 1348
    /// first you must call \ref init(), then you can adda source node
1346 1349
    /// with \ref addSource().
1347 1350
    /// Finally \ref start() will perform the actual path
1348 1351
    /// computation.
1349 1352

	
1350 1353
    /// @{
1351 1354
    /// \brief Initializes the internal data structures.
1352 1355
    ///
1353 1356
    /// Initializes the internal data structures.
1354 1357
    ///
1355 1358
    void init() {
1356 1359
      create_maps();
1357 1360
      _list.resize(countNodes(*_digraph));
1358 1361
      _list_front = _list_back = -1;
1359 1362
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1360 1363
        _reached->set(u, false);
1361 1364
      }
1362 1365
    }
1363 1366

	
1364 1367
    /// \brief Adds a new source node.
1365 1368
    ///
1366 1369
    /// Adds a new source node to the set of nodes to be processed.
1367 1370
    void addSource(Node s) {
1368 1371
      if(!(*_reached)[s]) {
1369 1372
          _reached->set(s,true);
1370 1373
          _visitor->start(s);
1371 1374
          _visitor->reach(s);
1372 1375
          _list[++_list_back] = s;
1373 1376
        }
1374 1377
    }
1375 1378

	
1376 1379
    /// \brief Processes the next node.
1377 1380
    ///
1378 1381
    /// Processes the next node.
1379 1382
    ///
1380 1383
    /// \return The processed node.
1381 1384
    ///
1382 1385
    /// \pre The queue must not be empty!
1383 1386
    Node processNextNode() {
1384 1387
      Node n = _list[++_list_front];
1385 1388
      _visitor->process(n);
1386 1389
      Arc e;
1387 1390
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1388 1391
        Node m = _digraph->target(e);
1389 1392
        if (!(*_reached)[m]) {
1390 1393
          _visitor->discover(e);
1391 1394
          _visitor->reach(m);
1392 1395
          _reached->set(m, true);
1393 1396
          _list[++_list_back] = m;
1394 1397
        } else {
1395 1398
          _visitor->examine(e);
1396 1399
        }
1397 1400
      }
1398 1401
      return n;
1399 1402
    }
1400 1403

	
1401 1404
    /// \brief Processes the next node.
1402 1405
    ///
1403 1406
    /// Processes the next node. And checks that the given target node
1404 1407
    /// is reached. If the target node is reachable from the processed
1405 1408
    /// node then the reached parameter will be set true. The reached
1406 1409
    /// parameter should be initially false.
1407 1410
    ///
1408 1411
    /// \param target The target node.
1409 1412
    /// \retval reach Indicates that the target node is reached.
1410 1413
    /// \return The processed node.
1411 1414
    ///
1412 1415
    /// \warning The queue must not be empty!
1413 1416
    Node processNextNode(Node target, bool& reach) {
1414 1417
      Node n = _list[++_list_front];
1415 1418
      _visitor->process(n);
1416 1419
      Arc e;
1417 1420
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1418 1421
        Node m = _digraph->target(e);
1419 1422
        if (!(*_reached)[m]) {
1420 1423
          _visitor->discover(e);
1421 1424
          _visitor->reach(m);
1422 1425
          _reached->set(m, true);
1423 1426
          _list[++_list_back] = m;
1424 1427
          reach = reach || (target == m);
1425 1428
        } else {
1426 1429
          _visitor->examine(e);
1427 1430
        }
1428 1431
      }
1429 1432
      return n;
1430 1433
    }
1431 1434

	
1432 1435
    /// \brief Processes the next node.
1433 1436
    ///
1434 1437
    /// Processes the next node. And checks that at least one of
1435 1438
    /// reached node has true value in the \c nm node map. If one node
1436 1439
    /// with true value is reachable from the processed node then the
1437 1440
    /// rnode parameter will be set to the first of such nodes.
1438 1441
    ///
1439 1442
    /// \param nm The node map of possible targets.
1440 1443
    /// \retval rnode The reached target node.
1441 1444
    /// \return The processed node.
1442 1445
    ///
1443 1446
    /// \warning The queue must not be empty!
1444 1447
    template <typename NM>
1445 1448
    Node processNextNode(const NM& nm, Node& rnode) {
1446 1449
      Node n = _list[++_list_front];
1447 1450
      _visitor->process(n);
1448 1451
      Arc e;
1449 1452
      for (_digraph->firstOut(e, n); e != INVALID; _digraph->nextOut(e)) {
1450 1453
        Node m = _digraph->target(e);
1451 1454
        if (!(*_reached)[m]) {
1452 1455
          _visitor->discover(e);
1453 1456
          _visitor->reach(m);
1454 1457
          _reached->set(m, true);
1455 1458
          _list[++_list_back] = m;
1456 1459
          if (nm[m] && rnode == INVALID) rnode = m;
1457 1460
        } else {
1458 1461
          _visitor->examine(e);
1459 1462
        }
1460 1463
      }
1461 1464
      return n;
1462 1465
    }
1463 1466

	
1464 1467
    /// \brief Next node to be processed.
1465 1468
    ///
1466 1469
    /// Next node to be processed.
1467 1470
    ///
1468 1471
    /// \return The next node to be processed or INVALID if the stack is
1469 1472
    /// empty.
1470 1473
    Node nextNode() {
1471 1474
      return _list_front != _list_back ? _list[_list_front + 1] : INVALID;
1472 1475
    }
1473 1476

	
1474 1477
    /// \brief Returns \c false if there are nodes
1475 1478
    /// to be processed in the queue
1476 1479
    ///
1477 1480
    /// Returns \c false if there are nodes
1478 1481
    /// to be processed in the queue
1479 1482
    bool emptyQueue() { return _list_front == _list_back; }
1480 1483

	
1481 1484
    /// \brief Returns the number of the nodes to be processed.
1482 1485
    ///
1483 1486
    /// Returns the number of the nodes to be processed in the queue.
1484 1487
    int queueSize() { return _list_back - _list_front; }
1485 1488

	
1486 1489
    /// \brief Executes the algorithm.
1487 1490
    ///
1488 1491
    /// Executes the algorithm.
1489 1492
    ///
1490 1493
    /// \pre init() must be called and at least one node should be added
1491 1494
    /// with addSource() before using this function.
1492 1495
    void start() {
1493 1496
      while ( !emptyQueue() ) processNextNode();
1494 1497
    }
1495 1498

	
1496 1499
    /// \brief Executes the algorithm until \c dest is reached.
1497 1500
    ///
1498 1501
    /// Executes the algorithm until \c dest is reached.
1499 1502
    ///
1500 1503
    /// \pre init() must be called and at least one node should be added
1501 1504
    /// with addSource() before using this function.
1502 1505
    void start(Node dest) {
1503 1506
      bool reach = false;
1504 1507
      while ( !emptyQueue() && !reach ) processNextNode(dest, reach);
1505 1508
    }
1506 1509

	
1507 1510
    /// \brief Executes the algorithm until a condition is met.
1508 1511
    ///
1509 1512
    /// Executes the algorithm until a condition is met.
1510 1513
    ///
1511 1514
    /// \pre init() must be called and at least one node should be added
1512 1515
    /// with addSource() before using this function.
1513 1516
    ///
1514 1517
    ///\param nm must be a bool (or convertible) node map. The
1515 1518
    ///algorithm will stop when it reaches a node \c v with
1516 1519
    /// <tt>nm[v]</tt> true.
1517 1520
    ///
1518 1521
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
1519 1522
    ///\c INVALID if no such node was found.
1520 1523
    template <typename NM>
1521 1524
    Node start(const NM &nm) {
1522 1525
      Node rnode = INVALID;
1523 1526
      while ( !emptyQueue() && rnode == INVALID ) {
1524 1527
        processNextNode(nm, rnode);
1525 1528
      }
1526 1529
      return rnode;
1527 1530
    }
1528 1531

	
1529 1532
    /// \brief Runs %BFSVisit algorithm from node \c s.
1530 1533
    ///
1531 1534
    /// This method runs the %BFS algorithm from a root node \c s.
1532 1535
    /// \note b.run(s) is just a shortcut of the following code.
1533 1536
    ///\code
1534 1537
    ///   b.init();
1535 1538
    ///   b.addSource(s);
1536 1539
    ///   b.start();
1537 1540
    ///\endcode
1538 1541
    void run(Node s) {
1539 1542
      init();
1540 1543
      addSource(s);
1541 1544
      start();
1542 1545
    }
1543 1546

	
1544 1547
    /// \brief Runs %BFSVisit algorithm to visit all nodes in the digraph.
1545 1548
    ///
1546 1549
    /// This method runs the %BFS algorithm in order to
1547 1550
    /// compute the %BFS path to each node. The algorithm computes
1548 1551
    /// - The %BFS tree.
1549 1552
    /// - The distance of each node from the root in the %BFS tree.
1550 1553
    ///
1551 1554
    ///\note b.run() is just a shortcut of the following code.
1552 1555
    ///\code
1553 1556
    ///  b.init();
1554 1557
    ///  for (NodeIt it(digraph); it != INVALID; ++it) {
1555 1558
    ///    if (!b.reached(it)) {
1556 1559
    ///      b.addSource(it);
1557 1560
    ///      b.start();
1558 1561
    ///    }
1559 1562
    ///  }
1560 1563
    ///\endcode
1561 1564
    void run() {
1562 1565
      init();
1563 1566
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1564 1567
        if (!reached(it)) {
1565 1568
          addSource(it);
1566 1569
          start();
1567 1570
        }
1568 1571
      }
1569 1572
    }
1570 1573
    ///@}
1571 1574

	
1572 1575
    /// \name Query Functions
1573 1576
    /// The result of the %BFS algorithm can be obtained using these
1574 1577
    /// functions.\n
1575 1578
    /// Before the use of these functions,
1576 1579
    /// either run() or start() must be called.
1577 1580
    ///@{
1578 1581

	
1579 1582
    /// \brief Checks if a node is reachable from the root.
1580 1583
    ///
1581 1584
    /// Returns \c true if \c v is reachable from the root(s).
1582 1585
    /// \warning The source nodes are inditated as unreachable.
1583 1586
    /// \pre Either \ref run() or \ref start()
1584 1587
    /// must be called before using this function.
1585 1588
    ///
1586 1589
    bool reached(Node v) { return (*_reached)[v]; }
1587 1590
    ///@}
1588 1591
  };
1589 1592

	
1590 1593
} //END OF NAMESPACE LEMON
1591 1594

	
1592 1595
#endif
1593 1596

	
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_CONCEPT_MAPS_H
20 20
#define LEMON_CONCEPT_MAPS_H
21 21

	
22 22
#include <lemon/bits/utility.h>
23 23
#include <lemon/concept_check.h>
24 24

	
25 25
///\ingroup concept
26 26
///\file
27 27
///\brief The concept of maps.
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  namespace concepts {
32 32

	
33 33
    /// \addtogroup concept
34 34
    /// @{
35 35

	
36 36
    /// Readable map concept
37 37

	
38 38
    /// Readable map concept.
39 39
    ///
40 40
    template<typename K, typename T>
41 41
    class ReadMap
42 42
    {
43 43
    public:
44 44
      /// The key type of the map.
45 45
      typedef K Key;
46
      /// The value type of the map. (The type of objects associated with the keys).
46
      /// \brief The value type of the map.
47
      /// (The type of objects associated with the keys).
47 48
      typedef T Value;
48 49

	
49 50
      /// Returns the value associated with the given key.
50 51
      Value operator[](const Key &) const {
51 52
        return *static_cast<Value *>(0);
52 53
      }
53 54

	
54 55
      template<typename _ReadMap>
55 56
      struct Constraints {
56 57
        void constraints() {
57 58
          Value val = m[key];
58 59
          val = m[key];
59 60
          typename _ReadMap::Value own_val = m[own_key];
60 61
          own_val = m[own_key];
61 62

	
62 63
          ignore_unused_variable_warning(key);
63 64
          ignore_unused_variable_warning(val);
64 65
          ignore_unused_variable_warning(own_key);
65 66
          ignore_unused_variable_warning(own_val);
66 67
        }
67 68
        const Key& key;
68 69
        const typename _ReadMap::Key& own_key;
69 70
        const _ReadMap& m;
70 71
      };
71 72

	
72 73
    };
73 74

	
74 75

	
75 76
    /// Writable map concept
76 77

	
77 78
    /// Writable map concept.
78 79
    ///
79 80
    template<typename K, typename T>
80 81
    class WriteMap
81 82
    {
82 83
    public:
83 84
      /// The key type of the map.
84 85
      typedef K Key;
85
      /// The value type of the map. (The type of objects associated with the keys).
86
      /// \brief The value type of the map.
87
      /// (The type of objects associated with the keys).
86 88
      typedef T Value;
87 89

	
88 90
      /// Sets the value associated with the given key.
89 91
      void set(const Key &, const Value &) {}
90 92

	
91 93
      /// Default constructor.
92 94
      WriteMap() {}
93 95

	
94 96
      template <typename _WriteMap>
95 97
      struct Constraints {
96 98
        void constraints() {
97 99
          m.set(key, val);
98 100
          m.set(own_key, own_val);
99 101

	
100 102
          ignore_unused_variable_warning(key);
101 103
          ignore_unused_variable_warning(val);
102 104
          ignore_unused_variable_warning(own_key);
103 105
          ignore_unused_variable_warning(own_val);
104 106
        }
105 107
        const Key& key;
106 108
        const Value& val;
107 109
        const typename _WriteMap::Key& own_key;
108 110
        const typename _WriteMap::Value& own_val;
109 111
        _WriteMap& m;
110 112
      };
111 113
    };
112 114

	
113 115
    /// Read/writable map concept
114 116

	
115 117
    /// Read/writable map concept.
116 118
    ///
117 119
    template<typename K, typename T>
118 120
    class ReadWriteMap : public ReadMap<K,T>,
119 121
                         public WriteMap<K,T>
120 122
    {
121 123
    public:
122 124
      /// The key type of the map.
123 125
      typedef K Key;
124
      /// The value type of the map. (The type of objects associated with the keys).
126
      /// \brief The value type of the map.
127
      /// (The type of objects associated with the keys).
125 128
      typedef T Value;
126 129

	
127 130
      /// Returns the value associated with the given key.
128 131
      Value operator[](const Key &) const {
129 132
        return *static_cast<Value *>(0);
130 133
      }
131 134

	
132 135
      /// Sets the value associated with the given key.
133 136
      void set(const Key &, const Value &) {}
134 137

	
135 138
      template<typename _ReadWriteMap>
136 139
      struct Constraints {
137 140
        void constraints() {
138 141
          checkConcept<ReadMap<K, T>, _ReadWriteMap >();
139 142
          checkConcept<WriteMap<K, T>, _ReadWriteMap >();
140 143
        }
141 144
      };
142 145
    };
143 146

	
144 147

	
145 148
    /// Dereferable map concept
146 149

	
147 150
    /// Dereferable map concept.
148 151
    ///
149 152
    template<typename K, typename T, typename R, typename CR>
150 153
    class ReferenceMap : public ReadWriteMap<K,T>
151 154
    {
152 155
    public:
153 156
      /// Tag for reference maps.
154 157
      typedef True ReferenceMapTag;
155 158
      /// The key type of the map.
156 159
      typedef K Key;
157
      /// The value type of the map. (The type of objects associated with the keys).
160
      /// \brief The value type of the map.
161
      /// (The type of objects associated with the keys).
158 162
      typedef T Value;
159 163
      /// The reference type of the map.
160 164
      typedef R Reference;
161 165
      /// The const reference type of the map.
162 166
      typedef CR ConstReference;
163 167

	
164 168
    public:
165 169

	
166 170
      /// Returns a reference to the value associated with the given key.
167 171
      Reference operator[](const Key &) {
168 172
        return *static_cast<Value *>(0);
169 173
      }
170 174

	
171 175
      /// Returns a const reference to the value associated with the given key.
172 176
      ConstReference operator[](const Key &) const {
173 177
        return *static_cast<Value *>(0);
174 178
      }
175 179

	
176 180
      /// Sets the value associated with the given key.
177 181
      void set(const Key &k,const Value &t) { operator[](k)=t; }
178 182

	
179 183
      template<typename _ReferenceMap>
180 184
      struct Constraints {
181 185
        void constraints() {
182 186
          checkConcept<ReadWriteMap<K, T>, _ReferenceMap >();
183 187
          ref = m[key];
184 188
          m[key] = val;
185 189
          m[key] = ref;
186 190
          m[key] = cref;
187 191
          own_ref = m[own_key];
188 192
          m[own_key] = own_val;
189 193
          m[own_key] = own_ref;
190 194
          m[own_key] = own_cref;
191 195
          m[key] = m[own_key];
192 196
          m[own_key] = m[key];
193 197
        }
194 198
        const Key& key;
195 199
        Value& val;
196 200
        Reference ref;
197 201
        ConstReference cref;
198 202
        const typename _ReferenceMap::Key& own_key;
199 203
        typename _ReferenceMap::Value& own_val;
200 204
        typename _ReferenceMap::Reference own_ref;
201 205
        typename _ReferenceMap::ConstReference own_cref;
202 206
        _ReferenceMap& m;
203 207
      };
204 208
    };
205 209

	
206 210
    // @}
207 211

	
208 212
  } //namespace concepts
209 213

	
210 214
} //namespace lemon
211 215

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

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

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

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

	
33 33
#include <lemon/concept_check.h>
34 34

	
35 35
namespace lemon {
36 36

	
37 37

	
38 38
  ///Default traits class of Dfs class.
39 39

	
40 40
  ///Default traits class of Dfs class.
41 41
  ///\tparam GR Digraph type.
42 42
  template<class GR>
43 43
  struct DfsDefaultTraits
44 44
  {
45 45
    ///The digraph type the algorithm runs on.
46 46
    typedef GR Digraph;
47 47
    ///\brief The type of the map that stores the last
48 48
    ///arcs of the %DFS paths.
49 49
    ///
50 50
    ///The type of the map that stores the last
51 51
    ///arcs of the %DFS paths.
52 52
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
53 53
    ///
54 54
    typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap;
55 55
    ///Instantiates a PredMap.
56 56

	
57 57
    ///This function instantiates a \ref PredMap.
58 58
    ///\param G is the digraph, to which we would like to define the PredMap.
59 59
    ///\todo The digraph alone may be insufficient to initialize
60 60
    static PredMap *createPredMap(const GR &G)
61 61
    {
62 62
      return new PredMap(G);
63 63
    }
64 64

	
65 65
    ///The type of the map that indicates which nodes are processed.
66 66

	
67 67
    ///The type of the map that indicates which nodes are processed.
68 68
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
69 69
    ///\todo named parameter to set this type, function to read and write.
70 70
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
71 71
    ///Instantiates a ProcessedMap.
72 72

	
73 73
    ///This function instantiates a \ref ProcessedMap.
74 74
    ///\param g is the digraph, to which
75 75
    ///we would like to define the \ref ProcessedMap
76 76
#ifdef DOXYGEN
77 77
    static ProcessedMap *createProcessedMap(const GR &g)
78 78
#else
79 79
    static ProcessedMap *createProcessedMap(const GR &)
80 80
#endif
81 81
    {
82 82
      return new ProcessedMap();
83 83
    }
84 84
    ///The type of the map that indicates which nodes are reached.
85 85

	
86 86
    ///The type of the map that indicates which nodes are reached.
87 87
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
88 88
    ///\todo named parameter to set this type, function to read and write.
89 89
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
90 90
    ///Instantiates a ReachedMap.
91 91

	
92 92
    ///This function instantiates a \ref ReachedMap.
93 93
    ///\param G is the digraph, to which
94 94
    ///we would like to define the \ref ReachedMap.
95 95
    static ReachedMap *createReachedMap(const GR &G)
96 96
    {
97 97
      return new ReachedMap(G);
98 98
    }
99 99
    ///The type of the map that stores the dists of the nodes.
100 100

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

	
107 107
    ///This function instantiates a \ref DistMap.
108
    ///\param G is the digraph, to which we would like to define the \ref DistMap
108
    ///\param G is the digraph, to which we would like to define
109
    ///the \ref DistMap
109 110
    static DistMap *createDistMap(const GR &G)
110 111
    {
111 112
      return new DistMap(G);
112 113
    }
113 114
  };
114 115

	
115 116
  ///%DFS algorithm class.
116 117

	
117 118
  ///\ingroup search
118 119
  ///This class provides an efficient implementation of the %DFS algorithm.
119 120
  ///
120 121
  ///\tparam GR The digraph type the algorithm runs on. The default value is
121 122
  ///\ref ListDigraph. The value of GR is not used directly by Dfs, it
122 123
  ///is only passed to \ref DfsDefaultTraits.
123 124
  ///\tparam TR Traits class to set various data types used by the algorithm.
124 125
  ///The default traits class is
125 126
  ///\ref DfsDefaultTraits "DfsDefaultTraits<GR>".
126 127
  ///See \ref DfsDefaultTraits for the documentation of
127 128
  ///a Dfs traits class.
128 129
#ifdef DOXYGEN
129 130
  template <typename GR,
130 131
            typename TR>
131 132
#else
132 133
  template <typename GR=ListDigraph,
133 134
            typename TR=DfsDefaultTraits<GR> >
134 135
#endif
135 136
  class Dfs {
136 137
  public:
137 138
    /**
138 139
     * \brief \ref Exception for uninitialized parameters.
139 140
     *
140 141
     * This error represents problems in the initialization
141 142
     * of the parameters of the algorithms.
142 143
     */
143 144
    class UninitializedParameter : public lemon::UninitializedParameter {
144 145
    public:
145 146
      virtual const char* what() const throw() {
146 147
        return "lemon::Dfs::UninitializedParameter";
147 148
      }
148 149
    };
149 150

	
150 151
    typedef TR Traits;
151 152
    ///The type of the underlying digraph.
152 153
    typedef typename TR::Digraph Digraph;
153 154
    ///\e
154 155
    typedef typename Digraph::Node Node;
155 156
    ///\e
156 157
    typedef typename Digraph::NodeIt NodeIt;
157 158
    ///\e
158 159
    typedef typename Digraph::Arc Arc;
159 160
    ///\e
160 161
    typedef typename Digraph::OutArcIt OutArcIt;
161 162

	
162 163
    ///\brief The type of the map that stores the last
163 164
    ///arcs of the %DFS paths.
164 165
    typedef typename TR::PredMap PredMap;
165 166
    ///The type of the map indicating which nodes are reached.
166 167
    typedef typename TR::ReachedMap ReachedMap;
167 168
    ///The type of the map indicating which nodes are processed.
168 169
    typedef typename TR::ProcessedMap ProcessedMap;
169 170
    ///The type of the map that stores the dists of the nodes.
170 171
    typedef typename TR::DistMap DistMap;
171 172
  private:
172 173
    /// Pointer to the underlying digraph.
173 174
    const Digraph *G;
174 175
    ///Pointer to the map of predecessors arcs.
175 176
    PredMap *_pred;
176 177
    ///Indicates if \ref _pred is locally allocated (\c true) or not.
177 178
    bool local_pred;
178 179
    ///Pointer to the map of distances.
179 180
    DistMap *_dist;
180 181
    ///Indicates if \ref _dist is locally allocated (\c true) or not.
181 182
    bool local_dist;
182 183
    ///Pointer to the map of reached status of the nodes.
183 184
    ReachedMap *_reached;
184 185
    ///Indicates if \ref _reached is locally allocated (\c true) or not.
185 186
    bool local_reached;
186 187
    ///Pointer to the map of processed status of the nodes.
187 188
    ProcessedMap *_processed;
188 189
    ///Indicates if \ref _processed is locally allocated (\c true) or not.
189 190
    bool local_processed;
190 191

	
191 192
    std::vector<typename Digraph::OutArcIt> _stack;
192 193
    int _stack_head;
193 194

	
194 195
    ///Creates the maps if necessary.
195 196

	
196 197
    ///\todo Better memory allocation (instead of new).
197 198
    void create_maps()
198 199
    {
199 200
      if(!_pred) {
200 201
        local_pred = true;
201 202
        _pred = Traits::createPredMap(*G);
202 203
      }
203 204
      if(!_dist) {
204 205
        local_dist = true;
205 206
        _dist = Traits::createDistMap(*G);
206 207
      }
207 208
      if(!_reached) {
208 209
        local_reached = true;
209 210
        _reached = Traits::createReachedMap(*G);
210 211
      }
211 212
      if(!_processed) {
212 213
        local_processed = true;
213 214
        _processed = Traits::createProcessedMap(*G);
214 215
      }
215 216
    }
216 217

	
217 218
  protected:
218 219

	
219 220
    Dfs() {}
220 221

	
221 222
  public:
222 223

	
223 224
    typedef Dfs Create;
224 225

	
225 226
    ///\name Named template parameters
226 227

	
227 228
    ///@{
228 229

	
229 230
    template <class T>
230 231
    struct DefPredMapTraits : public Traits {
231 232
      typedef T PredMap;
232 233
      static PredMap *createPredMap(const Digraph &G)
233 234
      {
234 235
        throw UninitializedParameter();
235 236
      }
236 237
    };
237 238
    ///\brief \ref named-templ-param "Named parameter" for setting
238 239
    ///PredMap type
239 240
    ///
240 241
    ///\ref named-templ-param "Named parameter" for setting PredMap type
241 242
    ///
242 243
    template <class T>
243 244
    struct DefPredMap : public Dfs<Digraph, DefPredMapTraits<T> > {
244 245
      typedef Dfs<Digraph, DefPredMapTraits<T> > Create;
245 246
    };
246 247

	
247 248

	
248 249
    template <class T>
249 250
    struct DefDistMapTraits : public Traits {
250 251
      typedef T DistMap;
251 252
      static DistMap *createDistMap(const Digraph &)
252 253
      {
253 254
        throw UninitializedParameter();
254 255
      }
255 256
    };
256 257
    ///\brief \ref named-templ-param "Named parameter" for setting
257 258
    ///DistMap type
258 259
    ///
259 260
    ///\ref named-templ-param "Named parameter" for setting DistMap
260 261
    ///type
261 262
    template <class T>
262 263
    struct DefDistMap {
263 264
      typedef Dfs<Digraph, DefDistMapTraits<T> > Create;
264 265
    };
265 266

	
266 267
    template <class T>
267 268
    struct DefReachedMapTraits : public Traits {
268 269
      typedef T ReachedMap;
269 270
      static ReachedMap *createReachedMap(const Digraph &)
270 271
      {
271 272
        throw UninitializedParameter();
272 273
      }
273 274
    };
274 275
    ///\brief \ref named-templ-param "Named parameter" for setting
275 276
    ///ReachedMap type
276 277
    ///
277 278
    ///\ref named-templ-param "Named parameter" for setting ReachedMap type
278 279
    ///
279 280
    template <class T>
280 281
    struct DefReachedMap : public Dfs< Digraph, DefReachedMapTraits<T> > {
281 282
      typedef Dfs< Digraph, DefReachedMapTraits<T> > Create;
282 283
    };
283 284

	
284 285
    template <class T>
285 286
    struct DefProcessedMapTraits : public Traits {
286 287
      typedef T ProcessedMap;
287 288
      static ProcessedMap *createProcessedMap(const Digraph &)
288 289
      {
289 290
        throw UninitializedParameter();
290 291
      }
291 292
    };
292 293
    ///\brief \ref named-templ-param "Named parameter" for setting
293 294
    ///ProcessedMap type
294 295
    ///
295 296
    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
296 297
    ///
297 298
    template <class T>
298 299
    struct DefProcessedMap : public Dfs< Digraph, DefProcessedMapTraits<T> > {
299 300
      typedef Dfs< Digraph, DefProcessedMapTraits<T> > Create;
300 301
    };
301 302

	
302 303
    struct DefDigraphProcessedMapTraits : public Traits {
303 304
      typedef typename Digraph::template NodeMap<bool> ProcessedMap;
304 305
      static ProcessedMap *createProcessedMap(const Digraph &G)
305 306
      {
306 307
        return new ProcessedMap(G);
307 308
      }
308 309
    };
309 310
    ///\brief \ref named-templ-param "Named parameter"
310 311
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
311 312
    ///
312 313
    ///\ref named-templ-param "Named parameter"
313 314
    ///for setting the ProcessedMap type to be Digraph::NodeMap<bool>.
314 315
    ///If you don't set it explicitely, it will be automatically allocated.
315 316
    template <class T>
316 317
    class DefProcessedMapToBeDefaultMap :
317 318
      public Dfs< Digraph, DefDigraphProcessedMapTraits> {
318 319
      typedef Dfs< Digraph, DefDigraphProcessedMapTraits> Create;
319 320
    };
320 321

	
321 322
    ///@}
322 323

	
323 324
  public:
324 325

	
325 326
    ///Constructor.
326 327

	
327 328
    ///\param _G the digraph the algorithm will run on.
328 329
    ///
329 330
    Dfs(const Digraph& _G) :
330 331
      G(&_G),
331 332
      _pred(NULL), local_pred(false),
332 333
      _dist(NULL), local_dist(false),
333 334
      _reached(NULL), local_reached(false),
334 335
      _processed(NULL), local_processed(false)
335 336
    { }
336 337

	
337 338
    ///Destructor.
338 339
    ~Dfs()
339 340
    {
340 341
      if(local_pred) delete _pred;
341 342
      if(local_dist) delete _dist;
342 343
      if(local_reached) delete _reached;
343 344
      if(local_processed) delete _processed;
344 345
    }
345 346

	
346 347
    ///Sets the map storing the predecessor arcs.
347 348

	
348 349
    ///Sets the map storing the predecessor arcs.
349 350
    ///If you don't use this function before calling \ref run(),
350 351
    ///it will allocate one. The destuctor deallocates this
351 352
    ///automatically allocated map, of course.
352 353
    ///\return <tt> (*this) </tt>
353 354
    Dfs &predMap(PredMap &m)
354 355
    {
355 356
      if(local_pred) {
356 357
        delete _pred;
357 358
        local_pred=false;
358 359
      }
359 360
      _pred = &m;
360 361
      return *this;
361 362
    }
362 363

	
363 364
    ///Sets the map storing the distances calculated by the algorithm.
364 365

	
365 366
    ///Sets the map storing the distances calculated by the algorithm.
366 367
    ///If you don't use this function before calling \ref run(),
367 368
    ///it will allocate one. The destuctor deallocates this
368 369
    ///automatically allocated map, of course.
369 370
    ///\return <tt> (*this) </tt>
370 371
    Dfs &distMap(DistMap &m)
371 372
    {
372 373
      if(local_dist) {
373 374
        delete _dist;
374 375
        local_dist=false;
375 376
      }
376 377
      _dist = &m;
377 378
      return *this;
378 379
    }
379 380

	
380 381
    ///Sets the map indicating if a node is reached.
381 382

	
382 383
    ///Sets the map indicating if a node is reached.
383 384
    ///If you don't use this function before calling \ref run(),
384 385
    ///it will allocate one. The destuctor deallocates this
385 386
    ///automatically allocated map, of course.
386 387
    ///\return <tt> (*this) </tt>
387 388
    Dfs &reachedMap(ReachedMap &m)
388 389
    {
389 390
      if(local_reached) {
390 391
        delete _reached;
391 392
        local_reached=false;
392 393
      }
393 394
      _reached = &m;
394 395
      return *this;
395 396
    }
396 397

	
397 398
    ///Sets the map indicating if a node is processed.
398 399

	
399 400
    ///Sets the map indicating if a node is processed.
400 401
    ///If you don't use this function before calling \ref run(),
401 402
    ///it will allocate one. The destuctor deallocates this
402 403
    ///automatically allocated map, of course.
403 404
    ///\return <tt> (*this) </tt>
404 405
    Dfs &processedMap(ProcessedMap &m)
405 406
    {
406 407
      if(local_processed) {
407 408
        delete _processed;
408 409
        local_processed=false;
409 410
      }
410 411
      _processed = &m;
411 412
      return *this;
412 413
    }
413 414

	
414 415
  public:
415 416
    ///\name Execution control
416 417
    ///The simplest way to execute the algorithm is to use
417 418
    ///one of the member functions called \c run(...).
418 419
    ///\n
419 420
    ///If you need more control on the execution,
420 421
    ///first you must call \ref init(), then you can add a source node
421 422
    ///with \ref addSource().
422 423
    ///Finally \ref start() will perform the actual path
423 424
    ///computation.
424 425

	
425 426
    ///@{
426 427

	
427 428
    ///Initializes the internal data structures.
428 429

	
429 430
    ///Initializes the internal data structures.
430 431
    ///
431 432
    void init()
432 433
    {
433 434
      create_maps();
434 435
      _stack.resize(countNodes(*G));
435 436
      _stack_head=-1;
436 437
      for ( NodeIt u(*G) ; u!=INVALID ; ++u ) {
437 438
        _pred->set(u,INVALID);
438 439
        // _predNode->set(u,INVALID);
439 440
        _reached->set(u,false);
440 441
        _processed->set(u,false);
441 442
      }
442 443
    }
443 444

	
444 445
    ///Adds a new source node.
445 446

	
446 447
    ///Adds a new source node to the set of nodes to be processed.
447 448
    ///
448 449
    ///\warning dists are wrong (or at least strange)
449 450
    ///in case of multiple sources.
450 451
    void addSource(Node s)
451 452
    {
452 453
      if(!(*_reached)[s])
453 454
        {
454 455
          _reached->set(s,true);
455 456
          _pred->set(s,INVALID);
456 457
          OutArcIt e(*G,s);
457 458
          if(e!=INVALID) {
458 459
            _stack[++_stack_head]=e;
459 460
            _dist->set(s,_stack_head);
460 461
          }
461 462
          else {
462 463
            _processed->set(s,true);
463 464
            _dist->set(s,0);
464 465
          }
465 466
        }
466 467
    }
467 468

	
468 469
    ///Processes the next arc.
469 470

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

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

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

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

	
522 523
    ///Executes the algorithm.
523 524

	
524 525
    ///Executes the algorithm.
525 526
    ///
526 527
    ///\pre init() must be called and at least one node should be added
527 528
    ///with addSource() before using this function.
528 529
    ///
529 530
    ///This method runs the %DFS algorithm from the root node(s)
530 531
    ///in order to
531 532
    ///compute the
532 533
    ///%DFS path to each node. The algorithm computes
533 534
    ///- The %DFS tree.
534 535
    ///- The distance of each node from the root(s) in the %DFS tree.
535 536
    ///
536 537
    void start()
537 538
    {
538 539
      while ( !emptyQueue() ) processNextArc();
539 540
    }
540 541

	
541 542
    ///Executes the algorithm until \c dest is reached.
542 543

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

	
561 562
    ///Executes the algorithm until a condition is met.
562 563

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

	
584 585
    ///Runs %DFS algorithm to visit all nodes in the digraph.
585 586

	
586 587
    ///This method runs the %DFS algorithm in order to
587 588
    ///compute the
588 589
    ///%DFS path to each node. The algorithm computes
589 590
    ///- The %DFS tree.
590 591
    ///- The distance of each node from the root in the %DFS tree.
591 592
    ///
592 593
    ///\note d.run() is just a shortcut of the following code.
593 594
    ///\code
594 595
    ///  d.init();
595 596
    ///  for (NodeIt it(digraph); it != INVALID; ++it) {
596 597
    ///    if (!d.reached(it)) {
597 598
    ///      d.addSource(it);
598 599
    ///      d.start();
599 600
    ///    }
600 601
    ///  }
601 602
    ///\endcode
602 603
    void run() {
603 604
      init();
604 605
      for (NodeIt it(*G); it != INVALID; ++it) {
605 606
        if (!reached(it)) {
606 607
          addSource(it);
607 608
          start();
608 609
        }
609 610
      }
610 611
    }
611 612

	
612 613
    ///Runs %DFS algorithm from node \c s.
613 614

	
614 615
    ///This method runs the %DFS algorithm from a root node \c s
615 616
    ///in order to
616 617
    ///compute the
617 618
    ///%DFS path to each node. The algorithm computes
618 619
    ///- The %DFS tree.
619 620
    ///- The distance of each node from the root in the %DFS tree.
620 621
    ///
621 622
    ///\note d.run(s) is just a shortcut of the following code.
622 623
    ///\code
623 624
    ///  d.init();
624 625
    ///  d.addSource(s);
625 626
    ///  d.start();
626 627
    ///\endcode
627 628
    void run(Node s) {
628 629
      init();
629 630
      addSource(s);
630 631
      start();
631 632
    }
632 633

	
633 634
    ///Finds the %DFS path between \c s and \c t.
634 635

	
635 636
    ///Finds the %DFS path between \c s and \c t.
636 637
    ///
637 638
    ///\return The length of the %DFS s---t path if there exists one,
638 639
    ///0 otherwise.
639 640
    ///\note Apart from the return value, d.run(s,t) is
640 641
    ///just a shortcut of the following code.
641 642
    ///\code
642 643
    ///  d.init();
643 644
    ///  d.addSource(s);
644 645
    ///  d.start(t);
645 646
    ///\endcode
646 647
    int run(Node s,Node t) {
647 648
      init();
648 649
      addSource(s);
649 650
      start(t);
650 651
      return reached(t)?_stack_head+1:0;
651 652
    }
652 653

	
653 654
    ///@}
654 655

	
655 656
    ///\name Query Functions
656 657
    ///The result of the %DFS algorithm can be obtained using these
657 658
    ///functions.\n
658 659
    ///Before the use of these functions,
659 660
    ///either run() or start() must be called.
660 661

	
661 662
    ///@{
662 663

	
663 664
    typedef PredMapPath<Digraph, PredMap> Path;
664 665

	
665 666
    ///Gives back the shortest path.
666 667

	
667 668
    ///Gives back the shortest path.
668 669
    ///\pre The \c t should be reachable from the source.
669 670
    Path path(Node t)
670 671
    {
671 672
      return Path(*G, *_pred, t);
672 673
    }
673 674

	
674 675
    ///The distance of a node from the root(s).
675 676

	
676 677
    ///Returns the distance of a node from the root(s).
677 678
    ///\pre \ref run() must be called before using this function.
678 679
    ///\warning If node \c v is unreachable from the root(s) then the return
679 680
    ///value of this funcion is undefined.
680 681
    int dist(Node v) const { return (*_dist)[v]; }
681 682

	
682 683
    ///Returns the 'previous arc' of the %DFS tree.
683 684

	
684 685
    ///For a node \c v it returns the 'previous arc'
685 686
    ///of the %DFS path,
686 687
    ///i.e. it returns the last arc of a %DFS path from the root(s) to \c
687 688
    ///v. It is \ref INVALID
688 689
    ///if \c v is unreachable from the root(s) or \c v is a root. The
689 690
    ///%DFS tree used here is equal to the %DFS tree used in
690 691
    ///\ref predNode().
691 692
    ///\pre Either \ref run() or \ref start() must be called before using
692 693
    ///this function.
693 694
    Arc predArc(Node v) const { return (*_pred)[v];}
694 695

	
695 696
    ///Returns the 'previous node' of the %DFS tree.
696 697

	
697 698
    ///For a node \c v it returns the 'previous node'
698 699
    ///of the %DFS tree,
699 700
    ///i.e. it returns the last but one node from a %DFS path from the
700 701
    ///root(s) to \c v.
701 702
    ///It is INVALID if \c v is unreachable from the root(s) or
702 703
    ///if \c v itself a root.
703 704
    ///The %DFS tree used here is equal to the %DFS
704 705
    ///tree used in \ref predArc().
705 706
    ///\pre Either \ref run() or \ref start() must be called before
706 707
    ///using this function.
707 708
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
708 709
                                  G->source((*_pred)[v]); }
709 710

	
710 711
    ///Returns a reference to the NodeMap of distances.
711 712

	
712 713
    ///Returns a reference to the NodeMap of distances.
713 714
    ///\pre Either \ref run() or \ref init() must
714 715
    ///be called before using this function.
715 716
    const DistMap &distMap() const { return *_dist;}
716 717

	
717 718
    ///Returns a reference to the %DFS arc-tree map.
718 719

	
719 720
    ///Returns a reference to the NodeMap of the arcs of the
720 721
    ///%DFS tree.
721 722
    ///\pre Either \ref run() or \ref init()
722 723
    ///must be called before using this function.
723 724
    const PredMap &predMap() const { return *_pred;}
724 725

	
725 726
    ///Checks if a node is reachable from the root.
726 727

	
727 728
    ///Returns \c true if \c v is reachable from the root(s).
728 729
    ///\warning The source nodes are inditated as unreachable.
729 730
    ///\pre Either \ref run() or \ref start()
730 731
    ///must be called before using this function.
731 732
    ///
732 733
    bool reached(Node v) { return (*_reached)[v]; }
733 734

	
734 735
    ///@}
735 736
  };
736 737

	
737 738
  ///Default traits class of Dfs function.
738 739

	
739 740
  ///Default traits class of Dfs function.
740 741
  ///\tparam GR Digraph type.
741 742
  template<class GR>
742 743
  struct DfsWizardDefaultTraits
743 744
  {
744 745
    ///The digraph type the algorithm runs on.
745 746
    typedef GR Digraph;
746 747
    ///\brief The type of the map that stores the last
747 748
    ///arcs of the %DFS paths.
748 749
    ///
749 750
    ///The type of the map that stores the last
750 751
    ///arcs of the %DFS paths.
751 752
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
752 753
    ///
753 754
    typedef NullMap<typename Digraph::Node,typename GR::Arc> PredMap;
754 755
    ///Instantiates a PredMap.
755 756

	
756 757
    ///This function instantiates a \ref PredMap.
757 758
    ///\param g is the digraph, to which we would like to define the PredMap.
758 759
    ///\todo The digraph alone may be insufficient to initialize
759 760
#ifdef DOXYGEN
760 761
    static PredMap *createPredMap(const GR &g)
761 762
#else
762 763
    static PredMap *createPredMap(const GR &)
763 764
#endif
764 765
    {
765 766
      return new PredMap();
766 767
    }
767 768

	
768 769
    ///The type of the map that indicates which nodes are processed.
769 770

	
770 771
    ///The type of the map that indicates which nodes are processed.
771 772
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
772 773
    ///\todo named parameter to set this type, function to read and write.
773 774
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
774 775
    ///Instantiates a ProcessedMap.
775 776

	
776 777
    ///This function instantiates a \ref ProcessedMap.
777 778
    ///\param g is the digraph, to which
778 779
    ///we would like to define the \ref ProcessedMap
779 780
#ifdef DOXYGEN
780 781
    static ProcessedMap *createProcessedMap(const GR &g)
781 782
#else
782 783
    static ProcessedMap *createProcessedMap(const GR &)
783 784
#endif
784 785
    {
785 786
      return new ProcessedMap();
786 787
    }
787 788
    ///The type of the map that indicates which nodes are reached.
788 789

	
789 790
    ///The type of the map that indicates which nodes are reached.
790 791
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
791 792
    ///\todo named parameter to set this type, function to read and write.
792 793
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
793 794
    ///Instantiates a ReachedMap.
794 795

	
795 796
    ///This function instantiates a \ref ReachedMap.
796 797
    ///\param G is the digraph, to which
797 798
    ///we would like to define the \ref ReachedMap.
798 799
    static ReachedMap *createReachedMap(const GR &G)
799 800
    {
800 801
      return new ReachedMap(G);
801 802
    }
802 803
    ///The type of the map that stores the dists of the nodes.
803 804

	
804 805
    ///The type of the map that stores the dists of the nodes.
805 806
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
806 807
    ///
807 808
    typedef NullMap<typename Digraph::Node,int> DistMap;
808 809
    ///Instantiates a DistMap.
809 810

	
810 811
    ///This function instantiates a \ref DistMap.
811
    ///\param g is the digraph, to which we would like to define the \ref DistMap
812
    ///\param g is the digraph, to which we would like to define
813
    ///the \ref DistMap
812 814
#ifdef DOXYGEN
813 815
    static DistMap *createDistMap(const GR &g)
814 816
#else
815 817
    static DistMap *createDistMap(const GR &)
816 818
#endif
817 819
    {
818 820
      return new DistMap();
819 821
    }
820 822
  };
821 823

	
822 824
  /// Default traits used by \ref DfsWizard
823 825

	
824 826
  /// To make it easier to use Dfs algorithm
825 827
  ///we have created a wizard class.
826 828
  /// This \ref DfsWizard class needs default traits,
827 829
  ///as well as the \ref Dfs class.
828 830
  /// The \ref DfsWizardBase is a class to be the default traits of the
829 831
  /// \ref DfsWizard class.
830 832
  template<class GR>
831 833
  class DfsWizardBase : public DfsWizardDefaultTraits<GR>
832 834
  {
833 835

	
834 836
    typedef DfsWizardDefaultTraits<GR> Base;
835 837
  protected:
836 838
    /// Type of the nodes in the digraph.
837 839
    typedef typename Base::Digraph::Node Node;
838 840

	
839 841
    /// Pointer to the underlying digraph.
840 842
    void *_g;
841 843
    ///Pointer to the map of reached nodes.
842 844
    void *_reached;
843 845
    ///Pointer to the map of processed nodes.
844 846
    void *_processed;
845 847
    ///Pointer to the map of predecessors arcs.
846 848
    void *_pred;
847 849
    ///Pointer to the map of distances.
848 850
    void *_dist;
849 851
    ///Pointer to the source node.
850 852
    Node _source;
851 853

	
852 854
    public:
853 855
    /// Constructor.
854 856

	
855 857
    /// This constructor does not require parameters, therefore it initiates
856 858
    /// all of the attributes to default values (0, INVALID).
857 859
    DfsWizardBase() : _g(0), _reached(0), _processed(0), _pred(0),
858 860
                           _dist(0), _source(INVALID) {}
859 861

	
860 862
    /// Constructor.
861 863

	
862 864
    /// This constructor requires some parameters,
863 865
    /// listed in the parameters list.
864 866
    /// Others are initiated to 0.
865 867
    /// \param g is the initial value of  \ref _g
866 868
    /// \param s is the initial value of  \ref _source
867 869
    DfsWizardBase(const GR &g, Node s=INVALID) :
868 870
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
869 871
      _reached(0), _processed(0), _pred(0), _dist(0), _source(s) {}
870 872

	
871 873
  };
872 874

	
873 875
  /// A class to make the usage of the Dfs algorithm easier
874 876

	
875 877
  /// This class is created to make it easier to use the Dfs algorithm.
876 878
  /// It uses the functions and features of the plain \ref Dfs,
877 879
  /// but it is much simpler to use it.
878 880
  ///
879 881
  /// Simplicity means that the way to change the types defined
880 882
  /// in the traits class is based on functions that returns the new class
881 883
  /// and not on templatable built-in classes.
882 884
  /// When using the plain \ref Dfs
883 885
  /// the new class with the modified type comes from
884 886
  /// the original class by using the ::
885 887
  /// operator. In the case of \ref DfsWizard only
886 888
  /// a function have to be called and it will
887 889
  /// return the needed class.
888 890
  ///
889 891
  /// It does not have own \ref run method. When its \ref run method is called
890 892
  /// it initiates a plain \ref Dfs object, and calls the \ref Dfs::run
891 893
  /// method of it.
892 894
  template<class TR>
893 895
  class DfsWizard : public TR
894 896
  {
895 897
    typedef TR Base;
896 898

	
897 899
    ///The type of the underlying digraph.
898 900
    typedef typename TR::Digraph Digraph;
899 901
    //\e
900 902
    typedef typename Digraph::Node Node;
901 903
    //\e
902 904
    typedef typename Digraph::NodeIt NodeIt;
903 905
    //\e
904 906
    typedef typename Digraph::Arc Arc;
905 907
    //\e
906 908
    typedef typename Digraph::OutArcIt OutArcIt;
907 909

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

	
920 922
  public:
921 923
    /// Constructor.
922 924
    DfsWizard() : TR() {}
923 925

	
924 926
    /// Constructor that requires parameters.
925 927

	
926 928
    /// Constructor that requires parameters.
927 929
    /// These parameters will be the default values for the traits class.
928 930
    DfsWizard(const Digraph &g, Node s=INVALID) :
929 931
      TR(g,s) {}
930 932

	
931 933
    ///Copy constructor
932 934
    DfsWizard(const TR &b) : TR(b) {}
933 935

	
934 936
    ~DfsWizard() {}
935 937

	
936 938
    ///Runs Dfs algorithm from a given node.
937 939

	
938 940
    ///Runs Dfs algorithm from a given node.
939 941
    ///The node can be given by the \ref source function.
940 942
    void run()
941 943
    {
942 944
      if(Base::_source==INVALID) throw UninitializedParameter();
943 945
      Dfs<Digraph,TR> alg(*reinterpret_cast<const Digraph*>(Base::_g));
944 946
      if(Base::_reached)
945 947
        alg.reachedMap(*reinterpret_cast<ReachedMap*>(Base::_reached));
946 948
      if(Base::_processed)
947 949
        alg.processedMap(*reinterpret_cast<ProcessedMap*>(Base::_processed));
948 950
      if(Base::_pred)
949 951
        alg.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
950 952
      if(Base::_dist)
951 953
        alg.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
952 954
      alg.run(Base::_source);
953 955
    }
954 956

	
955 957
    ///Runs Dfs algorithm from the given node.
956 958

	
957 959
    ///Runs Dfs algorithm from the given node.
958 960
    ///\param s is the given source.
959 961
    void run(Node s)
960 962
    {
961 963
      Base::_source=s;
962 964
      run();
963 965
    }
964 966

	
965 967
    template<class T>
966 968
    struct DefPredMapBase : public Base {
967 969
      typedef T PredMap;
968 970
      static PredMap *createPredMap(const Digraph &) { return 0; };
969 971
      DefPredMapBase(const TR &b) : TR(b) {}
970 972
    };
971 973

	
972 974
    ///\brief \ref named-templ-param "Named parameter"
973 975
    ///function for setting PredMap type
974 976
    ///
975 977
    /// \ref named-templ-param "Named parameter"
976 978
    ///function for setting PredMap type
977 979
    ///
978 980
    template<class T>
979 981
    DfsWizard<DefPredMapBase<T> > predMap(const T &t)
980 982
    {
981 983
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
982 984
      return DfsWizard<DefPredMapBase<T> >(*this);
983 985
    }
984 986

	
985 987

	
986 988
    template<class T>
987 989
    struct DefReachedMapBase : public Base {
988 990
      typedef T ReachedMap;
989 991
      static ReachedMap *createReachedMap(const Digraph &) { return 0; };
990 992
      DefReachedMapBase(const TR &b) : TR(b) {}
991 993
    };
992 994

	
993 995
    ///\brief \ref named-templ-param "Named parameter"
994 996
    ///function for setting ReachedMap
995 997
    ///
996 998
    /// \ref named-templ-param "Named parameter"
997 999
    ///function for setting ReachedMap
998 1000
    ///
999 1001
    template<class T>
1000 1002
    DfsWizard<DefReachedMapBase<T> > reachedMap(const T &t)
1001 1003
    {
1002 1004
      Base::_reached=reinterpret_cast<void*>(const_cast<T*>(&t));
1003 1005
      return DfsWizard<DefReachedMapBase<T> >(*this);
1004 1006
    }
1005 1007

	
1006 1008

	
1007 1009
    template<class T>
1008 1010
    struct DefProcessedMapBase : public Base {
1009 1011
      typedef T ProcessedMap;
1010 1012
      static ProcessedMap *createProcessedMap(const Digraph &) { return 0; };
1011 1013
      DefProcessedMapBase(const TR &b) : TR(b) {}
1012 1014
    };
1013 1015

	
1014 1016
    ///\brief \ref named-templ-param "Named parameter"
1015 1017
    ///function for setting ProcessedMap
1016 1018
    ///
1017 1019
    /// \ref named-templ-param "Named parameter"
1018 1020
    ///function for setting ProcessedMap
1019 1021
    ///
1020 1022
    template<class T>
1021 1023
    DfsWizard<DefProcessedMapBase<T> > processedMap(const T &t)
1022 1024
    {
1023 1025
      Base::_processed=reinterpret_cast<void*>(const_cast<T*>(&t));
1024 1026
      return DfsWizard<DefProcessedMapBase<T> >(*this);
1025 1027
    }
1026 1028

	
1027 1029
    template<class T>
1028 1030
    struct DefDistMapBase : public Base {
1029 1031
      typedef T DistMap;
1030 1032
      static DistMap *createDistMap(const Digraph &) { return 0; };
1031 1033
      DefDistMapBase(const TR &b) : TR(b) {}
1032 1034
    };
1033 1035

	
1034 1036
    ///\brief \ref named-templ-param "Named parameter"
1035 1037
    ///function for setting DistMap type
1036 1038
    ///
1037 1039
    /// \ref named-templ-param "Named parameter"
1038 1040
    ///function for setting DistMap type
1039 1041
    ///
1040 1042
    template<class T>
1041 1043
    DfsWizard<DefDistMapBase<T> > distMap(const T &t)
1042 1044
    {
1043 1045
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1044 1046
      return DfsWizard<DefDistMapBase<T> >(*this);
1045 1047
    }
1046 1048

	
1047 1049
    /// Sets the source node, from which the Dfs algorithm runs.
1048 1050

	
1049 1051
    /// Sets the source node, from which the Dfs algorithm runs.
1050 1052
    /// \param s is the source node.
1051 1053
    DfsWizard<TR> &source(Node s)
1052 1054
    {
1053 1055
      Base::_source=s;
1054 1056
      return *this;
1055 1057
    }
1056 1058

	
1057 1059
  };
1058 1060

	
1059 1061
  ///Function type interface for Dfs algorithm.
1060 1062

	
1061 1063
  ///\ingroup search
1062 1064
  ///Function type interface for Dfs algorithm.
1063 1065
  ///
1064 1066
  ///This function also has several
1065 1067
  ///\ref named-templ-func-param "named parameters",
1066 1068
  ///they are declared as the members of class \ref DfsWizard.
1067 1069
  ///The following
1068 1070
  ///example shows how to use these parameters.
1069 1071
  ///\code
1070 1072
  ///  dfs(g,source).predMap(preds).run();
1071 1073
  ///\endcode
1072 1074
  ///\warning Don't forget to put the \ref DfsWizard::run() "run()"
1073 1075
  ///to the end of the parameter list.
1074 1076
  ///\sa DfsWizard
1075 1077
  ///\sa Dfs
1076 1078
  template<class GR>
1077 1079
  DfsWizard<DfsWizardBase<GR> >
1078 1080
  dfs(const GR &g,typename GR::Node s=INVALID)
1079 1081
  {
1080 1082
    return DfsWizard<DfsWizardBase<GR> >(g,s);
1081 1083
  }
1082 1084

	
1083 1085
#ifdef DOXYGEN
1084 1086
  /// \brief Visitor class for dfs.
1085 1087
  ///
1086 1088
  /// It gives a simple interface for a functional interface for dfs
1087 1089
  /// traversal. The traversal on a linear data structure.
1088 1090
  template <typename _Digraph>
1089 1091
  struct DfsVisitor {
1090 1092
    typedef _Digraph Digraph;
1091 1093
    typedef typename Digraph::Arc Arc;
1092 1094
    typedef typename Digraph::Node Node;
1093 1095
    /// \brief Called when the arc reach a node.
1094 1096
    ///
1095 1097
    /// It is called when the dfs find an arc which target is not
1096 1098
    /// reached yet.
1097 1099
    void discover(const Arc& arc) {}
1098 1100
    /// \brief Called when the node reached first time.
1099 1101
    ///
1100 1102
    /// It is Called when the node reached first time.
1101 1103
    void reach(const Node& node) {}
1102 1104
    /// \brief Called when we step back on an arc.
1103 1105
    ///
1104 1106
    /// It is called when the dfs should step back on the arc.
1105 1107
    void backtrack(const Arc& arc) {}
1106 1108
    /// \brief Called when we step back from the node.
1107 1109
    ///
1108 1110
    /// It is called when we step back from the node.
1109 1111
    void leave(const Node& node) {}
1110 1112
    /// \brief Called when the arc examined but target of the arc
1111 1113
    /// already discovered.
1112 1114
    ///
1113 1115
    /// It called when the arc examined but the target of the arc
1114 1116
    /// already discovered.
1115 1117
    void examine(const Arc& arc) {}
1116 1118
    /// \brief Called for the source node of the dfs.
1117 1119
    ///
1118 1120
    /// It is called for the source node of the dfs.
1119 1121
    void start(const Node& node) {}
1120 1122
    /// \brief Called when we leave the source node of the dfs.
1121 1123
    ///
1122 1124
    /// It is called when we leave the source node of the dfs.
1123 1125
    void stop(const Node& node) {}
1124 1126

	
1125 1127
  };
1126 1128
#else
1127 1129
  template <typename _Digraph>
1128 1130
  struct DfsVisitor {
1129 1131
    typedef _Digraph Digraph;
1130 1132
    typedef typename Digraph::Arc Arc;
1131 1133
    typedef typename Digraph::Node Node;
1132 1134
    void discover(const Arc&) {}
1133 1135
    void reach(const Node&) {}
1134 1136
    void backtrack(const Arc&) {}
1135 1137
    void leave(const Node&) {}
1136 1138
    void examine(const Arc&) {}
1137 1139
    void start(const Node&) {}
1138 1140
    void stop(const Node&) {}
1139 1141

	
1140 1142
    template <typename _Visitor>
1141 1143
    struct Constraints {
1142 1144
      void constraints() {
1143 1145
        Arc arc;
1144 1146
        Node node;
1145 1147
        visitor.discover(arc);
1146 1148
        visitor.reach(node);
1147 1149
        visitor.backtrack(arc);
1148 1150
        visitor.leave(node);
1149 1151
        visitor.examine(arc);
1150 1152
        visitor.start(node);
1151 1153
        visitor.stop(arc);
1152 1154
      }
1153 1155
      _Visitor& visitor;
1154 1156
    };
1155 1157
  };
1156 1158
#endif
1157 1159

	
1158 1160
  /// \brief Default traits class of DfsVisit class.
1159 1161
  ///
1160 1162
  /// Default traits class of DfsVisit class.
1161 1163
  /// \tparam _Digraph Digraph type.
1162 1164
  template<class _Digraph>
1163 1165
  struct DfsVisitDefaultTraits {
1164 1166

	
1165 1167
    /// \brief The digraph type the algorithm runs on.
1166 1168
    typedef _Digraph Digraph;
1167 1169

	
1168 1170
    /// \brief The type of the map that indicates which nodes are reached.
1169 1171
    ///
1170 1172
    /// The type of the map that indicates which nodes are reached.
1171 1173
    /// It must meet the \ref concepts::WriteMap "WriteMap" concept.
1172 1174
    /// \todo named parameter to set this type, function to read and write.
1173 1175
    typedef typename Digraph::template NodeMap<bool> ReachedMap;
1174 1176

	
1175 1177
    /// \brief Instantiates a ReachedMap.
1176 1178
    ///
1177 1179
    /// This function instantiates a \ref ReachedMap.
1178 1180
    /// \param digraph is the digraph, to which
1179 1181
    /// we would like to define the \ref ReachedMap.
1180 1182
    static ReachedMap *createReachedMap(const Digraph &digraph) {
1181 1183
      return new ReachedMap(digraph);
1182 1184
    }
1183 1185

	
1184 1186
  };
1185 1187

	
1186 1188
  /// %DFS Visit algorithm class.
1187 1189

	
1188 1190
  /// \ingroup search
1189 1191
  /// This class provides an efficient implementation of the %DFS algorithm
1190 1192
  /// with visitor interface.
1191 1193
  ///
1192 1194
  /// The %DfsVisit class provides an alternative interface to the Dfs
1193 1195
  /// class. It works with callback mechanism, the DfsVisit object calls
1194 1196
  /// on every dfs event the \c Visitor class member functions.
1195 1197
  ///
1196
  /// \tparam _Digraph The digraph type the algorithm runs on. The default value is
1198
  /// \tparam _Digraph The digraph type the algorithm runs on.
1199
  /// The default value is
1197 1200
  /// \ref ListDigraph. The value of _Digraph is not used directly by Dfs, it
1198 1201
  /// is only passed to \ref DfsDefaultTraits.
1199 1202
  /// \tparam _Visitor The Visitor object for the algorithm. The
1200 1203
  /// \ref DfsVisitor "DfsVisitor<_Digraph>" is an empty Visitor which
1201 1204
  /// does not observe the Dfs events. If you want to observe the dfs
1202 1205
  /// events you should implement your own Visitor class.
1203 1206
  /// \tparam _Traits Traits class to set various data types used by the
1204 1207
  /// algorithm. The default traits class is
1205 1208
  /// \ref DfsVisitDefaultTraits "DfsVisitDefaultTraits<_Digraph>".
1206 1209
  /// See \ref DfsVisitDefaultTraits for the documentation of
1207 1210
  /// a Dfs visit traits class.
1208 1211
  ///
1209 1212
  /// \author Jacint Szabo, Alpar Juttner and Balazs Dezso
1210 1213
#ifdef DOXYGEN
1211 1214
  template <typename _Digraph, typename _Visitor, typename _Traits>
1212 1215
#else
1213 1216
  template <typename _Digraph = ListDigraph,
1214 1217
            typename _Visitor = DfsVisitor<_Digraph>,
1215 1218
            typename _Traits = DfsDefaultTraits<_Digraph> >
1216 1219
#endif
1217 1220
  class DfsVisit {
1218 1221
  public:
1219 1222

	
1220 1223
    /// \brief \ref Exception for uninitialized parameters.
1221 1224
    ///
1222 1225
    /// This error represents problems in the initialization
1223 1226
    /// of the parameters of the algorithms.
1224 1227
    class UninitializedParameter : public lemon::UninitializedParameter {
1225 1228
    public:
1226 1229
      virtual const char* what() const throw()
1227 1230
      {
1228 1231
        return "lemon::DfsVisit::UninitializedParameter";
1229 1232
      }
1230 1233
    };
1231 1234

	
1232 1235
    typedef _Traits Traits;
1233 1236

	
1234 1237
    typedef typename Traits::Digraph Digraph;
1235 1238

	
1236 1239
    typedef _Visitor Visitor;
1237 1240

	
1238 1241
    ///The type of the map indicating which nodes are reached.
1239 1242
    typedef typename Traits::ReachedMap ReachedMap;
1240 1243

	
1241 1244
  private:
1242 1245

	
1243 1246
    typedef typename Digraph::Node Node;
1244 1247
    typedef typename Digraph::NodeIt NodeIt;
1245 1248
    typedef typename Digraph::Arc Arc;
1246 1249
    typedef typename Digraph::OutArcIt OutArcIt;
1247 1250

	
1248 1251
    /// Pointer to the underlying digraph.
1249 1252
    const Digraph *_digraph;
1250 1253
    /// Pointer to the visitor object.
1251 1254
    Visitor *_visitor;
1252 1255
    ///Pointer to the map of reached status of the nodes.
1253 1256
    ReachedMap *_reached;
1254 1257
    ///Indicates if \ref _reached is locally allocated (\c true) or not.
1255 1258
    bool local_reached;
1256 1259

	
1257 1260
    std::vector<typename Digraph::Arc> _stack;
1258 1261
    int _stack_head;
1259 1262

	
1260 1263
    /// \brief Creates the maps if necessary.
1261 1264
    ///
1262 1265
    /// Creates the maps if necessary.
1263 1266
    void create_maps() {
1264 1267
      if(!_reached) {
1265 1268
        local_reached = true;
1266 1269
        _reached = Traits::createReachedMap(*_digraph);
1267 1270
      }
1268 1271
    }
1269 1272

	
1270 1273
  protected:
1271 1274

	
1272 1275
    DfsVisit() {}
1273 1276

	
1274 1277
  public:
1275 1278

	
1276 1279
    typedef DfsVisit Create;
1277 1280

	
1278 1281
    /// \name Named template parameters
1279 1282

	
1280 1283
    ///@{
1281 1284
    template <class T>
1282 1285
    struct DefReachedMapTraits : public Traits {
1283 1286
      typedef T ReachedMap;
1284 1287
      static ReachedMap *createReachedMap(const Digraph &digraph) {
1285 1288
        throw UninitializedParameter();
1286 1289
      }
1287 1290
    };
1288 1291
    /// \brief \ref named-templ-param "Named parameter" for setting
1289 1292
    /// ReachedMap type
1290 1293
    ///
1291 1294
    /// \ref named-templ-param "Named parameter" for setting ReachedMap type
1292 1295
    template <class T>
1293 1296
    struct DefReachedMap : public DfsVisit< Digraph, Visitor,
1294 1297
                                            DefReachedMapTraits<T> > {
1295 1298
      typedef DfsVisit< Digraph, Visitor, DefReachedMapTraits<T> > Create;
1296 1299
    };
1297 1300
    ///@}
1298 1301

	
1299 1302
  public:
1300 1303

	
1301 1304
    /// \brief Constructor.
1302 1305
    ///
1303 1306
    /// Constructor.
1304 1307
    ///
1305 1308
    /// \param digraph the digraph the algorithm will run on.
1306 1309
    /// \param visitor The visitor of the algorithm.
1307 1310
    ///
1308 1311
    DfsVisit(const Digraph& digraph, Visitor& visitor)
1309 1312
      : _digraph(&digraph), _visitor(&visitor),
1310 1313
        _reached(0), local_reached(false) {}
1311 1314

	
1312 1315
    /// \brief Destructor.
1313 1316
    ///
1314 1317
    /// Destructor.
1315 1318
    ~DfsVisit() {
1316 1319
      if(local_reached) delete _reached;
1317 1320
    }
1318 1321

	
1319 1322
    /// \brief Sets the map indicating if a node is reached.
1320 1323
    ///
1321 1324
    /// Sets the map indicating if a node is reached.
1322 1325
    /// If you don't use this function before calling \ref run(),
1323 1326
    /// it will allocate one. The destuctor deallocates this
1324 1327
    /// automatically allocated map, of course.
1325 1328
    /// \return <tt> (*this) </tt>
1326 1329
    DfsVisit &reachedMap(ReachedMap &m) {
1327 1330
      if(local_reached) {
1328 1331
        delete _reached;
1329 1332
        local_reached=false;
1330 1333
      }
1331 1334
      _reached = &m;
1332 1335
      return *this;
1333 1336
    }
1334 1337

	
1335 1338
  public:
1336 1339
    /// \name Execution control
1337 1340
    /// The simplest way to execute the algorithm is to use
1338 1341
    /// one of the member functions called \c run(...).
1339 1342
    /// \n
1340 1343
    /// If you need more control on the execution,
1341 1344
    /// first you must call \ref init(), then you can adda source node
1342 1345
    /// with \ref addSource().
1343 1346
    /// Finally \ref start() will perform the actual path
1344 1347
    /// computation.
1345 1348

	
1346 1349
    /// @{
1347 1350
    /// \brief Initializes the internal data structures.
1348 1351
    ///
1349 1352
    /// Initializes the internal data structures.
1350 1353
    ///
1351 1354
    void init() {
1352 1355
      create_maps();
1353 1356
      _stack.resize(countNodes(*_digraph));
1354 1357
      _stack_head = -1;
1355 1358
      for (NodeIt u(*_digraph) ; u != INVALID ; ++u) {
1356 1359
        _reached->set(u, false);
1357 1360
      }
1358 1361
    }
1359 1362

	
1360 1363
    /// \brief Adds a new source node.
1361 1364
    ///
1362 1365
    /// Adds a new source node to the set of nodes to be processed.
1363 1366
    void addSource(Node s) {
1364 1367
      if(!(*_reached)[s]) {
1365 1368
          _reached->set(s,true);
1366 1369
          _visitor->start(s);
1367 1370
          _visitor->reach(s);
1368 1371
          Arc e;
1369 1372
          _digraph->firstOut(e, s);
1370 1373
          if (e != INVALID) {
1371 1374
            _stack[++_stack_head] = e;
1372 1375
          } else {
1373 1376
            _visitor->leave(s);
1374 1377
          }
1375 1378
        }
1376 1379
    }
1377 1380

	
1378 1381
    /// \brief Processes the next arc.
1379 1382
    ///
1380 1383
    /// Processes the next arc.
1381 1384
    ///
1382 1385
    /// \return The processed arc.
1383 1386
    ///
1384 1387
    /// \pre The stack must not be empty!
1385 1388
    Arc processNextArc() {
1386 1389
      Arc e = _stack[_stack_head];
1387 1390
      Node m = _digraph->target(e);
1388 1391
      if(!(*_reached)[m]) {
1389 1392
        _visitor->discover(e);
1390 1393
        _visitor->reach(m);
1391 1394
        _reached->set(m, true);
1392 1395
        _digraph->firstOut(_stack[++_stack_head], m);
1393 1396
      } else {
1394 1397
        _visitor->examine(e);
1395 1398
        m = _digraph->source(e);
1396 1399
        _digraph->nextOut(_stack[_stack_head]);
1397 1400
      }
1398 1401
      while (_stack_head>=0 && _stack[_stack_head] == INVALID) {
1399 1402
        _visitor->leave(m);
1400 1403
        --_stack_head;
1401 1404
        if (_stack_head >= 0) {
1402 1405
          _visitor->backtrack(_stack[_stack_head]);
1403 1406
          m = _digraph->source(_stack[_stack_head]);
1404 1407
          _digraph->nextOut(_stack[_stack_head]);
1405 1408
        } else {
1406 1409
          _visitor->stop(m);
1407 1410
        }
1408 1411
      }
1409 1412
      return e;
1410 1413
    }
1411 1414

	
1412 1415
    /// \brief Next arc to be processed.
1413 1416
    ///
1414 1417
    /// Next arc to be processed.
1415 1418
    ///
1416 1419
    /// \return The next arc to be processed or INVALID if the stack is
1417 1420
    /// empty.
1418 1421
    Arc nextArc() {
1419 1422
      return _stack_head >= 0 ? _stack[_stack_head] : INVALID;
1420 1423
    }
1421 1424

	
1422 1425
    /// \brief Returns \c false if there are nodes
1423 1426
    /// to be processed in the queue
1424 1427
    ///
1425 1428
    /// Returns \c false if there are nodes
1426 1429
    /// to be processed in the queue
1427 1430
    bool emptyQueue() { return _stack_head < 0; }
1428 1431

	
1429 1432
    /// \brief Returns the number of the nodes to be processed.
1430 1433
    ///
1431 1434
    /// Returns the number of the nodes to be processed in the queue.
1432 1435
    int queueSize() { return _stack_head + 1; }
1433 1436

	
1434 1437
    /// \brief Executes the algorithm.
1435 1438
    ///
1436 1439
    /// Executes the algorithm.
1437 1440
    ///
1438 1441
    /// \pre init() must be called and at least one node should be added
1439 1442
    /// with addSource() before using this function.
1440 1443
    void start() {
1441 1444
      while ( !emptyQueue() ) processNextArc();
1442 1445
    }
1443 1446

	
1444 1447
    /// \brief Executes the algorithm until \c dest is reached.
1445 1448
    ///
1446 1449
    /// Executes the algorithm until \c dest is reached.
1447 1450
    ///
1448 1451
    /// \pre init() must be called and at least one node should be added
1449 1452
    /// with addSource() before using this function.
1450 1453
    void start(Node dest) {
1451 1454
      while ( !emptyQueue() && _digraph->target(_stack[_stack_head]) != dest )
1452 1455
        processNextArc();
1453 1456
    }
1454 1457

	
1455 1458
    /// \brief Executes the algorithm until a condition is met.
1456 1459
    ///
1457 1460
    /// Executes the algorithm until a condition is met.
1458 1461
    ///
1459 1462
    /// \pre init() must be called and at least one node should be added
1460 1463
    /// with addSource() before using this function.
1461 1464
    ///
1462 1465
    /// \param em must be a bool (or convertible) arc map. The algorithm
1463 1466
    /// will stop when it reaches an arc \c e with <tt>em[e]</tt> true.
1464 1467
    ///
1465 1468
    ///\return The reached arc \c e with <tt>em[e]</tt> true or
1466 1469
    ///\c INVALID if no such arc was found.
1467 1470
    ///
1468 1471
    /// \warning Contrary to \ref Bfs and \ref Dijkstra, \c em is an arc map,
1469 1472
    /// not a node map.
1470 1473
    template <typename EM>
1471 1474
    Arc start(const EM &em) {
1472 1475
      while ( !emptyQueue() && !em[_stack[_stack_head]] )
1473 1476
        processNextArc();
1474 1477
      return emptyQueue() ? INVALID : _stack[_stack_head];
1475 1478
    }
1476 1479

	
1477 1480
    /// \brief Runs %DFSVisit algorithm from node \c s.
1478 1481
    ///
1479 1482
    /// This method runs the %DFS algorithm from a root node \c s.
1480 1483
    /// \note d.run(s) is just a shortcut of the following code.
1481 1484
    ///\code
1482 1485
    ///   d.init();
1483 1486
    ///   d.addSource(s);
1484 1487
    ///   d.start();
1485 1488
    ///\endcode
1486 1489
    void run(Node s) {
1487 1490
      init();
1488 1491
      addSource(s);
1489 1492
      start();
1490 1493
    }
1491 1494

	
1492 1495
    /// \brief Runs %DFSVisit algorithm to visit all nodes in the digraph.
1493 1496

	
1494 1497
    /// This method runs the %DFS algorithm in order to
1495 1498
    /// compute the %DFS path to each node. The algorithm computes
1496 1499
    /// - The %DFS tree.
1497 1500
    /// - The distance of each node from the root in the %DFS tree.
1498 1501
    ///
1499 1502
    ///\note d.run() is just a shortcut of the following code.
1500 1503
    ///\code
1501 1504
    ///  d.init();
1502 1505
    ///  for (NodeIt it(digraph); it != INVALID; ++it) {
1503 1506
    ///    if (!d.reached(it)) {
1504 1507
    ///      d.addSource(it);
1505 1508
    ///      d.start();
1506 1509
    ///    }
1507 1510
    ///  }
1508 1511
    ///\endcode
1509 1512
    void run() {
1510 1513
      init();
1511 1514
      for (NodeIt it(*_digraph); it != INVALID; ++it) {
1512 1515
        if (!reached(it)) {
1513 1516
          addSource(it);
1514 1517
          start();
1515 1518
        }
1516 1519
      }
1517 1520
    }
1518 1521
    ///@}
1519 1522

	
1520 1523
    /// \name Query Functions
1521 1524
    /// The result of the %DFS algorithm can be obtained using these
1522 1525
    /// functions.\n
1523 1526
    /// Before the use of these functions,
1524 1527
    /// either run() or start() must be called.
1525 1528
    ///@{
1526 1529
    /// \brief Checks if a node is reachable from the root.
1527 1530
    ///
1528 1531
    /// Returns \c true if \c v is reachable from the root(s).
1529 1532
    /// \warning The source nodes are inditated as unreachable.
1530 1533
    /// \pre Either \ref run() or \ref start()
1531 1534
    /// must be called before using this function.
1532 1535
    ///
1533 1536
    bool reached(Node v) { return (*_reached)[v]; }
1534 1537
    ///@}
1535 1538
  };
1536 1539

	
1537 1540

	
1538 1541
} //END OF NAMESPACE LEMON
1539 1542

	
1540 1543
#endif
1541 1544

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

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

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

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

	
34 34
namespace lemon {
35 35

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

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

	
76 76
  ///Default traits class of Dijkstra class.
77 77

	
78 78
  ///Default traits class of Dijkstra class.
79 79
  ///\tparam GR Digraph type.
80 80
  ///\tparam LM Type of length map.
81 81
  template<class GR, class LM>
82 82
  struct DijkstraDefaultTraits
83 83
  {
84 84
    ///The digraph type the algorithm runs on.
85 85
    typedef GR Digraph;
86 86
    ///The type of the map that stores the arc lengths.
87 87

	
88 88
    ///The type of the map that stores the arc lengths.
89 89
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
90 90
    typedef LM LengthMap;
91 91
    //The type of the length of the arcs.
92 92
    typedef typename LM::Value Value;
93 93
    /// Operation traits for Dijkstra algorithm.
94 94

	
95 95
    /// It defines the used operation by the algorithm.
96 96
    /// \see DijkstraDefaultOperationTraits
97 97
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
98 98
    /// The cross reference type used by heap.
99 99

	
100 100

	
101 101
    /// The cross reference type used by heap.
102 102
    /// Usually it is \c Digraph::NodeMap<int>.
103 103
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
104 104
    ///Instantiates a HeapCrossRef.
105 105

	
106 106
    ///This function instantiates a \c HeapCrossRef.
107 107
    /// \param G is the digraph, to which we would like to define the
108 108
    /// HeapCrossRef.
109 109
    static HeapCrossRef *createHeapCrossRef(const GR &G)
110 110
    {
111 111
      return new HeapCrossRef(G);
112 112
    }
113 113

	
114 114
    ///The heap type used by Dijkstra algorithm.
115 115

	
116 116
    ///The heap type used by Dijkstra algorithm.
117 117
    ///
118 118
    ///\sa BinHeap
119 119
    ///\sa Dijkstra
120 120
    typedef BinHeap<typename LM::Value, HeapCrossRef, std::less<Value> > Heap;
121 121

	
122 122
    static Heap *createHeap(HeapCrossRef& R)
123 123
    {
124 124
      return new Heap(R);
125 125
    }
126 126

	
127 127
    ///\brief The type of the map that stores the last
128 128
    ///arcs of the shortest paths.
129 129
    ///
130 130
    ///The type of the map that stores the last
131 131
    ///arcs of the shortest paths.
132 132
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
133 133
    ///
134 134
    typedef typename Digraph::template NodeMap<typename GR::Arc> PredMap;
135 135
    ///Instantiates a PredMap.
136 136

	
137 137
    ///This function instantiates a \c PredMap.
138 138
    ///\param G is the digraph, to which we would like to define the PredMap.
139 139
    ///\todo The digraph alone may be insufficient for the initialization
140 140
    static PredMap *createPredMap(const GR &G)
141 141
    {
142 142
      return new PredMap(G);
143 143
    }
144 144

	
145 145
    ///The type of the map that stores whether a nodes is processed.
146 146

	
147 147
    ///The type of the map that stores whether a nodes is processed.
148 148
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
149 149
    ///By default it is a NullMap.
150 150
    ///\todo If it is set to a real map,
151 151
    ///Dijkstra::processed() should read this.
152 152
    ///\todo named parameter to set this type, function to read and write.
153 153
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
154 154
    ///Instantiates a ProcessedMap.
155 155

	
156 156
    ///This function instantiates a \c ProcessedMap.
157 157
    ///\param g is the digraph, to which
158 158
    ///we would like to define the \c ProcessedMap
159 159
#ifdef DOXYGEN
160 160
    static ProcessedMap *createProcessedMap(const GR &g)
161 161
#else
162 162
    static ProcessedMap *createProcessedMap(const GR &)
163 163
#endif
164 164
    {
165 165
      return new ProcessedMap();
166 166
    }
167 167
    ///The type of the map that stores the dists of the nodes.
168 168

	
169 169
    ///The type of the map that stores the dists of the nodes.
170 170
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
171 171
    ///
172 172
    typedef typename Digraph::template NodeMap<typename LM::Value> DistMap;
173 173
    ///Instantiates a DistMap.
174 174

	
175 175
    ///This function instantiates a \ref DistMap.
176
    ///\param G is the digraph, to which we would like to define the \ref DistMap
176
    ///\param G is the digraph, to which we would like to define
177
    ///the \ref DistMap
177 178
    static DistMap *createDistMap(const GR &G)
178 179
    {
179 180
      return new DistMap(G);
180 181
    }
181 182
  };
182 183

	
183 184
  ///%Dijkstra algorithm class.
184 185

	
185 186
  /// \ingroup shortest_path
186 187
  ///This class provides an efficient implementation of %Dijkstra algorithm.
187 188
  ///The arc lengths are passed to the algorithm using a
188 189
  ///\ref concepts::ReadMap "ReadMap",
189 190
  ///so it is easy to change it to any kind of length.
190 191
  ///
191 192
  ///The type of the length is determined by the
192 193
  ///\ref concepts::ReadMap::Value "Value" of the length map.
193 194
  ///
194 195
  ///It is also possible to change the underlying priority heap.
195 196
  ///
196 197
  ///\tparam GR The digraph type the algorithm runs on. The default value
197 198
  ///is \ref ListDigraph. The value of GR is not used directly by
198 199
  ///Dijkstra, it is only passed to \ref DijkstraDefaultTraits.
199 200
  ///\tparam LM This read-only ArcMap determines the lengths of the
200 201
  ///arcs. It is read once for each arc, so the map may involve in
201 202
  ///relatively time consuming process to compute the arc length if
202 203
  ///it is necessary. The default map type is \ref
203 204
  ///concepts::Digraph::ArcMap "Digraph::ArcMap<int>".  The value
204 205
  ///of LM is not used directly by Dijkstra, it is only passed to \ref
205 206
  ///DijkstraDefaultTraits.
206 207
  ///\tparam TR Traits class to set
207 208
  ///various data types used by the algorithm.  The default traits
208 209
  ///class is \ref DijkstraDefaultTraits
209 210
  ///"DijkstraDefaultTraits<GR,LM>".  See \ref
210 211
  ///DijkstraDefaultTraits for the documentation of a Dijkstra traits
211 212
  ///class.
212 213

	
213 214
#ifdef DOXYGEN
214 215
  template <typename GR, typename LM, typename TR>
215 216
#else
216 217
  template <typename GR=ListDigraph,
217 218
            typename LM=typename GR::template ArcMap<int>,
218 219
            typename TR=DijkstraDefaultTraits<GR,LM> >
219 220
#endif
220 221
  class Dijkstra {
221 222
  public:
222 223
    /**
223 224
     * \brief \ref Exception for uninitialized parameters.
224 225
     *
225 226
     * This error represents problems in the initialization
226 227
     * of the parameters of the algorithms.
227 228
     */
228 229
    class UninitializedParameter : public lemon::UninitializedParameter {
229 230
    public:
230 231
      virtual const char* what() const throw() {
231 232
        return "lemon::Dijkstra::UninitializedParameter";
232 233
      }
233 234
    };
234 235

	
235 236
    typedef TR Traits;
236 237
    ///The type of the underlying digraph.
237 238
    typedef typename TR::Digraph Digraph;
238 239
    ///\e
239 240
    typedef typename Digraph::Node Node;
240 241
    ///\e
241 242
    typedef typename Digraph::NodeIt NodeIt;
242 243
    ///\e
243 244
    typedef typename Digraph::Arc Arc;
244 245
    ///\e
245 246
    typedef typename Digraph::OutArcIt OutArcIt;
246 247

	
247 248
    ///The type of the length of the arcs.
248 249
    typedef typename TR::LengthMap::Value Value;
249 250
    ///The type of the map that stores the arc lengths.
250 251
    typedef typename TR::LengthMap LengthMap;
251 252
    ///\brief The type of the map that stores the last
252 253
    ///arcs of the shortest paths.
253 254
    typedef typename TR::PredMap PredMap;
254 255
    ///The type of the map indicating if a node is processed.
255 256
    typedef typename TR::ProcessedMap ProcessedMap;
256 257
    ///The type of the map that stores the dists of the nodes.
257 258
    typedef typename TR::DistMap DistMap;
258 259
    ///The cross reference type used for the current heap.
259 260
    typedef typename TR::HeapCrossRef HeapCrossRef;
260 261
    ///The heap type used by the dijkstra algorithm.
261 262
    typedef typename TR::Heap Heap;
262 263
    ///The operation traits.
263 264
    typedef typename TR::OperationTraits OperationTraits;
264 265
  private:
265 266
    /// Pointer to the underlying digraph.
266 267
    const Digraph *G;
267 268
    /// Pointer to the length map
268 269
    const LengthMap *length;
269 270
    ///Pointer to the map of predecessors arcs.
270 271
    PredMap *_pred;
271 272
    ///Indicates if \ref _pred is locally allocated (\c true) or not.
272 273
    bool local_pred;
273 274
    ///Pointer to the map of distances.
274 275
    DistMap *_dist;
275 276
    ///Indicates if \ref _dist is locally allocated (\c true) or not.
276 277
    bool local_dist;
277 278
    ///Pointer to the map of processed status of the nodes.
278 279
    ProcessedMap *_processed;
279 280
    ///Indicates if \ref _processed is locally allocated (\c true) or not.
280 281
    bool local_processed;
281 282
    ///Pointer to the heap cross references.
282 283
    HeapCrossRef *_heap_cross_ref;
283 284
    ///Indicates if \ref _heap_cross_ref is locally allocated (\c true) or not.
284 285
    bool local_heap_cross_ref;
285 286
    ///Pointer to the heap.
286 287
    Heap *_heap;
287 288
    ///Indicates if \ref _heap is locally allocated (\c true) or not.
288 289
    bool local_heap;
289 290

	
290 291
    ///Creates the maps if necessary.
291 292

	
292 293
    ///\todo Better memory allocation (instead of new).
293 294
    void create_maps()
294 295
    {
295 296
      if(!_pred) {
296 297
        local_pred = true;
297 298
        _pred = Traits::createPredMap(*G);
298 299
      }
299 300
      if(!_dist) {
300 301
        local_dist = true;
301 302
        _dist = Traits::createDistMap(*G);
302 303
      }
303 304
      if(!_processed) {
304 305
        local_processed = true;
305 306
        _processed = Traits::createProcessedMap(*G);
306 307
      }
307 308
      if (!_heap_cross_ref) {
308 309
        local_heap_cross_ref = true;
309 310
        _heap_cross_ref = Traits::createHeapCrossRef(*G);
310 311
      }
311 312
      if (!_heap) {
312 313
        local_heap = true;
313 314
        _heap = Traits::createHeap(*_heap_cross_ref);
314 315
      }
315 316
    }
316 317

	
317 318
  public :
318 319

	
319 320
    typedef Dijkstra Create;
320 321

	
321 322
    ///\name Named template parameters
322 323

	
323 324
    ///@{
324 325

	
325 326
    template <class T>
326 327
    struct DefPredMapTraits : public Traits {
327 328
      typedef T PredMap;
328 329
      static PredMap *createPredMap(const Digraph &)
329 330
      {
330 331
        throw UninitializedParameter();
331 332
      }
332 333
    };
333 334
    ///\ref named-templ-param "Named parameter" for setting PredMap type
334 335

	
335 336
    ///\ref named-templ-param "Named parameter" for setting PredMap type
336 337
    ///
337 338
    template <class T>
338 339
    struct DefPredMap
339
      : public Dijkstra< Digraph,        LengthMap, DefPredMapTraits<T> > {
340
      typedef Dijkstra< Digraph,        LengthMap, DefPredMapTraits<T> > Create;
340
      : public Dijkstra< Digraph, LengthMap, DefPredMapTraits<T> > {
341
      typedef Dijkstra< Digraph, LengthMap, DefPredMapTraits<T> > Create;
341 342
    };
342 343

	
343 344
    template <class T>
344 345
    struct DefDistMapTraits : public Traits {
345 346
      typedef T DistMap;
346 347
      static DistMap *createDistMap(const Digraph &)
347 348
      {
348 349
        throw UninitializedParameter();
349 350
      }
350 351
    };
351 352
    ///\ref named-templ-param "Named parameter" for setting DistMap type
352 353

	
353 354
    ///\ref named-templ-param "Named parameter" for setting DistMap type
354 355
    ///
355 356
    template <class T>
356 357
    struct DefDistMap
357 358
      : public Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > {
358 359
      typedef Dijkstra< Digraph, LengthMap, DefDistMapTraits<T> > Create;
359 360
    };
360 361

	
361 362
    template <class T>
362 363
    struct DefProcessedMapTraits : public Traits {
363 364
      typedef T ProcessedMap;
364 365
      static ProcessedMap *createProcessedMap(const Digraph &G)
365 366
      {
366 367
        throw UninitializedParameter();
367 368
      }
368 369
    };
369 370
    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
370 371

	
371 372
    ///\ref named-templ-param "Named parameter" for setting ProcessedMap type
372 373
    ///
373 374
    template <class T>
374 375
    struct DefProcessedMap
375
      : public Dijkstra< Digraph,        LengthMap, DefProcessedMapTraits<T> > {
376
      typedef Dijkstra< Digraph,        LengthMap, DefProcessedMapTraits<T> > Create;
376
      : public Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > {
377
      typedef Dijkstra< Digraph, LengthMap, DefProcessedMapTraits<T> > Create;
377 378
    };
378 379

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

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

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

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

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

	
465 467
    ///@}
466 468

	
467 469

	
468 470
  protected:
469 471

	
470 472
    Dijkstra() {}
471 473

	
472 474
  public:
473 475

	
474 476
    ///Constructor.
475 477

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

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

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

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

	
507 509
    ///Sets the map storing the predecessor arcs.
508 510

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

	
524 526
    ///Sets the map storing the distances calculated by the algorithm.
525 527

	
526 528
    ///Sets the map storing the distances calculated by the algorithm.
527 529
    ///If you don't use this function before calling \ref run(),
528 530
    ///it will allocate one. The destuctor deallocates this
529 531
    ///automatically allocated map, of course.
530 532
    ///\return <tt> (*this) </tt>
531 533
    Dijkstra &distMap(DistMap &m)
532 534
    {
533 535
      if(local_dist) {
534 536
        delete _dist;
535 537
        local_dist=false;
536 538
      }
537 539
      _dist = &m;
538 540
      return *this;
539 541
    }
540 542

	
541 543
    ///Sets the heap and the cross reference used by algorithm.
542 544

	
543 545
    ///Sets the heap and the cross reference used by algorithm.
544 546
    ///If you don't use this function before calling \ref run(),
545 547
    ///it will allocate one. The destuctor deallocates this
546 548
    ///automatically allocated heap and cross reference, of course.
547 549
    ///\return <tt> (*this) </tt>
548 550
    Dijkstra &heap(Heap& hp, HeapCrossRef &cr)
549 551
    {
550 552
      if(local_heap_cross_ref) {
551 553
        delete _heap_cross_ref;
552 554
        local_heap_cross_ref=false;
553 555
      }
554 556
      _heap_cross_ref = &cr;
555 557
      if(local_heap) {
556 558
        delete _heap;
557 559
        local_heap=false;
558 560
      }
559 561
      _heap = &hp;
560 562
      return *this;
561 563
    }
562 564

	
563 565
  private:
564 566
    void finalizeNodeData(Node v,Value dst)
565 567
    {
566 568
      _processed->set(v,true);
567 569
      _dist->set(v, dst);
568 570
    }
569 571

	
570 572
  public:
571 573

	
572 574
    typedef PredMapPath<Digraph, PredMap> Path;
573 575

	
574 576
    ///\name Execution control
575 577
    ///The simplest way to execute the algorithm is to use
576 578
    ///one of the member functions called \c run(...).
577 579
    ///\n
578 580
    ///If you need more control on the execution,
579 581
    ///first you must call \ref init(), then you can add several source nodes
580 582
    ///with \ref addSource().
581 583
    ///Finally \ref start() will perform the actual path
582 584
    ///computation.
583 585

	
584 586
    ///@{
585 587

	
586 588
    ///Initializes the internal data structures.
587 589

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

	
601 603
    ///Adds a new source node.
602 604

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

	
620 622
    ///Processes the next node in the priority heap
621 623

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

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

	
657 659
    ///Next node to be processed.
658 660

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

	
668 670
    ///\brief Returns \c false if there are nodes
669 671
    ///to be processed in the priority heap
670 672
    ///
671 673
    ///Returns \c false if there are nodes
672 674
    ///to be processed in the priority heap
673 675
    bool emptyQueue() { return _heap->empty(); }
674 676
    ///Returns the number of the nodes to be processed in the priority heap
675 677

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

	
680 682
    ///Executes the algorithm.
681 683

	
682 684
    ///Executes the algorithm.
683 685
    ///
684 686
    ///\pre init() must be called and at least one node should be added
685 687
    ///with addSource() before using this function.
686 688
    ///
687 689
    ///This method runs the %Dijkstra algorithm from the root node(s)
688 690
    ///in order to
689 691
    ///compute the
690 692
    ///shortest path to each node. The algorithm computes
691 693
    ///- The shortest path tree.
692 694
    ///- The distance of each node from the root(s).
693 695
    ///
694 696
    void start()
695 697
    {
696 698
      while ( !_heap->empty() ) processNextNode();
697 699
    }
698 700

	
699 701
    ///Executes the algorithm until \c dest is reached.
700 702

	
701 703
    ///Executes the algorithm until \c dest is reached.
702 704
    ///
703 705
    ///\pre init() must be called and at least one node should be added
704 706
    ///with addSource() before using this function.
705 707
    ///
706 708
    ///This method runs the %Dijkstra algorithm from the root node(s)
707 709
    ///in order to
708 710
    ///compute the
709 711
    ///shortest path to \c dest. The algorithm computes
710 712
    ///- The shortest path to \c  dest.
711 713
    ///- The distance of \c dest from the root(s).
712 714
    ///
713 715
    void start(Node dest)
714 716
    {
715 717
      while ( !_heap->empty() && _heap->top()!=dest ) processNextNode();
716 718
      if ( !_heap->empty() ) finalizeNodeData(_heap->top(),_heap->prio());
717 719
    }
718 720

	
719 721
    ///Executes the algorithm until a condition is met.
720 722

	
721 723
    ///Executes the algorithm until a condition is met.
722 724
    ///
723 725
    ///\pre init() must be called and at least one node should be added
724 726
    ///with addSource() before using this function.
725 727
    ///
726 728
    ///\param nm must be a bool (or convertible) node map. The algorithm
727 729
    ///will stop when it reaches a node \c v with <tt>nm[v]</tt> true.
728 730
    ///
729 731
    ///\return The reached node \c v with <tt>nm[v]</tt> true or
730 732
    ///\c INVALID if no such node was found.
731 733
    template<class NodeBoolMap>
732 734
    Node start(const NodeBoolMap &nm)
733 735
    {
734 736
      while ( !_heap->empty() && !nm[_heap->top()] ) processNextNode();
735 737
      if ( _heap->empty() ) return INVALID;
736 738
      finalizeNodeData(_heap->top(),_heap->prio());
737 739
      return _heap->top();
738 740
    }
739 741

	
740 742
    ///Runs %Dijkstra algorithm from node \c s.
741 743

	
742 744
    ///This method runs the %Dijkstra algorithm from a root node \c s
743 745
    ///in order to
744 746
    ///compute the
745 747
    ///shortest path to each node. The algorithm computes
746 748
    ///- The shortest path tree.
747 749
    ///- The distance of each node from the root.
748 750
    ///
749 751
    ///\note d.run(s) is just a shortcut of the following code.
750 752
    ///\code
751 753
    ///  d.init();
752 754
    ///  d.addSource(s);
753 755
    ///  d.start();
754 756
    ///\endcode
755 757
    void run(Node s) {
756 758
      init();
757 759
      addSource(s);
758 760
      start();
759 761
    }
760 762

	
761 763
    ///Finds the shortest path between \c s and \c t.
762 764

	
763 765
    ///Finds the shortest path between \c s and \c t.
764 766
    ///
765 767
    ///\return The length of the shortest s---t path if there exists one,
766 768
    ///0 otherwise.
767 769
    ///\note Apart from the return value, d.run(s) is
768 770
    ///just a shortcut of the following code.
769 771
    ///\code
770 772
    ///  d.init();
771 773
    ///  d.addSource(s);
772 774
    ///  d.start(t);
773 775
    ///\endcode
774 776
    Value run(Node s,Node t) {
775 777
      init();
776 778
      addSource(s);
777 779
      start(t);
778 780
      return (*_pred)[t]==INVALID?OperationTraits::zero():(*_dist)[t];
779 781
    }
780 782

	
781 783
    ///@}
782 784

	
783 785
    ///\name Query Functions
784 786
    ///The result of the %Dijkstra algorithm can be obtained using these
785 787
    ///functions.\n
786 788
    ///Before the use of these functions,
787 789
    ///either run() or start() must be called.
788 790

	
789 791
    ///@{
790 792

	
791 793
    ///Gives back the shortest path.
792 794

	
793 795
    ///Gives back the shortest path.
794 796
    ///\pre The \c t should be reachable from the source.
795 797
    Path path(Node t)
796 798
    {
797 799
      return Path(*G, *_pred, t);
798 800
    }
799 801

	
800 802
    ///The distance of a node from the root.
801 803

	
802 804
    ///Returns the distance of a node from the root.
803 805
    ///\pre \ref run() must be called before using this function.
804 806
    ///\warning If node \c v in unreachable from the root the return value
805 807
    ///of this funcion is undefined.
806 808
    Value dist(Node v) const { return (*_dist)[v]; }
807 809

	
808 810
    ///The current distance of a node from the root.
809 811

	
810 812
    ///Returns the current distance of a node from the root.
811 813
    ///It may be decreased in the following processes.
812 814
    ///\pre \c node should be reached but not processed
813 815
    Value currentDist(Node v) const { return (*_heap)[v]; }
814 816

	
815 817
    ///Returns the 'previous arc' of the shortest path tree.
816 818

	
817 819
    ///For a node \c v it returns the 'previous arc' of the shortest path tree,
818 820
    ///i.e. it returns the last arc of a shortest path from the root to \c
819 821
    ///v. It is \ref INVALID
820 822
    ///if \c v is unreachable from the root or if \c v=s. The
821 823
    ///shortest path tree used here is equal to the shortest path tree used in
822 824
    ///\ref predNode().  \pre \ref run() must be called before using
823 825
    ///this function.
824 826
    Arc predArc(Node v) const { return (*_pred)[v]; }
825 827

	
826 828
    ///Returns the 'previous node' of the shortest path tree.
827 829

	
828 830
    ///For a node \c v it returns the 'previous node' of the shortest path tree,
829 831
    ///i.e. it returns the last but one node from a shortest path from the
830 832
    ///root to \c /v. It is INVALID if \c v is unreachable from the root or if
831 833
    ///\c v=s. The shortest path tree used here is equal to the shortest path
832 834
    ///tree used in \ref predArc().  \pre \ref run() must be called before
833 835
    ///using this function.
834 836
    Node predNode(Node v) const { return (*_pred)[v]==INVALID ? INVALID:
835 837
                                  G->source((*_pred)[v]); }
836 838

	
837 839
    ///Returns a reference to the NodeMap of distances.
838 840

	
839 841
    ///Returns a reference to the NodeMap of distances. \pre \ref run() must
840 842
    ///be called before using this function.
841 843
    const DistMap &distMap() const { return *_dist;}
842 844

	
843 845
    ///Returns a reference to the shortest path tree map.
844 846

	
845 847
    ///Returns a reference to the NodeMap of the arcs of the
846 848
    ///shortest path tree.
847 849
    ///\pre \ref run() must be called before using this function.
848 850
    const PredMap &predMap() const { return *_pred;}
849 851

	
850 852
    ///Checks if a node is reachable from the root.
851 853

	
852 854
    ///Returns \c true if \c v is reachable from the root.
853 855
    ///\warning The source nodes are inditated as unreached.
854 856
    ///\pre \ref run() must be called before using this function.
855 857
    ///
856 858
    bool reached(Node v) { return (*_heap_cross_ref)[v] != Heap::PRE_HEAP; }
857 859

	
858 860
    ///Checks if a node is processed.
859 861

	
860 862
    ///Returns \c true if \c v is processed, i.e. the shortest
861 863
    ///path to \c v has already found.
862 864
    ///\pre \ref run() must be called before using this function.
863 865
    ///
864 866
    bool processed(Node v) { return (*_heap_cross_ref)[v] == Heap::POST_HEAP; }
865 867

	
866 868
    ///@}
867 869
  };
868 870

	
869 871

	
870 872

	
871 873

	
872 874

	
873 875
  ///Default traits class of Dijkstra function.
874 876

	
875 877
  ///Default traits class of Dijkstra function.
876 878
  ///\tparam GR Digraph type.
877 879
  ///\tparam LM Type of length map.
878 880
  template<class GR, class LM>
879 881
  struct DijkstraWizardDefaultTraits
880 882
  {
881 883
    ///The digraph type the algorithm runs on.
882 884
    typedef GR Digraph;
883 885
    ///The type of the map that stores the arc lengths.
884 886

	
885 887
    ///The type of the map that stores the arc lengths.
886 888
    ///It must meet the \ref concepts::ReadMap "ReadMap" concept.
887 889
    typedef LM LengthMap;
888 890
    //The type of the length of the arcs.
889 891
    typedef typename LM::Value Value;
890 892
    /// Operation traits for Dijkstra algorithm.
891 893

	
892 894
    /// It defines the used operation by the algorithm.
893 895
    /// \see DijkstraDefaultOperationTraits
894 896
    typedef DijkstraDefaultOperationTraits<Value> OperationTraits;
895 897
    ///The heap type used by Dijkstra algorithm.
896 898

	
897 899
    /// The cross reference type used by heap.
898 900

	
899 901
    /// The cross reference type used by heap.
900 902
    /// Usually it is \c Digraph::NodeMap<int>.
901 903
    typedef typename Digraph::template NodeMap<int> HeapCrossRef;
902 904
    ///Instantiates a HeapCrossRef.
903 905

	
904 906
    ///This function instantiates a \ref HeapCrossRef.
905 907
    /// \param G is the digraph, to which we would like to define the
906 908
    /// HeapCrossRef.
907 909
    /// \todo The digraph alone may be insufficient for the initialization
908 910
    static HeapCrossRef *createHeapCrossRef(const GR &G)
909 911
    {
910 912
      return new HeapCrossRef(G);
911 913
    }
912 914

	
913 915
    ///The heap type used by Dijkstra algorithm.
914 916

	
915 917
    ///The heap type used by Dijkstra algorithm.
916 918
    ///
917 919
    ///\sa BinHeap
918 920
    ///\sa Dijkstra
919 921
    typedef BinHeap<typename LM::Value, typename GR::template NodeMap<int>,
920 922
                    std::less<Value> > Heap;
921 923

	
922 924
    static Heap *createHeap(HeapCrossRef& R)
923 925
    {
924 926
      return new Heap(R);
925 927
    }
926 928

	
927 929
    ///\brief The type of the map that stores the last
928 930
    ///arcs of the shortest paths.
929 931
    ///
930 932
    ///The type of the map that stores the last
931 933
    ///arcs of the shortest paths.
932 934
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
933 935
    ///
934 936
    typedef NullMap <typename GR::Node,typename GR::Arc> PredMap;
935 937
    ///Instantiates a PredMap.
936 938

	
937 939
    ///This function instantiates a \ref PredMap.
938 940
    ///\param g is the digraph, to which we would like to define the PredMap.
939 941
    ///\todo The digraph alone may be insufficient for the initialization
940 942
#ifdef DOXYGEN
941 943
    static PredMap *createPredMap(const GR &g)
942 944
#else
943 945
    static PredMap *createPredMap(const GR &)
944 946
#endif
945 947
    {
946 948
      return new PredMap();
947 949
    }
948 950
    ///The type of the map that stores whether a nodes is processed.
949 951

	
950 952
    ///The type of the map that stores whether a nodes is processed.
951 953
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
952 954
    ///By default it is a NullMap.
953 955
    ///\todo If it is set to a real map,
954 956
    ///Dijkstra::processed() should read this.
955 957
    ///\todo named parameter to set this type, function to read and write.
956 958
    typedef NullMap<typename Digraph::Node,bool> ProcessedMap;
957 959
    ///Instantiates a ProcessedMap.
958 960

	
959 961
    ///This function instantiates a \ref ProcessedMap.
960 962
    ///\param g is the digraph, to which
961 963
    ///we would like to define the \ref ProcessedMap
962 964
#ifdef DOXYGEN
963 965
    static ProcessedMap *createProcessedMap(const GR &g)
964 966
#else
965 967
    static ProcessedMap *createProcessedMap(const GR &)
966 968
#endif
967 969
    {
968 970
      return new ProcessedMap();
969 971
    }
970 972
    ///The type of the map that stores the dists of the nodes.
971 973

	
972 974
    ///The type of the map that stores the dists of the nodes.
973 975
    ///It must meet the \ref concepts::WriteMap "WriteMap" concept.
974 976
    ///
975 977
    typedef NullMap<typename Digraph::Node,typename LM::Value> DistMap;
976 978
    ///Instantiates a DistMap.
977 979

	
978 980
    ///This function instantiates a \ref DistMap.
979
    ///\param g is the digraph, to which we would like to define the \ref DistMap
981
    ///\param g is the digraph, to which we would like to define
982
    ///the \ref DistMap
980 983
#ifdef DOXYGEN
981 984
    static DistMap *createDistMap(const GR &g)
982 985
#else
983 986
    static DistMap *createDistMap(const GR &)
984 987
#endif
985 988
    {
986 989
      return new DistMap();
987 990
    }
988 991
  };
989 992

	
990 993
  /// Default traits used by \ref DijkstraWizard
991 994

	
992 995
  /// To make it easier to use Dijkstra algorithm
993 996
  ///we have created a wizard class.
994 997
  /// This \ref DijkstraWizard class needs default traits,
995 998
  ///as well as the \ref Dijkstra class.
996 999
  /// The \ref DijkstraWizardBase is a class to be the default traits of the
997 1000
  /// \ref DijkstraWizard class.
998 1001
  /// \todo More named parameters are required...
999 1002
  template<class GR,class LM>
1000 1003
  class DijkstraWizardBase : public DijkstraWizardDefaultTraits<GR,LM>
1001 1004
  {
1002 1005

	
1003 1006
    typedef DijkstraWizardDefaultTraits<GR,LM> Base;
1004 1007
  protected:
1005 1008
    /// Type of the nodes in the digraph.
1006 1009
    typedef typename Base::Digraph::Node Node;
1007 1010

	
1008 1011
    /// Pointer to the underlying digraph.
1009 1012
    void *_g;
1010 1013
    /// Pointer to the length map
1011 1014
    void *_length;
1012 1015
    ///Pointer to the map of predecessors arcs.
1013 1016
    void *_pred;
1014 1017
    ///Pointer to the map of distances.
1015 1018
    void *_dist;
1016 1019
    ///Pointer to the source node.
1017 1020
    Node _source;
1018 1021

	
1019 1022
    public:
1020 1023
    /// Constructor.
1021 1024

	
1022 1025
    /// This constructor does not require parameters, therefore it initiates
1023 1026
    /// all of the attributes to default values (0, INVALID).
1024 1027
    DijkstraWizardBase() : _g(0), _length(0), _pred(0),
1025 1028
                           _dist(0), _source(INVALID) {}
1026 1029

	
1027 1030
    /// Constructor.
1028 1031

	
1029 1032
    /// This constructor requires some parameters,
1030 1033
    /// listed in the parameters list.
1031 1034
    /// Others are initiated to 0.
1032 1035
    /// \param g is the initial value of  \ref _g
1033 1036
    /// \param l is the initial value of  \ref _length
1034 1037
    /// \param s is the initial value of  \ref _source
1035 1038
    DijkstraWizardBase(const GR &g,const LM &l, Node s=INVALID) :
1036 1039
      _g(reinterpret_cast<void*>(const_cast<GR*>(&g))),
1037 1040
      _length(reinterpret_cast<void*>(const_cast<LM*>(&l))),
1038 1041
      _pred(0), _dist(0), _source(s) {}
1039 1042

	
1040 1043
  };
1041 1044

	
1042 1045
  /// A class to make the usage of Dijkstra algorithm easier
1043 1046

	
1044 1047
  /// This class is created to make it easier to use Dijkstra algorithm.
1045 1048
  /// It uses the functions and features of the plain \ref Dijkstra,
1046 1049
  /// but it is much simpler to use it.
1047 1050
  ///
1048 1051
  /// Simplicity means that the way to change the types defined
1049 1052
  /// in the traits class is based on functions that returns the new class
1050 1053
  /// and not on templatable built-in classes.
1051 1054
  /// When using the plain \ref Dijkstra
1052 1055
  /// the new class with the modified type comes from
1053 1056
  /// the original class by using the ::
1054 1057
  /// operator. In the case of \ref DijkstraWizard only
1055 1058
  /// a function have to be called and it will
1056 1059
  /// return the needed class.
1057 1060
  ///
1058 1061
  /// It does not have own \ref run method. When its \ref run method is called
1059 1062
  /// it initiates a plain \ref Dijkstra class, and calls the \ref
1060 1063
  /// Dijkstra::run method of it.
1061 1064
  template<class TR>
1062 1065
  class DijkstraWizard : public TR
1063 1066
  {
1064 1067
    typedef TR Base;
1065 1068

	
1066 1069
    ///The type of the underlying digraph.
1067 1070
    typedef typename TR::Digraph Digraph;
1068 1071
    //\e
1069 1072
    typedef typename Digraph::Node Node;
1070 1073
    //\e
1071 1074
    typedef typename Digraph::NodeIt NodeIt;
1072 1075
    //\e
1073 1076
    typedef typename Digraph::Arc Arc;
1074 1077
    //\e
1075 1078
    typedef typename Digraph::OutArcIt OutArcIt;
1076 1079

	
1077 1080
    ///The type of the map that stores the arc lengths.
1078 1081
    typedef typename TR::LengthMap LengthMap;
1079 1082
    ///The type of the length of the arcs.
1080 1083
    typedef typename LengthMap::Value Value;
1081 1084
    ///\brief The type of the map that stores the last
1082 1085
    ///arcs of the shortest paths.
1083 1086
    typedef typename TR::PredMap PredMap;
1084 1087
    ///The type of the map that stores the dists of the nodes.
1085 1088
    typedef typename TR::DistMap DistMap;
1086 1089
    ///The heap type used by the dijkstra algorithm.
1087 1090
    typedef typename TR::Heap Heap;
1088 1091
  public:
1089 1092
    /// Constructor.
1090 1093
    DijkstraWizard() : TR() {}
1091 1094

	
1092 1095
    /// Constructor that requires parameters.
1093 1096

	
1094 1097
    /// Constructor that requires parameters.
1095 1098
    /// These parameters will be the default values for the traits class.
1096 1099
    DijkstraWizard(const Digraph &g,const LengthMap &l, Node s=INVALID) :
1097 1100
      TR(g,l,s) {}
1098 1101

	
1099 1102
    ///Copy constructor
1100 1103
    DijkstraWizard(const TR &b) : TR(b) {}
1101 1104

	
1102 1105
    ~DijkstraWizard() {}
1103 1106

	
1104 1107
    ///Runs Dijkstra algorithm from a given node.
1105 1108

	
1106 1109
    ///Runs Dijkstra algorithm from a given node.
1107 1110
    ///The node can be given by the \ref source function.
1108 1111
    void run()
1109 1112
    {
1110 1113
      if(Base::_source==INVALID) throw UninitializedParameter();
1111 1114
      Dijkstra<Digraph,LengthMap,TR>
1112 1115
        dij(*reinterpret_cast<const Digraph*>(Base::_g),
1113 1116
            *reinterpret_cast<const LengthMap*>(Base::_length));
1114 1117
      if(Base::_pred) dij.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1115 1118
      if(Base::_dist) dij.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1116 1119
      dij.run(Base::_source);
1117 1120
    }
1118 1121

	
1119 1122
    ///Runs Dijkstra algorithm from the given node.
1120 1123

	
1121 1124
    ///Runs Dijkstra algorithm from the given node.
1122 1125
    ///\param s is the given source.
1123 1126
    void run(Node s)
1124 1127
    {
1125 1128
      Base::_source=s;
1126 1129
      run();
1127 1130
    }
1128 1131

	
1129 1132
    template<class T>
1130 1133
    struct DefPredMapBase : public Base {
1131 1134
      typedef T PredMap;
1132 1135
      static PredMap *createPredMap(const Digraph &) { return 0; };
1133 1136
      DefPredMapBase(const TR &b) : TR(b) {}
1134 1137
    };
1135 1138

	
1136 1139
    ///\brief \ref named-templ-param "Named parameter"
1137 1140
    ///function for setting PredMap type
1138 1141
    ///
1139 1142
    /// \ref named-templ-param "Named parameter"
1140 1143
    ///function for setting PredMap type
1141 1144
    ///
1142 1145
    template<class T>
1143 1146
    DijkstraWizard<DefPredMapBase<T> > predMap(const T &t)
1144 1147
    {
1145 1148
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1146 1149
      return DijkstraWizard<DefPredMapBase<T> >(*this);
1147 1150
    }
1148 1151

	
1149 1152
    template<class T>
1150 1153
    struct DefDistMapBase : public Base {
1151 1154
      typedef T DistMap;
1152 1155
      static DistMap *createDistMap(const Digraph &) { return 0; };
1153 1156
      DefDistMapBase(const TR &b) : TR(b) {}
1154 1157
    };
1155 1158

	
1156 1159
    ///\brief \ref named-templ-param "Named parameter"
1157 1160
    ///function for setting DistMap type
1158 1161
    ///
1159 1162
    /// \ref named-templ-param "Named parameter"
1160 1163
    ///function for setting DistMap type
1161 1164
    ///
1162 1165
    template<class T>
1163 1166
    DijkstraWizard<DefDistMapBase<T> > distMap(const T &t)
1164 1167
    {
1165 1168
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1166 1169
      return DijkstraWizard<DefDistMapBase<T> >(*this);
1167 1170
    }
1168 1171

	
1169 1172
    /// Sets the source node, from which the Dijkstra algorithm runs.
1170 1173

	
1171 1174
    /// Sets the source node, from which the Dijkstra algorithm runs.
1172 1175
    /// \param s is the source node.
1173 1176
    DijkstraWizard<TR> &source(Node s)
1174 1177
    {
1175 1178
      Base::_source=s;
1176 1179
      return *this;
1177 1180
    }
1178 1181

	
1179 1182
  };
1180 1183

	
1181 1184
  ///Function type interface for Dijkstra algorithm.
1182 1185

	
1183 1186
  /// \ingroup shortest_path
1184 1187
  ///Function type interface for Dijkstra algorithm.
1185 1188
  ///
1186 1189
  ///This function also has several
1187 1190
  ///\ref named-templ-func-param "named parameters",
1188 1191
  ///they are declared as the members of class \ref DijkstraWizard.
1189 1192
  ///The following
1190 1193
  ///example shows how to use these parameters.
1191 1194
  ///\code
1192 1195
  ///  dijkstra(g,length,source).predMap(preds).run();
1193 1196
  ///\endcode
1194 1197
  ///\warning Don't forget to put the \ref DijkstraWizard::run() "run()"
1195 1198
  ///to the end of the parameter list.
1196 1199
  ///\sa DijkstraWizard
1197 1200
  ///\sa Dijkstra
1198 1201
  template<class GR, class LM>
1199 1202
  DijkstraWizard<DijkstraWizardBase<GR,LM> >
1200 1203
  dijkstra(const GR &g,const LM &l,typename GR::Node s=INVALID)
1201 1204
  {
1202 1205
    return DijkstraWizard<DijkstraWizardBase<GR,LM> >(g,l,s);
1203 1206
  }
1204 1207

	
1205 1208
} //END OF NAMESPACE LEMON
1206 1209

	
1207 1210
#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_GRAPH_TO_EPS_H
20 20
#define LEMON_GRAPH_TO_EPS_H
21 21

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

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

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

	
44 44

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

	
49 49
namespace lemon {
50 50

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

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

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

	
80 80

	
81 81
  const Graph &g;
82 82

	
83 83
  std::ostream& os;
84 84

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

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

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

	
95 95
  double _arcWidthScale;
96 96

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

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

	
105 105
  bool _showNodes, _showArcs;
106 106

	
107 107
  bool _enableParallel;
108 108
  double _parArcDist;
109 109

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

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

	
118 118
  bool _undirected;
119 119

	
120 120
  bool _pleaseRemoveOsStream;
121 121

	
122 122
  bool _scaleToA4;
123 123

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

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

	
131 131
  bool _autoNodeScale;
132 132
  bool _autoArcWidthScale;
133 133

	
134 134
  bool _absoluteNodeSizes;
135 135
  bool _absoluteArcWidths;
136 136

	
137 137
  bool _negY;
138 138

	
139 139
  bool _preScale;
140 140
  ///Constructor
141 141

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

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

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

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

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

	
198 199
  using T::_drawArrows;
199 200
  using T::_arrowLength;
200 201
  using T::_arrowWidth;
201 202

	
202 203
  using T::_showNodes;
203 204
  using T::_showArcs;
204 205

	
205 206
  using T::_enableParallel;
206 207
  using T::_parArcDist;
207 208

	
208 209
  using T::_showNodeText;
209 210
  using T::_nodeTexts;
210 211
  using T::_nodeTextSize;
211 212

	
212 213
  using T::_showNodePsText;
213 214
  using T::_nodePsTexts;
214 215
  using T::_nodePsTextsPreamble;
215 216

	
216 217
  using T::_undirected;
217 218

	
218 219
  using T::_pleaseRemoveOsStream;
219 220

	
220 221
  using T::_scaleToA4;
221 222

	
222 223
  using T::_title;
223 224
  using T::_copyright;
224 225

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

	
232 233
  using T::_autoNodeScale;
233 234
  using T::_autoArcWidthScale;
234 235

	
235 236
  using T::_absoluteNodeSizes;
236 237
  using T::_absoluteArcWidths;
237 238

	
238 239

	
239 240
  using T::_negY;
240 241
  using T::_preScale;
241 242

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

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

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

	
257 258
  bool dontPrint;
258 259

	
259 260
public:
260 261
  ///Node shapes
261 262

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
501 502
  ///Turns on/off the absolutematic node size scaling.
502 503

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

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

	
516 517
  ///Turn on/off pre-scaling
517 518

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

	
527 528
  ///Sets a global scale factor for arc widths
528 529

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

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

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

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

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

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

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

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

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

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

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

	
602 603
  ///Gives a preamble block for node Postscript block.
603 604

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

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

	
619 620
  ///Sets whether the graph is directed
620 621

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

	
629 630
  ///Sets the title.
630 631

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

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

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

	
658 659
public:
659 660
  ~GraphToEps() { }
660 661

	
661 662
  ///Draws the graph.
662 663

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

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

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

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

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

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

	
705 706
    if (_autoArcWidthScale) {
706 707
      double max_w=0;
707 708
      for(ArcIt e(g);e!=INVALID;++e)
708 709
        max_w=std::max(double(_arcWidths[e]),max_w);
709 710
      //\todo better 'epsilon' would be nice here.
710 711
      if(max_w>EPSILON) {
711 712
        _arcWidthScale/=max_w;
712 713
      }
713 714
    }
714 715

	
715 716
    if (_autoNodeScale) {
716 717
      double max_s=0;
717 718
      for(NodeIt n(g);n!=INVALID;++n)
718 719
        max_s=std::max(double(_nodeSizes[n]),max_s);
719 720
      //\todo better 'epsilon' would be nice here.
720 721
      if(max_s>EPSILON) {
721 722
        _nodeScale/=max_s;
722 723
      }
723 724
    }
724 725

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

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

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

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

	
779 780
    os << "%%EndComments\n";
780 781

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

	
835 841

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

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

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

	
890 897
        typename std::vector<Arc>::iterator j;
891 898
        for(typename std::vector<Arc>::iterator i=el.begin();i!=el.end();i=j) {
892 899
          for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
893 900

	
894 901
          double sw=0;
895 902
          for(typename std::vector<Arc>::iterator e=i;e!=j;++e)
896 903
            sw+=_arcWidths[*e]*_arcWidthScale+_parArcDist;
897 904
          sw-=_parArcDist;
898 905
          sw/=-2.0;
899 906
          dim2::Point<double>
900 907
            dvec(mycoords[g.target(*i)]-mycoords[g.source(*i)]);
901 908
          double l=std::sqrt(dvec.normSquare());
902 909
          //\todo better 'epsilon' would be nice here.
903 910
          dim2::Point<double> d(dvec/std::max(l,EPSILON));
904 911
           dim2::Point<double> m;
905
//           m=dim2::Point<double>(mycoords[g.target(*i)]+mycoords[g.source(*i)])/2.0;
912
//           m=dim2::Point<double>(mycoords[g.target(*i)]+
913
//                                 mycoords[g.source(*i)])/2.0;
906 914

	
907 915
//            m=dim2::Point<double>(mycoords[g.source(*i)])+
908 916
//             dvec*(double(_nodeSizes[g.source(*i)])/
909 917
//                (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
910 918

	
911 919
           m=dim2::Point<double>(mycoords[g.source(*i)])+
912 920
            d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
913 921

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

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

	
1063 1072
    os << "grestore\nshowpage\n";
1064 1073

	
1065 1074
    //CleanUp:
1066 1075
    if(_pleaseRemoveOsStream) {delete &os;}
1067 1076
  }
1068 1077

	
1069 1078
  ///\name Aliases
1070 1079
  ///These are just some aliases to other parameter setting functions.
1071 1080

	
1072 1081
  ///@{
1073 1082

	
1074 1083
  ///An alias for arcWidths()
1075 1084
  template<class X> GraphToEps<ArcWidthsTraits<X> > edgeWidths(const X &x)
1076 1085
  {
1077 1086
    return arcWidths(x);
1078 1087
  }
1079 1088

	
1080 1089
  ///An alias for arcColors()
1081 1090
  template<class X> GraphToEps<ArcColorsTraits<X> >
1082 1091
  edgeColors(const X &x)
1083 1092
  {
1084 1093
    return arcColors(x);
1085 1094
  }
1086 1095

	
1087 1096
  ///An alias for arcWidthScale()
1088 1097
  GraphToEps<T> &edgeWidthScale(double d) {return arcWidthScale(d);}
1089 1098

	
1090 1099
  ///An alias for autoArcWidthScale()
1091 1100
  GraphToEps<T> &autoEdgeWidthScale(bool b=true)
1092 1101
  {
1093 1102
    return autoArcWidthScale(b);
1094 1103
  }
1095 1104

	
1096 1105
  ///An alias for absoluteArcWidths()
1097 1106
  GraphToEps<T> &absoluteEdgeWidths(bool b=true)
1098 1107
  {
1099 1108
    return absoluteArcWidths(b);
1100 1109
  }
1101 1110

	
1102 1111
  ///An alias for parArcDist()
1103 1112
  GraphToEps<T> &parEdgeDist(double d) {return parArcDist(d);}
1104 1113

	
1105 1114
  ///An alias for hideArcs()
1106 1115
  GraphToEps<T> &hideEdges(bool b=true) {return hideArcs(b);}
1107 1116

	
1108 1117
  ///@}
1109 1118
};
1110 1119

	
1111 1120
template<class T>
1112 1121
const int GraphToEps<T>::INTERPOL_PREC = 20;
1113 1122
template<class T>
1114 1123
const double GraphToEps<T>::A4HEIGHT = 841.8897637795276;
1115 1124
template<class T>
1116 1125
const double GraphToEps<T>::A4WIDTH  = 595.275590551181;
1117 1126
template<class T>
1118 1127
const double GraphToEps<T>::A4BORDER = 15;
1119 1128

	
1120 1129

	
1121 1130
///Generates an EPS file from a graph
1122 1131

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

	
1153 1162
///Generates an EPS file from a graph
1154 1163

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

	
1169 1178
///Generates an EPS file from a graph
1170 1179

	
1171 1180
///\ingroup eps_io
1172 1181
///This function does the same as
1173 1182
///\ref graphToEps(G &g,std::ostream& os)
1174 1183
///but it writes its output into the file \c file_name
1175 1184
///instead of a stream.
1176 1185
///\sa graphToEps(G &g, std::ostream& os)
1177 1186
template<class G>
1178 1187
GraphToEps<DefaultGraphToEpsTraits<G> >
1179 1188
graphToEps(G &g,const std::string& file_name)
1180 1189
{
1181 1190
  return GraphToEps<DefaultGraphToEpsTraits<G> >
1182 1191
    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name.c_str()),true));
1183 1192
}
1184 1193

	
1185 1194
} //END OF NAMESPACE LEMON
1186 1195

	
1187 1196
#endif // LEMON_GRAPH_TO_EPS_H

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

0 comments (0 inline)