gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Add citations to the min mean cycle classes (#179, #184)
0 4 0
default
4 files changed with 13 insertions and 7 deletions:
↑ Collapse diff ↑
Ignore white space 6 line context
... ...
@@ -76,687 +76,690 @@
76 76

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
228 228
/**
229 229
@defgroup paths Path Structures
230 230
@ingroup datas
231 231
\brief %Path structures implemented in LEMON.
232 232

	
233 233
This group contains the path structures implemented in LEMON.
234 234

	
235 235
LEMON provides flexible data structures to work with paths.
236 236
All of them have similar interfaces and they can be copied easily with
237 237
assignment operators and copy constructors. This makes it easy and
238 238
efficient to have e.g. the Dijkstra algorithm to store its result in
239 239
any kind of path structure.
240 240

	
241 241
\sa \ref concepts::Path "Path concept"
242 242
*/
243 243

	
244 244
/**
245 245
@defgroup heaps Heap Structures
246 246
@ingroup datas
247 247
\brief %Heap structures implemented in LEMON.
248 248

	
249 249
This group contains the heap structures implemented in LEMON.
250 250

	
251 251
LEMON provides several heap classes. They are efficient implementations
252 252
of the abstract data type \e priority \e queue. They store items with
253 253
specified values called \e priorities in such a way that finding and
254 254
removing the item with minimum priority are efficient.
255 255
The basic operations are adding and erasing items, changing the priority
256 256
of an item, etc.
257 257

	
258 258
Heaps are crucial in several algorithms, such as Dijkstra and Prim.
259 259
The heap implementations have the same interface, thus any of them can be
260 260
used easily in such algorithms.
261 261

	
262 262
\sa \ref concepts::Heap "Heap concept"
263 263
*/
264 264

	
265 265
/**
266 266
@defgroup matrices Matrices
267 267
@ingroup datas
268 268
\brief Two dimensional data storages implemented in LEMON.
269 269

	
270 270
This group contains two dimensional data storages implemented in LEMON.
271 271
*/
272 272

	
273 273
/**
274 274
@defgroup auxdat Auxiliary Data Structures
275 275
@ingroup datas
276 276
\brief Auxiliary data structures implemented in LEMON.
277 277

	
278 278
This group contains some data structures implemented in LEMON in
279 279
order to make it easier to implement combinatorial algorithms.
280 280
*/
281 281

	
282 282
/**
283 283
@defgroup geomdat Geometric Data Structures
284 284
@ingroup auxdat
285 285
\brief Geometric data structures implemented in LEMON.
286 286

	
287 287
This group contains geometric data structures implemented in LEMON.
288 288

	
289 289
 - \ref lemon::dim2::Point "dim2::Point" implements a two dimensional
290 290
   vector with the usual operations.
291 291
 - \ref lemon::dim2::Box "dim2::Box" can be used to determine the
292 292
   rectangular bounding box of a set of \ref lemon::dim2::Point
293 293
   "dim2::Point"'s.
294 294
*/
295 295

	
296 296
/**
297 297
@defgroup matrices Matrices
298 298
@ingroup auxdat
299 299
\brief Two dimensional data storages implemented in LEMON.
300 300

	
301 301
This group contains two dimensional data storages implemented in LEMON.
302 302
*/
303 303

	
304 304
/**
305 305
@defgroup algs Algorithms
306 306
\brief This group contains the several algorithms
307 307
implemented in LEMON.
308 308

	
309 309
This group contains the several algorithms
310 310
implemented in LEMON.
311 311
*/
312 312

	
313 313
/**
314 314
@defgroup search Graph Search
315 315
@ingroup algs
316 316
\brief Common graph search algorithms.
317 317

	
318 318
This group contains the common graph search algorithms, namely
319 319
\e breadth-first \e search (BFS) and \e depth-first \e search (DFS)
320 320
\ref clrs01algorithms.
321 321
*/
322 322

	
323 323
/**
324 324
@defgroup shortest_path Shortest Path Algorithms
325 325
@ingroup algs
326 326
\brief Algorithms for finding shortest paths.
327 327

	
328 328
This group contains the algorithms for finding shortest paths in digraphs
329 329
\ref clrs01algorithms.
330 330

	
331 331
 - \ref Dijkstra algorithm for finding shortest paths from a source node
332 332
   when all arc lengths are non-negative.
333 333
 - \ref BellmanFord "Bellman-Ford" algorithm for finding shortest paths
334 334
   from a source node when arc lenghts can be either positive or negative,
335 335
   but the digraph should not contain directed cycles with negative total
336 336
   length.
337 337
 - \ref FloydWarshall "Floyd-Warshall" and \ref Johnson "Johnson" algorithms
338 338
   for solving the \e all-pairs \e shortest \e paths \e problem when arc
339 339
   lenghts can be either positive or negative, but the digraph should
340 340
   not contain directed cycles with negative total length.
341 341
 - \ref Suurballe A successive shortest path algorithm for finding
342 342
   arc-disjoint paths between two nodes having minimum total length.
343 343
*/
344 344

	
345 345
/**
346 346
@defgroup spantree Minimum Spanning Tree Algorithms
347 347
@ingroup algs
348 348
\brief Algorithms for finding minimum cost spanning trees and arborescences.
349 349

	
350 350
This group contains the algorithms for finding minimum cost spanning
351 351
trees and arborescences \ref clrs01algorithms.
352 352
*/
353 353

	
354 354
/**
355 355
@defgroup max_flow Maximum Flow Algorithms
356 356
@ingroup algs
357 357
\brief Algorithms for finding maximum flows.
358 358

	
359 359
This group contains the algorithms for finding maximum flows and
360 360
feasible circulations \ref clrs01algorithms, \ref amo93networkflows.
361 361

	
362 362
The \e maximum \e flow \e problem is to find a flow of maximum value between
363 363
a single source and a single target. Formally, there is a \f$G=(V,A)\f$
364 364
digraph, a \f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function and
365 365
\f$s, t \in V\f$ source and target nodes.
366 366
A maximum flow is an \f$f: A\rightarrow\mathbf{R}^+_0\f$ solution of the
367 367
following optimization problem.
368 368

	
369 369
\f[ \max\sum_{sv\in A} f(sv) - \sum_{vs\in A} f(vs) \f]
370 370
\f[ \sum_{uv\in A} f(uv) = \sum_{vu\in A} f(vu)
371 371
    \quad \forall u\in V\setminus\{s,t\} \f]
372 372
\f[ 0 \leq f(uv) \leq cap(uv) \quad \forall uv\in A \f]
373 373

	
374 374
LEMON contains several algorithms for solving maximum flow problems:
375 375
- \ref EdmondsKarp Edmonds-Karp algorithm
376 376
  \ref edmondskarp72theoretical.
377 377
- \ref Preflow Goldberg-Tarjan's preflow push-relabel algorithm
378 378
  \ref goldberg88newapproach.
379 379
- \ref DinitzSleatorTarjan Dinitz's blocking flow algorithm with dynamic trees
380 380
  \ref dinic70algorithm, \ref sleator83dynamic.
381 381
- \ref GoldbergTarjan !Preflow push-relabel algorithm with dynamic trees
382 382
  \ref goldberg88newapproach, \ref sleator83dynamic.
383 383

	
384 384
In most cases the \ref Preflow algorithm provides the
385 385
fastest method for computing a maximum flow. All implementations
386 386
also provide functions to query the minimum cut, which is the dual
387 387
problem of maximum flow.
388 388

	
389 389
\ref Circulation is a preflow push-relabel algorithm implemented directly 
390 390
for finding feasible circulations, which is a somewhat different problem,
391 391
but it is strongly related to maximum flow.
392 392
For more information, see \ref Circulation.
393 393
*/
394 394

	
395 395
/**
396 396
@defgroup min_cost_flow_algs Minimum Cost Flow Algorithms
397 397
@ingroup algs
398 398

	
399 399
\brief Algorithms for finding minimum cost flows and circulations.
400 400

	
401 401
This group contains the algorithms for finding minimum cost flows and
402 402
circulations \ref amo93networkflows. For more information about this
403 403
problem and its dual solution, see \ref min_cost_flow
404 404
"Minimum Cost Flow Problem".
405 405

	
406 406
LEMON contains several algorithms for this problem.
407 407
 - \ref NetworkSimplex Primal Network Simplex algorithm with various
408 408
   pivot strategies \ref dantzig63linearprog, \ref kellyoneill91netsimplex.
409 409
 - \ref CostScaling Push-Relabel and Augment-Relabel algorithms based on
410 410
   cost scaling \ref goldberg90approximation, \ref goldberg97efficient,
411 411
   \ref bunnagel98efficient.
412 412
 - \ref CapacityScaling Successive Shortest %Path algorithm with optional
413 413
   capacity scaling \ref edmondskarp72theoretical.
414 414
 - \ref CancelAndTighten The Cancel and Tighten algorithm
415 415
   \ref goldberg89cyclecanceling.
416 416
 - \ref CycleCanceling Cycle-Canceling algorithms
417 417
   \ref klein67primal, \ref goldberg89cyclecanceling.
418 418

	
419 419
In general NetworkSimplex is the most efficient implementation,
420 420
but in special cases other algorithms could be faster.
421 421
For example, if the total supply and/or capacities are rather small,
422 422
CapacityScaling is usually the fastest algorithm (without effective scaling).
423 423
*/
424 424

	
425 425
/**
426 426
@defgroup min_cut Minimum Cut Algorithms
427 427
@ingroup algs
428 428

	
429 429
\brief Algorithms for finding minimum cut in graphs.
430 430

	
431 431
This group contains the algorithms for finding minimum cut in graphs.
432 432

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

	
439 439
\f[ \min_{X \subset V, X\not\in \{\emptyset, V\}}
440 440
    \sum_{uv\in A: u\in X, v\not\in X}cap(uv) \f]
441 441

	
442 442
LEMON contains several algorithms related to minimum cut problems:
443 443

	
444 444
- \ref HaoOrlin "Hao-Orlin algorithm" for calculating minimum cut
445 445
  in directed graphs.
446 446
- \ref NagamochiIbaraki "Nagamochi-Ibaraki algorithm" for
447 447
  calculating minimum cut in undirected graphs.
448 448
- \ref GomoryHu "Gomory-Hu tree computation" for calculating
449 449
  all-pairs minimum cut in undirected graphs.
450 450

	
451 451
If you want to find minimum cut just between two distinict nodes,
452 452
see the \ref max_flow "maximum flow problem".
453 453
*/
454 454

	
455 455
/**
456 456
@defgroup min_mean_cycle Minimum Mean Cycle Algorithms
457 457
@ingroup algs
458 458
\brief Algorithms for finding minimum mean cycles.
459 459

	
460
This group contains the algorithms for finding minimum mean cycles.
460
This group contains the algorithms for finding minimum mean cycles
461
\ref clrs01algorithms, \ref amo93networkflows.
461 462

	
462 463
The \e minimum \e mean \e cycle \e problem is to find a directed cycle
463 464
of minimum mean length (cost) in a digraph.
464 465
The mean length of a cycle is the average length of its arcs, i.e. the
465 466
ratio between the total length of the cycle and the number of arcs on it.
466 467

	
467 468
This problem has an important connection to \e conservative \e length
468 469
\e functions, too. A length function on the arcs of a digraph is called
469 470
conservative if and only if there is no directed cycle of negative total
470 471
length. For an arbitrary length function, the negative of the minimum
471 472
cycle mean is the smallest \f$\epsilon\f$ value so that increasing the
472 473
arc lengths uniformly by \f$\epsilon\f$ results in a conservative length
473 474
function.
474 475

	
475 476
LEMON contains three algorithms for solving the minimum mean cycle problem:
476
- \ref Karp "Karp"'s original algorithm.
477
- \ref Karp "Karp"'s original algorithm \ref amo93networkflows,
478
  \ref dasdan98minmeancycle.
477 479
- \ref HartmannOrlin "Hartmann-Orlin"'s algorithm, which is an improved
478
  version of Karp's algorithm.
479
- \ref Howard "Howard"'s policy iteration algorithm.
480
  version of Karp's algorithm \ref dasdan98minmeancycle.
481
- \ref Howard "Howard"'s policy iteration algorithm
482
  \ref dasdan98minmeancycle.
480 483

	
481 484
In practice, the Howard algorithm proved to be by far the most efficient
482 485
one, though the best known theoretical bound on its running time is
483 486
exponential.
484 487
Both Karp and HartmannOrlin algorithms run in time O(ne) and use space
485 488
O(n<sup>2</sup>+e), but the latter one is typically faster due to the
486 489
applied early termination scheme.
487 490
*/
488 491

	
489 492
/**
490 493
@defgroup matching Matching Algorithms
491 494
@ingroup algs
492 495
\brief Algorithms for finding matchings in graphs and bipartite graphs.
493 496

	
494 497
This group contains the algorithms for calculating
495 498
matchings in graphs and bipartite graphs. The general matching problem is
496 499
finding a subset of the edges for which each node has at most one incident
497 500
edge.
498 501

	
499 502
There are several different algorithms for calculate matchings in
500 503
graphs.  The matching problems in bipartite graphs are generally
501 504
easier than in general graphs. The goal of the matching optimization
502 505
can be finding maximum cardinality, maximum weight or minimum cost
503 506
matching. The search can be constrained to find perfect or
504 507
maximum cardinality matching.
505 508

	
506 509
The matching algorithms implemented in LEMON:
507 510
- \ref MaxBipartiteMatching Hopcroft-Karp augmenting path algorithm
508 511
  for calculating maximum cardinality matching in bipartite graphs.
509 512
- \ref PrBipartiteMatching Push-relabel algorithm
510 513
  for calculating maximum cardinality matching in bipartite graphs.
511 514
- \ref MaxWeightedBipartiteMatching
512 515
  Successive shortest path algorithm for calculating maximum weighted
513 516
  matching and maximum weighted bipartite matching in bipartite graphs.
514 517
- \ref MinCostMaxBipartiteMatching
515 518
  Successive shortest path algorithm for calculating minimum cost maximum
516 519
  matching in bipartite graphs.
517 520
- \ref MaxMatching Edmond's blossom shrinking algorithm for calculating
518 521
  maximum cardinality matching in general graphs.
519 522
- \ref MaxWeightedMatching Edmond's blossom shrinking algorithm for calculating
520 523
  maximum weighted matching in general graphs.
521 524
- \ref MaxWeightedPerfectMatching
522 525
  Edmond's blossom shrinking algorithm for calculating maximum weighted
523 526
  perfect matching in general graphs.
524 527

	
525 528
\image html bipartite_matching.png
526 529
\image latex bipartite_matching.eps "Bipartite Matching" width=\textwidth
527 530
*/
528 531

	
529 532
/**
530 533
@defgroup graph_properties Connectivity and Other Graph Properties
531 534
@ingroup algs
532 535
\brief Algorithms for discovering the graph properties
533 536

	
534 537
This group contains the algorithms for discovering the graph properties
535 538
like connectivity, bipartiteness, euler property, simplicity etc.
536 539

	
537 540
\image html connected_components.png
538 541
\image latex connected_components.eps "Connected components" width=\textwidth
539 542
*/
540 543

	
541 544
/**
542 545
@defgroup planar Planarity Embedding and Drawing
543 546
@ingroup algs
544 547
\brief Algorithms for planarity checking, embedding and drawing
545 548

	
546 549
This group contains the algorithms for planarity checking,
547 550
embedding and drawing.
548 551

	
549 552
\image html planar.png
550 553
\image latex planar.eps "Plane graph" width=\textwidth
551 554
*/
552 555

	
553 556
/**
554 557
@defgroup approx Approximation Algorithms
555 558
@ingroup algs
556 559
\brief Approximation algorithms.
557 560

	
558 561
This group contains the approximation and heuristic algorithms
559 562
implemented in LEMON.
560 563
*/
561 564

	
562 565
/**
563 566
@defgroup auxalg Auxiliary Algorithms
564 567
@ingroup algs
565 568
\brief Auxiliary algorithms implemented in LEMON.
566 569

	
567 570
This group contains some algorithms implemented in LEMON
568 571
in order to make it easier to implement complex algorithms.
569 572
*/
570 573

	
571 574
/**
572 575
@defgroup gen_opt_group General Optimization Tools
573 576
\brief This group contains some general optimization frameworks
574 577
implemented in LEMON.
575 578

	
576 579
This group contains some general optimization frameworks
577 580
implemented in LEMON.
578 581
*/
579 582

	
580 583
/**
581 584
@defgroup lp_group LP and MIP Solvers
582 585
@ingroup gen_opt_group
583 586
\brief LP and MIP solver interfaces for LEMON.
584 587

	
585 588
This group contains LP and MIP solver interfaces for LEMON.
586 589
Various LP solvers could be used in the same manner with this
587 590
high-level interface.
588 591

	
589 592
The currently supported solvers are \ref glpk, \ref clp, \ref cbc,
590 593
\ref cplex, \ref soplex.
591 594
*/
592 595

	
593 596
/**
594 597
@defgroup lp_utils Tools for Lp and Mip Solvers
595 598
@ingroup lp_group
596 599
\brief Helper tools to the Lp and Mip solvers.
597 600

	
598 601
This group adds some helper tools to general optimization framework
599 602
implemented in LEMON.
600 603
*/
601 604

	
602 605
/**
603 606
@defgroup metah Metaheuristics
604 607
@ingroup gen_opt_group
605 608
\brief Metaheuristics for LEMON library.
606 609

	
607 610
This group contains some metaheuristic optimization tools.
608 611
*/
609 612

	
610 613
/**
611 614
@defgroup utils Tools and Utilities
612 615
\brief Tools and utilities for programming in LEMON
613 616

	
614 617
Tools and utilities for programming in LEMON.
615 618
*/
616 619

	
617 620
/**
618 621
@defgroup gutils Basic Graph Utilities
619 622
@ingroup utils
620 623
\brief Simple basic graph utilities.
621 624

	
622 625
This group contains some simple basic graph utilities.
623 626
*/
624 627

	
625 628
/**
626 629
@defgroup misc Miscellaneous Tools
627 630
@ingroup utils
628 631
\brief Tools for development, debugging and testing.
629 632

	
630 633
This group contains several useful tools for development,
631 634
debugging and testing.
632 635
*/
633 636

	
634 637
/**
635 638
@defgroup timecount Time Measuring and Counting
636 639
@ingroup misc
637 640
\brief Simple tools for measuring the performance of algorithms.
638 641

	
639 642
This group contains simple tools for measuring the performance
640 643
of algorithms.
641 644
*/
642 645

	
643 646
/**
644 647
@defgroup exceptions Exceptions
645 648
@ingroup utils
646 649
\brief Exceptions defined in LEMON.
647 650

	
648 651
This group contains the exceptions defined in LEMON.
649 652
*/
650 653

	
651 654
/**
652 655
@defgroup io_group Input-Output
653 656
\brief Graph Input-Output methods
654 657

	
655 658
This group contains the tools for importing and exporting graphs
656 659
and graph related data. Now it supports the \ref lgf-format
657 660
"LEMON Graph Format", the \c DIMACS format and the encapsulated
658 661
postscript (EPS) format.
659 662
*/
660 663

	
661 664
/**
662 665
@defgroup lemon_io LEMON Graph Format
663 666
@ingroup io_group
664 667
\brief Reading and writing LEMON Graph Format.
665 668

	
666 669
This group contains methods for reading and writing
667 670
\ref lgf-format "LEMON Graph Format".
668 671
*/
669 672

	
670 673
/**
671 674
@defgroup eps_io Postscript Exporting
672 675
@ingroup io_group
673 676
\brief General \c EPS drawer and graph exporter
674 677

	
675 678
This group contains general \c EPS drawing methods and special
676 679
graph exporting tools.
677 680
*/
678 681

	
679 682
/**
680 683
@defgroup dimacs_group DIMACS Format
681 684
@ingroup io_group
682 685
\brief Read and write files in DIMACS format
683 686

	
684 687
Tools to read a digraph from or write it to a file in DIMACS format data.
685 688
*/
686 689

	
687 690
/**
688 691
@defgroup nauty_group NAUTY Format
689 692
@ingroup io_group
690 693
\brief Read \e Nauty format
691 694

	
692 695
Tool to read graphs from \e Nauty format data.
693 696
*/
694 697

	
695 698
/**
696 699
@defgroup concept Concepts
697 700
\brief Skeleton classes and concept checking classes
698 701

	
699 702
This group contains the data/algorithm skeletons and concept checking
700 703
classes implemented in LEMON.
701 704

	
702 705
The purpose of the classes in this group is fourfold.
703 706

	
704 707
- These classes contain the documentations of the %concepts. In order
705 708
  to avoid document multiplications, an implementation of a concept
706 709
  simply refers to the corresponding concept class.
707 710

	
708 711
- These classes declare every functions, <tt>typedef</tt>s etc. an
709 712
  implementation of the %concepts should provide, however completely
710 713
  without implementations and real data structures behind the
711 714
  interface. On the other hand they should provide nothing else. All
712 715
  the algorithms working on a data structure meeting a certain concept
713 716
  should compile with these classes. (Though it will not run properly,
714 717
  of course.) In this way it is easily to check if an algorithm
715 718
  doesn't use any extra feature of a certain implementation.
716 719

	
717 720
- The concept descriptor classes also provide a <em>checker class</em>
718 721
  that makes it possible to check whether a certain implementation of a
719 722
  concept indeed provides all the required features.
720 723

	
721 724
- Finally, They can serve as a skeleton of a new implementation of a concept.
722 725
*/
723 726

	
724 727
/**
725 728
@defgroup graph_concepts Graph Structure Concepts
726 729
@ingroup concept
727 730
\brief Skeleton and concept checking classes for graph structures
728 731

	
729 732
This group contains the skeletons and concept checking classes of
730 733
graph structures.
731 734
*/
732 735

	
733 736
/**
734 737
@defgroup map_concepts Map Concepts
735 738
@ingroup concept
736 739
\brief Skeleton and concept checking classes for maps
737 740

	
738 741
This group contains the skeletons and concept checking classes of maps.
739 742
*/
740 743

	
741 744
/**
742 745
@defgroup tools Standalone Utility Applications
743 746

	
744 747
Some utility applications are listed here.
745 748

	
746 749
The standard compilation procedure (<tt>./configure;make</tt>) will compile
747 750
them, as well.
748 751
*/
749 752

	
750 753
/**
751 754
\anchor demoprograms
752 755

	
753 756
@defgroup demos Demo Programs
754 757

	
755 758
Some demo programs are listed here. Their full source codes can be found in
756 759
the \c demo subdirectory of the source tree.
757 760

	
758 761
In order to compile them, use the <tt>make demo</tt> or the
759 762
<tt>make check</tt> commands.
760 763
*/
761 764

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

	
19 19
#ifndef LEMON_HARTMANN_ORLIN_H
20 20
#define LEMON_HARTMANN_ORLIN_H
21 21

	
22 22
/// \ingroup min_mean_cycle
23 23
///
24 24
/// \file
25 25
/// \brief Hartmann-Orlin's algorithm for finding a minimum mean cycle.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <lemon/core.h>
30 30
#include <lemon/path.h>
31 31
#include <lemon/tolerance.h>
32 32
#include <lemon/connectivity.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default traits class of HartmannOrlin algorithm.
37 37
  ///
38 38
  /// Default traits class of HartmannOrlin algorithm.
39 39
  /// \tparam GR The type of the digraph.
40 40
  /// \tparam LEN The type of the length map.
41 41
  /// It must conform to the \ref concepts::Rea_data "Rea_data" concept.
42 42
#ifdef DOXYGEN
43 43
  template <typename GR, typename LEN>
44 44
#else
45 45
  template <typename GR, typename LEN,
46 46
    bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
47 47
#endif
48 48
  struct HartmannOrlinDefaultTraits
49 49
  {
50 50
    /// The type of the digraph
51 51
    typedef GR Digraph;
52 52
    /// The type of the length map
53 53
    typedef LEN LengthMap;
54 54
    /// The type of the arc lengths
55 55
    typedef typename LengthMap::Value Value;
56 56

	
57 57
    /// \brief The large value type used for internal computations
58 58
    ///
59 59
    /// The large value type used for internal computations.
60 60
    /// It is \c long \c long if the \c Value type is integer,
61 61
    /// otherwise it is \c double.
62 62
    /// \c Value must be convertible to \c LargeValue.
63 63
    typedef double LargeValue;
64 64

	
65 65
    /// The tolerance type used for internal computations
66 66
    typedef lemon::Tolerance<LargeValue> Tolerance;
67 67

	
68 68
    /// \brief The path type of the found cycles
69 69
    ///
70 70
    /// The path type of the found cycles.
71 71
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
72 72
    /// and it must have an \c addBack() function.
73 73
    typedef lemon::Path<Digraph> Path;
74 74
  };
75 75

	
76 76
  // Default traits class for integer value types
77 77
  template <typename GR, typename LEN>
78 78
  struct HartmannOrlinDefaultTraits<GR, LEN, true>
79 79
  {
80 80
    typedef GR Digraph;
81 81
    typedef LEN LengthMap;
82 82
    typedef typename LengthMap::Value Value;
83 83
#ifdef LEMON_HAVE_LONG_LONG
84 84
    typedef long long LargeValue;
85 85
#else
86 86
    typedef long LargeValue;
87 87
#endif
88 88
    typedef lemon::Tolerance<LargeValue> Tolerance;
89 89
    typedef lemon::Path<Digraph> Path;
90 90
  };
91 91

	
92 92

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

	
96 96
  /// \brief Implementation of the Hartmann-Orlin algorithm for finding
97 97
  /// a minimum mean cycle.
98 98
  ///
99 99
  /// This class implements the Hartmann-Orlin algorithm for finding
100
  /// a directed cycle of minimum mean length (cost) in a digraph.
100
  /// a directed cycle of minimum mean length (cost) in a digraph
101
  /// \ref amo93networkflows, \ref dasdan98minmeancycle.
101 102
  /// It is an improved version of \ref Karp "Karp"'s original algorithm,
102 103
  /// it applies an efficient early termination scheme.
103 104
  /// It runs in time O(ne) and uses space O(n<sup>2</sup>+e).
104 105
  ///
105 106
  /// \tparam GR The type of the digraph the algorithm runs on.
106 107
  /// \tparam LEN The type of the length map. The default
107 108
  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
108 109
#ifdef DOXYGEN
109 110
  template <typename GR, typename LEN, typename TR>
110 111
#else
111 112
  template < typename GR,
112 113
             typename LEN = typename GR::template ArcMap<int>,
113 114
             typename TR = HartmannOrlinDefaultTraits<GR, LEN> >
114 115
#endif
115 116
  class HartmannOrlin
116 117
  {
117 118
  public:
118 119

	
119 120
    /// The type of the digraph
120 121
    typedef typename TR::Digraph Digraph;
121 122
    /// The type of the length map
122 123
    typedef typename TR::LengthMap LengthMap;
123 124
    /// The type of the arc lengths
124 125
    typedef typename TR::Value Value;
125 126

	
126 127
    /// \brief The large value type
127 128
    ///
128 129
    /// The large value type used for internal computations.
129 130
    /// Using the \ref HartmannOrlinDefaultTraits "default traits class",
130 131
    /// it is \c long \c long if the \c Value type is integer,
131 132
    /// otherwise it is \c double.
132 133
    typedef typename TR::LargeValue LargeValue;
133 134

	
134 135
    /// The tolerance type
135 136
    typedef typename TR::Tolerance Tolerance;
136 137

	
137 138
    /// \brief The path type of the found cycles
138 139
    ///
139 140
    /// The path type of the found cycles.
140 141
    /// Using the \ref HartmannOrlinDefaultTraits "default traits class",
141 142
    /// it is \ref lemon::Path "Path<Digraph>".
142 143
    typedef typename TR::Path Path;
143 144

	
144 145
    /// The \ref HartmannOrlinDefaultTraits "traits class" of the algorithm
145 146
    typedef TR Traits;
146 147

	
147 148
  private:
148 149

	
149 150
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
150 151

	
151 152
    // Data sturcture for path data
152 153
    struct PathData
153 154
    {
154 155
      LargeValue dist;
155 156
      Arc pred;
156 157
      PathData(LargeValue d, Arc p = INVALID) :
157 158
        dist(d), pred(p) {}
158 159
    };
159 160

	
160 161
    typedef typename Digraph::template NodeMap<std::vector<PathData> >
161 162
      PathDataNodeMap;
162 163

	
163 164
  private:
164 165

	
165 166
    // The digraph the algorithm runs on
166 167
    const Digraph &_gr;
167 168
    // The length of the arcs
168 169
    const LengthMap &_length;
169 170

	
170 171
    // Data for storing the strongly connected components
171 172
    int _comp_num;
172 173
    typename Digraph::template NodeMap<int> _comp;
173 174
    std::vector<std::vector<Node> > _comp_nodes;
174 175
    std::vector<Node>* _nodes;
175 176
    typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
176 177

	
177 178
    // Data for the found cycles
178 179
    bool _curr_found, _best_found;
179 180
    LargeValue _curr_length, _best_length;
180 181
    int _curr_size, _best_size;
181 182
    Node _curr_node, _best_node;
182 183
    int _curr_level, _best_level;
183 184

	
184 185
    Path *_cycle_path;
185 186
    bool _local_path;
186 187

	
187 188
    // Node map for storing path data
188 189
    PathDataNodeMap _data;
189 190
    // The processed nodes in the last round
190 191
    std::vector<Node> _process;
191 192

	
192 193
    Tolerance _tolerance;
193 194

	
194 195
    // Infinite constant
195 196
    const LargeValue INF;
196 197

	
197 198
  public:
198 199

	
199 200
    /// \name Named Template Parameters
200 201
    /// @{
201 202

	
202 203
    template <typename T>
203 204
    struct SetLargeValueTraits : public Traits {
204 205
      typedef T LargeValue;
205 206
      typedef lemon::Tolerance<T> Tolerance;
206 207
    };
207 208

	
208 209
    /// \brief \ref named-templ-param "Named parameter" for setting
209 210
    /// \c LargeValue type.
210 211
    ///
211 212
    /// \ref named-templ-param "Named parameter" for setting \c LargeValue
212 213
    /// type. It is used for internal computations in the algorithm.
213 214
    template <typename T>
214 215
    struct SetLargeValue
215 216
      : public HartmannOrlin<GR, LEN, SetLargeValueTraits<T> > {
216 217
      typedef HartmannOrlin<GR, LEN, SetLargeValueTraits<T> > Create;
217 218
    };
218 219

	
219 220
    template <typename T>
220 221
    struct SetPathTraits : public Traits {
221 222
      typedef T Path;
222 223
    };
223 224

	
224 225
    /// \brief \ref named-templ-param "Named parameter" for setting
225 226
    /// \c %Path type.
226 227
    ///
227 228
    /// \ref named-templ-param "Named parameter" for setting the \c %Path
228 229
    /// type of the found cycles.
229 230
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
230 231
    /// and it must have an \c addFront() function.
231 232
    template <typename T>
232 233
    struct SetPath
233 234
      : public HartmannOrlin<GR, LEN, SetPathTraits<T> > {
234 235
      typedef HartmannOrlin<GR, LEN, SetPathTraits<T> > Create;
235 236
    };
236 237

	
237 238
    /// @}
238 239

	
239 240
  public:
240 241

	
241 242
    /// \brief Constructor.
242 243
    ///
243 244
    /// The constructor of the class.
244 245
    ///
245 246
    /// \param digraph The digraph the algorithm runs on.
246 247
    /// \param length The lengths (costs) of the arcs.
247 248
    HartmannOrlin( const Digraph &digraph,
248 249
                   const LengthMap &length ) :
249 250
      _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
250 251
      _best_found(false), _best_length(0), _best_size(1),
251 252
      _cycle_path(NULL), _local_path(false), _data(digraph),
252 253
      INF(std::numeric_limits<LargeValue>::has_infinity ?
253 254
          std::numeric_limits<LargeValue>::infinity() :
254 255
          std::numeric_limits<LargeValue>::max())
255 256
    {}
256 257

	
257 258
    /// Destructor.
258 259
    ~HartmannOrlin() {
259 260
      if (_local_path) delete _cycle_path;
260 261
    }
261 262

	
262 263
    /// \brief Set the path structure for storing the found cycle.
263 264
    ///
264 265
    /// This function sets an external path structure for storing the
265 266
    /// found cycle.
266 267
    ///
267 268
    /// If you don't call this function before calling \ref run() or
268 269
    /// \ref findMinMean(), it will allocate a local \ref Path "path"
269 270
    /// structure. The destuctor deallocates this automatically
270 271
    /// allocated object, of course.
271 272
    ///
272 273
    /// \note The algorithm calls only the \ref lemon::Path::addFront()
273 274
    /// "addFront()" function of the given path structure.
274 275
    ///
275 276
    /// \return <tt>(*this)</tt>
276 277
    HartmannOrlin& cycle(Path &path) {
277 278
      if (_local_path) {
278 279
        delete _cycle_path;
279 280
        _local_path = false;
280 281
      }
281 282
      _cycle_path = &path;
282 283
      return *this;
283 284
    }
284 285

	
285 286
    /// \brief Set the tolerance used by the algorithm.
286 287
    ///
287 288
    /// This function sets the tolerance object used by the algorithm.
288 289
    ///
289 290
    /// \return <tt>(*this)</tt>
290 291
    HartmannOrlin& tolerance(const Tolerance& tolerance) {
291 292
      _tolerance = tolerance;
292 293
      return *this;
293 294
    }
294 295

	
295 296
    /// \brief Return a const reference to the tolerance.
296 297
    ///
297 298
    /// This function returns a const reference to the tolerance object
298 299
    /// used by the algorithm.
299 300
    const Tolerance& tolerance() const {
300 301
      return _tolerance;
301 302
    }
302 303

	
303 304
    /// \name Execution control
304 305
    /// The simplest way to execute the algorithm is to call the \ref run()
305 306
    /// function.\n
306 307
    /// If you only need the minimum mean length, you may call
307 308
    /// \ref findMinMean().
308 309

	
309 310
    /// @{
310 311

	
311 312
    /// \brief Run the algorithm.
312 313
    ///
313 314
    /// This function runs the algorithm.
314 315
    /// It can be called more than once (e.g. if the underlying digraph
315 316
    /// and/or the arc lengths have been modified).
316 317
    ///
317 318
    /// \return \c true if a directed cycle exists in the digraph.
318 319
    ///
319 320
    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
320 321
    /// \code
321 322
    ///   return mmc.findMinMean() && mmc.findCycle();
322 323
    /// \endcode
323 324
    bool run() {
324 325
      return findMinMean() && findCycle();
325 326
    }
326 327

	
327 328
    /// \brief Find the minimum cycle mean.
328 329
    ///
329 330
    /// This function finds the minimum mean length of the directed
330 331
    /// cycles in the digraph.
331 332
    ///
332 333
    /// \return \c true if a directed cycle exists in the digraph.
333 334
    bool findMinMean() {
334 335
      // Initialization and find strongly connected components
335 336
      init();
336 337
      findComponents();
337 338
      
338 339
      // Find the minimum cycle mean in the components
339 340
      for (int comp = 0; comp < _comp_num; ++comp) {
340 341
        if (!initComponent(comp)) continue;
341 342
        processRounds();
342 343
        
343 344
        // Update the best cycle (global minimum mean cycle)
344 345
        if ( _curr_found && (!_best_found || 
345 346
             _curr_length * _best_size < _best_length * _curr_size) ) {
346 347
          _best_found = true;
347 348
          _best_length = _curr_length;
348 349
          _best_size = _curr_size;
349 350
          _best_node = _curr_node;
350 351
          _best_level = _curr_level;
351 352
        }
352 353
      }
353 354
      return _best_found;
354 355
    }
355 356

	
356 357
    /// \brief Find a minimum mean directed cycle.
357 358
    ///
358 359
    /// This function finds a directed cycle of minimum mean length
359 360
    /// in the digraph using the data computed by findMinMean().
360 361
    ///
361 362
    /// \return \c true if a directed cycle exists in the digraph.
362 363
    ///
363 364
    /// \pre \ref findMinMean() must be called before using this function.
364 365
    bool findCycle() {
365 366
      if (!_best_found) return false;
366 367
      IntNodeMap reached(_gr, -1);
367 368
      int r = _best_level + 1;
368 369
      Node u = _best_node;
369 370
      while (reached[u] < 0) {
370 371
        reached[u] = --r;
371 372
        u = _gr.source(_data[u][r].pred);
372 373
      }
373 374
      r = reached[u];
374 375
      Arc e = _data[u][r].pred;
375 376
      _cycle_path->addFront(e);
376 377
      _best_length = _length[e];
377 378
      _best_size = 1;
378 379
      Node v;
379 380
      while ((v = _gr.source(e)) != u) {
380 381
        e = _data[v][--r].pred;
381 382
        _cycle_path->addFront(e);
382 383
        _best_length += _length[e];
383 384
        ++_best_size;
384 385
      }
385 386
      return true;
386 387
    }
387 388

	
388 389
    /// @}
389 390

	
390 391
    /// \name Query Functions
391 392
    /// The results of the algorithm can be obtained using these
392 393
    /// functions.\n
393 394
    /// The algorithm should be executed before using them.
394 395

	
395 396
    /// @{
396 397

	
397 398
    /// \brief Return the total length of the found cycle.
398 399
    ///
399 400
    /// This function returns the total length of the found cycle.
400 401
    ///
401 402
    /// \pre \ref run() or \ref findMinMean() must be called before
402 403
    /// using this function.
403 404
    LargeValue cycleLength() const {
404 405
      return _best_length;
405 406
    }
406 407

	
407 408
    /// \brief Return the number of arcs on the found cycle.
408 409
    ///
409 410
    /// This function returns the number of arcs on the found cycle.
410 411
    ///
411 412
    /// \pre \ref run() or \ref findMinMean() must be called before
412 413
    /// using this function.
413 414
    int cycleArcNum() const {
414 415
      return _best_size;
415 416
    }
416 417

	
417 418
    /// \brief Return the mean length of the found cycle.
418 419
    ///
419 420
    /// This function returns the mean length of the found cycle.
420 421
    ///
421 422
    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
422 423
    /// following code.
423 424
    /// \code
424 425
    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
425 426
    /// \endcode
426 427
    ///
427 428
    /// \pre \ref run() or \ref findMinMean() must be called before
428 429
    /// using this function.
429 430
    double cycleMean() const {
430 431
      return static_cast<double>(_best_length) / _best_size;
431 432
    }
432 433

	
433 434
    /// \brief Return the found cycle.
434 435
    ///
435 436
    /// This function returns a const reference to the path structure
436 437
    /// storing the found cycle.
437 438
    ///
438 439
    /// \pre \ref run() or \ref findCycle() must be called before using
439 440
    /// this function.
440 441
    const Path& cycle() const {
441 442
      return *_cycle_path;
442 443
    }
443 444

	
444 445
    ///@}
445 446

	
446 447
  private:
447 448

	
448 449
    // Initialization
449 450
    void init() {
450 451
      if (!_cycle_path) {
451 452
        _local_path = true;
452 453
        _cycle_path = new Path;
453 454
      }
454 455
      _cycle_path->clear();
455 456
      _best_found = false;
456 457
      _best_length = 0;
457 458
      _best_size = 1;
458 459
      _cycle_path->clear();
459 460
      for (NodeIt u(_gr); u != INVALID; ++u)
460 461
        _data[u].clear();
461 462
    }
462 463

	
463 464
    // Find strongly connected components and initialize _comp_nodes
464 465
    // and _out_arcs
465 466
    void findComponents() {
466 467
      _comp_num = stronglyConnectedComponents(_gr, _comp);
467 468
      _comp_nodes.resize(_comp_num);
468 469
      if (_comp_num == 1) {
469 470
        _comp_nodes[0].clear();
470 471
        for (NodeIt n(_gr); n != INVALID; ++n) {
471 472
          _comp_nodes[0].push_back(n);
472 473
          _out_arcs[n].clear();
473 474
          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
474 475
            _out_arcs[n].push_back(a);
475 476
          }
476 477
        }
477 478
      } else {
478 479
        for (int i = 0; i < _comp_num; ++i)
479 480
          _comp_nodes[i].clear();
480 481
        for (NodeIt n(_gr); n != INVALID; ++n) {
481 482
          int k = _comp[n];
482 483
          _comp_nodes[k].push_back(n);
483 484
          _out_arcs[n].clear();
484 485
          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
Ignore white space 6 line context
1 1
/* -*- C++ -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_HOWARD_H
20 20
#define LEMON_HOWARD_H
21 21

	
22 22
/// \ingroup min_mean_cycle
23 23
///
24 24
/// \file
25 25
/// \brief Howard's algorithm for finding a minimum mean cycle.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <lemon/core.h>
30 30
#include <lemon/path.h>
31 31
#include <lemon/tolerance.h>
32 32
#include <lemon/connectivity.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default traits class of Howard class.
37 37
  ///
38 38
  /// Default traits class of Howard class.
39 39
  /// \tparam GR The type of the digraph.
40 40
  /// \tparam LEN The type of the length map.
41 41
  /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
42 42
#ifdef DOXYGEN
43 43
  template <typename GR, typename LEN>
44 44
#else
45 45
  template <typename GR, typename LEN,
46 46
    bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
47 47
#endif
48 48
  struct HowardDefaultTraits
49 49
  {
50 50
    /// The type of the digraph
51 51
    typedef GR Digraph;
52 52
    /// The type of the length map
53 53
    typedef LEN LengthMap;
54 54
    /// The type of the arc lengths
55 55
    typedef typename LengthMap::Value Value;
56 56

	
57 57
    /// \brief The large value type used for internal computations
58 58
    ///
59 59
    /// The large value type used for internal computations.
60 60
    /// It is \c long \c long if the \c Value type is integer,
61 61
    /// otherwise it is \c double.
62 62
    /// \c Value must be convertible to \c LargeValue.
63 63
    typedef double LargeValue;
64 64

	
65 65
    /// The tolerance type used for internal computations
66 66
    typedef lemon::Tolerance<LargeValue> Tolerance;
67 67

	
68 68
    /// \brief The path type of the found cycles
69 69
    ///
70 70
    /// The path type of the found cycles.
71 71
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
72 72
    /// and it must have an \c addBack() function.
73 73
    typedef lemon::Path<Digraph> Path;
74 74
  };
75 75

	
76 76
  // Default traits class for integer value types
77 77
  template <typename GR, typename LEN>
78 78
  struct HowardDefaultTraits<GR, LEN, true>
79 79
  {
80 80
    typedef GR Digraph;
81 81
    typedef LEN LengthMap;
82 82
    typedef typename LengthMap::Value Value;
83 83
#ifdef LEMON_HAVE_LONG_LONG
84 84
    typedef long long LargeValue;
85 85
#else
86 86
    typedef long LargeValue;
87 87
#endif
88 88
    typedef lemon::Tolerance<LargeValue> Tolerance;
89 89
    typedef lemon::Path<Digraph> Path;
90 90
  };
91 91

	
92 92

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

	
96 96
  /// \brief Implementation of Howard's algorithm for finding a minimum
97 97
  /// mean cycle.
98 98
  ///
99 99
  /// This class implements Howard's policy iteration algorithm for finding
100
  /// a directed cycle of minimum mean length (cost) in a digraph.
100
  /// a directed cycle of minimum mean length (cost) in a digraph
101
  /// \ref amo93networkflows, \ref dasdan98minmeancycle.
101 102
  /// This class provides the most efficient algorithm for the
102 103
  /// minimum mean cycle problem, though the best known theoretical
103 104
  /// bound on its running time is exponential.
104 105
  ///
105 106
  /// \tparam GR The type of the digraph the algorithm runs on.
106 107
  /// \tparam LEN The type of the length map. The default
107 108
  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
108 109
#ifdef DOXYGEN
109 110
  template <typename GR, typename LEN, typename TR>
110 111
#else
111 112
  template < typename GR,
112 113
             typename LEN = typename GR::template ArcMap<int>,
113 114
             typename TR = HowardDefaultTraits<GR, LEN> >
114 115
#endif
115 116
  class Howard
116 117
  {
117 118
  public:
118 119
  
119 120
    /// The type of the digraph
120 121
    typedef typename TR::Digraph Digraph;
121 122
    /// The type of the length map
122 123
    typedef typename TR::LengthMap LengthMap;
123 124
    /// The type of the arc lengths
124 125
    typedef typename TR::Value Value;
125 126

	
126 127
    /// \brief The large value type
127 128
    ///
128 129
    /// The large value type used for internal computations.
129 130
    /// Using the \ref HowardDefaultTraits "default traits class",
130 131
    /// it is \c long \c long if the \c Value type is integer,
131 132
    /// otherwise it is \c double.
132 133
    typedef typename TR::LargeValue LargeValue;
133 134

	
134 135
    /// The tolerance type
135 136
    typedef typename TR::Tolerance Tolerance;
136 137

	
137 138
    /// \brief The path type of the found cycles
138 139
    ///
139 140
    /// The path type of the found cycles.
140 141
    /// Using the \ref HowardDefaultTraits "default traits class",
141 142
    /// it is \ref lemon::Path "Path<Digraph>".
142 143
    typedef typename TR::Path Path;
143 144

	
144 145
    /// The \ref HowardDefaultTraits "traits class" of the algorithm
145 146
    typedef TR Traits;
146 147

	
147 148
  private:
148 149

	
149 150
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
150 151
  
151 152
    // The digraph the algorithm runs on
152 153
    const Digraph &_gr;
153 154
    // The length of the arcs
154 155
    const LengthMap &_length;
155 156

	
156 157
    // Data for the found cycles
157 158
    bool _curr_found, _best_found;
158 159
    LargeValue _curr_length, _best_length;
159 160
    int _curr_size, _best_size;
160 161
    Node _curr_node, _best_node;
161 162

	
162 163
    Path *_cycle_path;
163 164
    bool _local_path;
164 165

	
165 166
    // Internal data used by the algorithm
166 167
    typename Digraph::template NodeMap<Arc> _policy;
167 168
    typename Digraph::template NodeMap<bool> _reached;
168 169
    typename Digraph::template NodeMap<int> _level;
169 170
    typename Digraph::template NodeMap<LargeValue> _dist;
170 171

	
171 172
    // Data for storing the strongly connected components
172 173
    int _comp_num;
173 174
    typename Digraph::template NodeMap<int> _comp;
174 175
    std::vector<std::vector<Node> > _comp_nodes;
175 176
    std::vector<Node>* _nodes;
176 177
    typename Digraph::template NodeMap<std::vector<Arc> > _in_arcs;
177 178
    
178 179
    // Queue used for BFS search
179 180
    std::vector<Node> _queue;
180 181
    int _qfront, _qback;
181 182

	
182 183
    Tolerance _tolerance;
183 184
  
184 185
    // Infinite constant
185 186
    const LargeValue INF;
186 187

	
187 188
  public:
188 189
  
189 190
    /// \name Named Template Parameters
190 191
    /// @{
191 192

	
192 193
    template <typename T>
193 194
    struct SetLargeValueTraits : public Traits {
194 195
      typedef T LargeValue;
195 196
      typedef lemon::Tolerance<T> Tolerance;
196 197
    };
197 198

	
198 199
    /// \brief \ref named-templ-param "Named parameter" for setting
199 200
    /// \c LargeValue type.
200 201
    ///
201 202
    /// \ref named-templ-param "Named parameter" for setting \c LargeValue
202 203
    /// type. It is used for internal computations in the algorithm.
203 204
    template <typename T>
204 205
    struct SetLargeValue
205 206
      : public Howard<GR, LEN, SetLargeValueTraits<T> > {
206 207
      typedef Howard<GR, LEN, SetLargeValueTraits<T> > Create;
207 208
    };
208 209

	
209 210
    template <typename T>
210 211
    struct SetPathTraits : public Traits {
211 212
      typedef T Path;
212 213
    };
213 214

	
214 215
    /// \brief \ref named-templ-param "Named parameter" for setting
215 216
    /// \c %Path type.
216 217
    ///
217 218
    /// \ref named-templ-param "Named parameter" for setting the \c %Path
218 219
    /// type of the found cycles.
219 220
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
220 221
    /// and it must have an \c addBack() function.
221 222
    template <typename T>
222 223
    struct SetPath
223 224
      : public Howard<GR, LEN, SetPathTraits<T> > {
224 225
      typedef Howard<GR, LEN, SetPathTraits<T> > Create;
225 226
    };
226 227
    
227 228
    /// @}
228 229

	
229 230
  public:
230 231

	
231 232
    /// \brief Constructor.
232 233
    ///
233 234
    /// The constructor of the class.
234 235
    ///
235 236
    /// \param digraph The digraph the algorithm runs on.
236 237
    /// \param length The lengths (costs) of the arcs.
237 238
    Howard( const Digraph &digraph,
238 239
            const LengthMap &length ) :
239 240
      _gr(digraph), _length(length), _best_found(false),
240 241
      _best_length(0), _best_size(1), _cycle_path(NULL), _local_path(false),
241 242
      _policy(digraph), _reached(digraph), _level(digraph), _dist(digraph),
242 243
      _comp(digraph), _in_arcs(digraph),
243 244
      INF(std::numeric_limits<LargeValue>::has_infinity ?
244 245
          std::numeric_limits<LargeValue>::infinity() :
245 246
          std::numeric_limits<LargeValue>::max())
246 247
    {}
247 248

	
248 249
    /// Destructor.
249 250
    ~Howard() {
250 251
      if (_local_path) delete _cycle_path;
251 252
    }
252 253

	
253 254
    /// \brief Set the path structure for storing the found cycle.
254 255
    ///
255 256
    /// This function sets an external path structure for storing the
256 257
    /// found cycle.
257 258
    ///
258 259
    /// If you don't call this function before calling \ref run() or
259 260
    /// \ref findMinMean(), it will allocate a local \ref Path "path"
260 261
    /// structure. The destuctor deallocates this automatically
261 262
    /// allocated object, of course.
262 263
    ///
263 264
    /// \note The algorithm calls only the \ref lemon::Path::addBack()
264 265
    /// "addBack()" function of the given path structure.
265 266
    ///
266 267
    /// \return <tt>(*this)</tt>
267 268
    Howard& cycle(Path &path) {
268 269
      if (_local_path) {
269 270
        delete _cycle_path;
270 271
        _local_path = false;
271 272
      }
272 273
      _cycle_path = &path;
273 274
      return *this;
274 275
    }
275 276

	
276 277
    /// \brief Set the tolerance used by the algorithm.
277 278
    ///
278 279
    /// This function sets the tolerance object used by the algorithm.
279 280
    ///
280 281
    /// \return <tt>(*this)</tt>
281 282
    Howard& tolerance(const Tolerance& tolerance) {
282 283
      _tolerance = tolerance;
283 284
      return *this;
284 285
    }
285 286

	
286 287
    /// \brief Return a const reference to the tolerance.
287 288
    ///
288 289
    /// This function returns a const reference to the tolerance object
289 290
    /// used by the algorithm.
290 291
    const Tolerance& tolerance() const {
291 292
      return _tolerance;
292 293
    }
293 294

	
294 295
    /// \name Execution control
295 296
    /// The simplest way to execute the algorithm is to call the \ref run()
296 297
    /// function.\n
297 298
    /// If you only need the minimum mean length, you may call
298 299
    /// \ref findMinMean().
299 300

	
300 301
    /// @{
301 302

	
302 303
    /// \brief Run the algorithm.
303 304
    ///
304 305
    /// This function runs the algorithm.
305 306
    /// It can be called more than once (e.g. if the underlying digraph
306 307
    /// and/or the arc lengths have been modified).
307 308
    ///
308 309
    /// \return \c true if a directed cycle exists in the digraph.
309 310
    ///
310 311
    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
311 312
    /// \code
312 313
    ///   return mmc.findMinMean() && mmc.findCycle();
313 314
    /// \endcode
314 315
    bool run() {
315 316
      return findMinMean() && findCycle();
316 317
    }
317 318

	
318 319
    /// \brief Find the minimum cycle mean.
319 320
    ///
320 321
    /// This function finds the minimum mean length of the directed
321 322
    /// cycles in the digraph.
322 323
    ///
323 324
    /// \return \c true if a directed cycle exists in the digraph.
324 325
    bool findMinMean() {
325 326
      // Initialize and find strongly connected components
326 327
      init();
327 328
      findComponents();
328 329
      
329 330
      // Find the minimum cycle mean in the components
330 331
      for (int comp = 0; comp < _comp_num; ++comp) {
331 332
        // Find the minimum mean cycle in the current component
332 333
        if (!buildPolicyGraph(comp)) continue;
333 334
        while (true) {
334 335
          findPolicyCycle();
335 336
          if (!computeNodeDistances()) break;
336 337
        }
337 338
        // Update the best cycle (global minimum mean cycle)
338 339
        if ( _curr_found && (!_best_found ||
339 340
             _curr_length * _best_size < _best_length * _curr_size) ) {
340 341
          _best_found = true;
341 342
          _best_length = _curr_length;
342 343
          _best_size = _curr_size;
343 344
          _best_node = _curr_node;
344 345
        }
345 346
      }
346 347
      return _best_found;
347 348
    }
348 349

	
349 350
    /// \brief Find a minimum mean directed cycle.
350 351
    ///
351 352
    /// This function finds a directed cycle of minimum mean length
352 353
    /// in the digraph using the data computed by findMinMean().
353 354
    ///
354 355
    /// \return \c true if a directed cycle exists in the digraph.
355 356
    ///
356 357
    /// \pre \ref findMinMean() must be called before using this function.
357 358
    bool findCycle() {
358 359
      if (!_best_found) return false;
359 360
      _cycle_path->addBack(_policy[_best_node]);
360 361
      for ( Node v = _best_node;
361 362
            (v = _gr.target(_policy[v])) != _best_node; ) {
362 363
        _cycle_path->addBack(_policy[v]);
363 364
      }
364 365
      return true;
365 366
    }
366 367

	
367 368
    /// @}
368 369

	
369 370
    /// \name Query Functions
370 371
    /// The results of the algorithm can be obtained using these
371 372
    /// functions.\n
372 373
    /// The algorithm should be executed before using them.
373 374

	
374 375
    /// @{
375 376

	
376 377
    /// \brief Return the total length of the found cycle.
377 378
    ///
378 379
    /// This function returns the total length of the found cycle.
379 380
    ///
380 381
    /// \pre \ref run() or \ref findMinMean() must be called before
381 382
    /// using this function.
382 383
    LargeValue cycleLength() const {
383 384
      return _best_length;
384 385
    }
385 386

	
386 387
    /// \brief Return the number of arcs on the found cycle.
387 388
    ///
388 389
    /// This function returns the number of arcs on the found cycle.
389 390
    ///
390 391
    /// \pre \ref run() or \ref findMinMean() must be called before
391 392
    /// using this function.
392 393
    int cycleArcNum() const {
393 394
      return _best_size;
394 395
    }
395 396

	
396 397
    /// \brief Return the mean length of the found cycle.
397 398
    ///
398 399
    /// This function returns the mean length of the found cycle.
399 400
    ///
400 401
    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
401 402
    /// following code.
402 403
    /// \code
403 404
    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
404 405
    /// \endcode
405 406
    ///
406 407
    /// \pre \ref run() or \ref findMinMean() must be called before
407 408
    /// using this function.
408 409
    double cycleMean() const {
409 410
      return static_cast<double>(_best_length) / _best_size;
410 411
    }
411 412

	
412 413
    /// \brief Return the found cycle.
413 414
    ///
414 415
    /// This function returns a const reference to the path structure
415 416
    /// storing the found cycle.
416 417
    ///
417 418
    /// \pre \ref run() or \ref findCycle() must be called before using
418 419
    /// this function.
419 420
    const Path& cycle() const {
420 421
      return *_cycle_path;
421 422
    }
422 423

	
423 424
    ///@}
424 425

	
425 426
  private:
426 427

	
427 428
    // Initialize
428 429
    void init() {
429 430
      if (!_cycle_path) {
430 431
        _local_path = true;
431 432
        _cycle_path = new Path;
432 433
      }
433 434
      _queue.resize(countNodes(_gr));
434 435
      _best_found = false;
435 436
      _best_length = 0;
436 437
      _best_size = 1;
437 438
      _cycle_path->clear();
438 439
    }
439 440
    
440 441
    // Find strongly connected components and initialize _comp_nodes
441 442
    // and _in_arcs
442 443
    void findComponents() {
443 444
      _comp_num = stronglyConnectedComponents(_gr, _comp);
444 445
      _comp_nodes.resize(_comp_num);
445 446
      if (_comp_num == 1) {
446 447
        _comp_nodes[0].clear();
447 448
        for (NodeIt n(_gr); n != INVALID; ++n) {
448 449
          _comp_nodes[0].push_back(n);
449 450
          _in_arcs[n].clear();
450 451
          for (InArcIt a(_gr, n); a != INVALID; ++a) {
451 452
            _in_arcs[n].push_back(a);
452 453
          }
453 454
        }
454 455
      } else {
455 456
        for (int i = 0; i < _comp_num; ++i)
456 457
          _comp_nodes[i].clear();
457 458
        for (NodeIt n(_gr); n != INVALID; ++n) {
458 459
          int k = _comp[n];
459 460
          _comp_nodes[k].push_back(n);
460 461
          _in_arcs[n].clear();
461 462
          for (InArcIt a(_gr, n); a != INVALID; ++a) {
462 463
            if (_comp[_gr.source(a)] == k) _in_arcs[n].push_back(a);
463 464
          }
464 465
        }
465 466
      }
466 467
    }
467 468

	
468 469
    // Build the policy graph in the given strongly connected component
469 470
    // (the out-degree of every node is 1)
470 471
    bool buildPolicyGraph(int comp) {
471 472
      _nodes = &(_comp_nodes[comp]);
472 473
      if (_nodes->size() < 1 ||
473 474
          (_nodes->size() == 1 && _in_arcs[(*_nodes)[0]].size() == 0)) {
474 475
        return false;
475 476
      }
476 477
      for (int i = 0; i < int(_nodes->size()); ++i) {
477 478
        _dist[(*_nodes)[i]] = INF;
478 479
      }
479 480
      Node u, v;
480 481
      Arc e;
481 482
      for (int i = 0; i < int(_nodes->size()); ++i) {
482 483
        v = (*_nodes)[i];
483 484
        for (int j = 0; j < int(_in_arcs[v].size()); ++j) {
484 485
          e = _in_arcs[v][j];
Ignore white space 768 line context
1 1
/* -*- C++ -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_KARP_H
20 20
#define LEMON_KARP_H
21 21

	
22 22
/// \ingroup min_mean_cycle
23 23
///
24 24
/// \file
25 25
/// \brief Karp's algorithm for finding a minimum mean cycle.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <lemon/core.h>
30 30
#include <lemon/path.h>
31 31
#include <lemon/tolerance.h>
32 32
#include <lemon/connectivity.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \brief Default traits class of Karp algorithm.
37 37
  ///
38 38
  /// Default traits class of Karp algorithm.
39 39
  /// \tparam GR The type of the digraph.
40 40
  /// \tparam LEN The type of the length map.
41 41
  /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
42 42
#ifdef DOXYGEN
43 43
  template <typename GR, typename LEN>
44 44
#else
45 45
  template <typename GR, typename LEN,
46 46
    bool integer = std::numeric_limits<typename LEN::Value>::is_integer>
47 47
#endif
48 48
  struct KarpDefaultTraits
49 49
  {
50 50
    /// The type of the digraph
51 51
    typedef GR Digraph;
52 52
    /// The type of the length map
53 53
    typedef LEN LengthMap;
54 54
    /// The type of the arc lengths
55 55
    typedef typename LengthMap::Value Value;
56 56

	
57 57
    /// \brief The large value type used for internal computations
58 58
    ///
59 59
    /// The large value type used for internal computations.
60 60
    /// It is \c long \c long if the \c Value type is integer,
61 61
    /// otherwise it is \c double.
62 62
    /// \c Value must be convertible to \c LargeValue.
63 63
    typedef double LargeValue;
64 64

	
65 65
    /// The tolerance type used for internal computations
66 66
    typedef lemon::Tolerance<LargeValue> Tolerance;
67 67

	
68 68
    /// \brief The path type of the found cycles
69 69
    ///
70 70
    /// The path type of the found cycles.
71 71
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
72 72
    /// and it must have an \c addBack() function.
73 73
    typedef lemon::Path<Digraph> Path;
74 74
  };
75 75

	
76 76
  // Default traits class for integer value types
77 77
  template <typename GR, typename LEN>
78 78
  struct KarpDefaultTraits<GR, LEN, true>
79 79
  {
80 80
    typedef GR Digraph;
81 81
    typedef LEN LengthMap;
82 82
    typedef typename LengthMap::Value Value;
83 83
#ifdef LEMON_HAVE_LONG_LONG
84 84
    typedef long long LargeValue;
85 85
#else
86 86
    typedef long LargeValue;
87 87
#endif
88 88
    typedef lemon::Tolerance<LargeValue> Tolerance;
89 89
    typedef lemon::Path<Digraph> Path;
90 90
  };
91 91

	
92 92

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

	
96 96
  /// \brief Implementation of Karp's algorithm for finding a minimum
97 97
  /// mean cycle.
98 98
  ///
99 99
  /// This class implements Karp's algorithm for finding a directed
100
  /// cycle of minimum mean length (cost) in a digraph.
100
  /// cycle of minimum mean length (cost) in a digraph
101
  /// \ref amo93networkflows, \ref dasdan98minmeancycle.
101 102
  /// It runs in time O(ne) and uses space O(n<sup>2</sup>+e).
102 103
  ///
103 104
  /// \tparam GR The type of the digraph the algorithm runs on.
104 105
  /// \tparam LEN The type of the length map. The default
105 106
  /// map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
106 107
#ifdef DOXYGEN
107 108
  template <typename GR, typename LEN, typename TR>
108 109
#else
109 110
  template < typename GR,
110 111
             typename LEN = typename GR::template ArcMap<int>,
111 112
             typename TR = KarpDefaultTraits<GR, LEN> >
112 113
#endif
113 114
  class Karp
114 115
  {
115 116
  public:
116 117

	
117 118
    /// The type of the digraph
118 119
    typedef typename TR::Digraph Digraph;
119 120
    /// The type of the length map
120 121
    typedef typename TR::LengthMap LengthMap;
121 122
    /// The type of the arc lengths
122 123
    typedef typename TR::Value Value;
123 124

	
124 125
    /// \brief The large value type
125 126
    ///
126 127
    /// The large value type used for internal computations.
127 128
    /// Using the \ref KarpDefaultTraits "default traits class",
128 129
    /// it is \c long \c long if the \c Value type is integer,
129 130
    /// otherwise it is \c double.
130 131
    typedef typename TR::LargeValue LargeValue;
131 132

	
132 133
    /// The tolerance type
133 134
    typedef typename TR::Tolerance Tolerance;
134 135

	
135 136
    /// \brief The path type of the found cycles
136 137
    ///
137 138
    /// The path type of the found cycles.
138 139
    /// Using the \ref KarpDefaultTraits "default traits class",
139 140
    /// it is \ref lemon::Path "Path<Digraph>".
140 141
    typedef typename TR::Path Path;
141 142

	
142 143
    /// The \ref KarpDefaultTraits "traits class" of the algorithm
143 144
    typedef TR Traits;
144 145

	
145 146
  private:
146 147

	
147 148
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
148 149

	
149 150
    // Data sturcture for path data
150 151
    struct PathData
151 152
    {
152 153
      LargeValue dist;
153 154
      Arc pred;
154 155
      PathData(LargeValue d, Arc p = INVALID) :
155 156
        dist(d), pred(p) {}
156 157
    };
157 158

	
158 159
    typedef typename Digraph::template NodeMap<std::vector<PathData> >
159 160
      PathDataNodeMap;
160 161

	
161 162
  private:
162 163

	
163 164
    // The digraph the algorithm runs on
164 165
    const Digraph &_gr;
165 166
    // The length of the arcs
166 167
    const LengthMap &_length;
167 168

	
168 169
    // Data for storing the strongly connected components
169 170
    int _comp_num;
170 171
    typename Digraph::template NodeMap<int> _comp;
171 172
    std::vector<std::vector<Node> > _comp_nodes;
172 173
    std::vector<Node>* _nodes;
173 174
    typename Digraph::template NodeMap<std::vector<Arc> > _out_arcs;
174 175

	
175 176
    // Data for the found cycle
176 177
    LargeValue _cycle_length;
177 178
    int _cycle_size;
178 179
    Node _cycle_node;
179 180

	
180 181
    Path *_cycle_path;
181 182
    bool _local_path;
182 183

	
183 184
    // Node map for storing path data
184 185
    PathDataNodeMap _data;
185 186
    // The processed nodes in the last round
186 187
    std::vector<Node> _process;
187 188

	
188 189
    Tolerance _tolerance;
189 190
    
190 191
    // Infinite constant
191 192
    const LargeValue INF;
192 193

	
193 194
  public:
194 195

	
195 196
    /// \name Named Template Parameters
196 197
    /// @{
197 198

	
198 199
    template <typename T>
199 200
    struct SetLargeValueTraits : public Traits {
200 201
      typedef T LargeValue;
201 202
      typedef lemon::Tolerance<T> Tolerance;
202 203
    };
203 204

	
204 205
    /// \brief \ref named-templ-param "Named parameter" for setting
205 206
    /// \c LargeValue type.
206 207
    ///
207 208
    /// \ref named-templ-param "Named parameter" for setting \c LargeValue
208 209
    /// type. It is used for internal computations in the algorithm.
209 210
    template <typename T>
210 211
    struct SetLargeValue
211 212
      : public Karp<GR, LEN, SetLargeValueTraits<T> > {
212 213
      typedef Karp<GR, LEN, SetLargeValueTraits<T> > Create;
213 214
    };
214 215

	
215 216
    template <typename T>
216 217
    struct SetPathTraits : public Traits {
217 218
      typedef T Path;
218 219
    };
219 220

	
220 221
    /// \brief \ref named-templ-param "Named parameter" for setting
221 222
    /// \c %Path type.
222 223
    ///
223 224
    /// \ref named-templ-param "Named parameter" for setting the \c %Path
224 225
    /// type of the found cycles.
225 226
    /// It must conform to the \ref lemon::concepts::Path "Path" concept
226 227
    /// and it must have an \c addFront() function.
227 228
    template <typename T>
228 229
    struct SetPath
229 230
      : public Karp<GR, LEN, SetPathTraits<T> > {
230 231
      typedef Karp<GR, LEN, SetPathTraits<T> > Create;
231 232
    };
232 233

	
233 234
    /// @}
234 235

	
235 236
  public:
236 237

	
237 238
    /// \brief Constructor.
238 239
    ///
239 240
    /// The constructor of the class.
240 241
    ///
241 242
    /// \param digraph The digraph the algorithm runs on.
242 243
    /// \param length The lengths (costs) of the arcs.
243 244
    Karp( const Digraph &digraph,
244 245
          const LengthMap &length ) :
245 246
      _gr(digraph), _length(length), _comp(digraph), _out_arcs(digraph),
246 247
      _cycle_length(0), _cycle_size(1), _cycle_node(INVALID),
247 248
      _cycle_path(NULL), _local_path(false), _data(digraph),
248 249
      INF(std::numeric_limits<LargeValue>::has_infinity ?
249 250
          std::numeric_limits<LargeValue>::infinity() :
250 251
          std::numeric_limits<LargeValue>::max())
251 252
    {}
252 253

	
253 254
    /// Destructor.
254 255
    ~Karp() {
255 256
      if (_local_path) delete _cycle_path;
256 257
    }
257 258

	
258 259
    /// \brief Set the path structure for storing the found cycle.
259 260
    ///
260 261
    /// This function sets an external path structure for storing the
261 262
    /// found cycle.
262 263
    ///
263 264
    /// If you don't call this function before calling \ref run() or
264 265
    /// \ref findMinMean(), it will allocate a local \ref Path "path"
265 266
    /// structure. The destuctor deallocates this automatically
266 267
    /// allocated object, of course.
267 268
    ///
268 269
    /// \note The algorithm calls only the \ref lemon::Path::addFront()
269 270
    /// "addFront()" function of the given path structure.
270 271
    ///
271 272
    /// \return <tt>(*this)</tt>
272 273
    Karp& cycle(Path &path) {
273 274
      if (_local_path) {
274 275
        delete _cycle_path;
275 276
        _local_path = false;
276 277
      }
277 278
      _cycle_path = &path;
278 279
      return *this;
279 280
    }
280 281

	
281 282
    /// \brief Set the tolerance used by the algorithm.
282 283
    ///
283 284
    /// This function sets the tolerance object used by the algorithm.
284 285
    ///
285 286
    /// \return <tt>(*this)</tt>
286 287
    Karp& tolerance(const Tolerance& tolerance) {
287 288
      _tolerance = tolerance;
288 289
      return *this;
289 290
    }
290 291

	
291 292
    /// \brief Return a const reference to the tolerance.
292 293
    ///
293 294
    /// This function returns a const reference to the tolerance object
294 295
    /// used by the algorithm.
295 296
    const Tolerance& tolerance() const {
296 297
      return _tolerance;
297 298
    }
298 299

	
299 300
    /// \name Execution control
300 301
    /// The simplest way to execute the algorithm is to call the \ref run()
301 302
    /// function.\n
302 303
    /// If you only need the minimum mean length, you may call
303 304
    /// \ref findMinMean().
304 305

	
305 306
    /// @{
306 307

	
307 308
    /// \brief Run the algorithm.
308 309
    ///
309 310
    /// This function runs the algorithm.
310 311
    /// It can be called more than once (e.g. if the underlying digraph
311 312
    /// and/or the arc lengths have been modified).
312 313
    ///
313 314
    /// \return \c true if a directed cycle exists in the digraph.
314 315
    ///
315 316
    /// \note <tt>mmc.run()</tt> is just a shortcut of the following code.
316 317
    /// \code
317 318
    ///   return mmc.findMinMean() && mmc.findCycle();
318 319
    /// \endcode
319 320
    bool run() {
320 321
      return findMinMean() && findCycle();
321 322
    }
322 323

	
323 324
    /// \brief Find the minimum cycle mean.
324 325
    ///
325 326
    /// This function finds the minimum mean length of the directed
326 327
    /// cycles in the digraph.
327 328
    ///
328 329
    /// \return \c true if a directed cycle exists in the digraph.
329 330
    bool findMinMean() {
330 331
      // Initialization and find strongly connected components
331 332
      init();
332 333
      findComponents();
333 334
      
334 335
      // Find the minimum cycle mean in the components
335 336
      for (int comp = 0; comp < _comp_num; ++comp) {
336 337
        if (!initComponent(comp)) continue;
337 338
        processRounds();
338 339
        updateMinMean();
339 340
      }
340 341
      return (_cycle_node != INVALID);
341 342
    }
342 343

	
343 344
    /// \brief Find a minimum mean directed cycle.
344 345
    ///
345 346
    /// This function finds a directed cycle of minimum mean length
346 347
    /// in the digraph using the data computed by findMinMean().
347 348
    ///
348 349
    /// \return \c true if a directed cycle exists in the digraph.
349 350
    ///
350 351
    /// \pre \ref findMinMean() must be called before using this function.
351 352
    bool findCycle() {
352 353
      if (_cycle_node == INVALID) return false;
353 354
      IntNodeMap reached(_gr, -1);
354 355
      int r = _data[_cycle_node].size();
355 356
      Node u = _cycle_node;
356 357
      while (reached[u] < 0) {
357 358
        reached[u] = --r;
358 359
        u = _gr.source(_data[u][r].pred);
359 360
      }
360 361
      r = reached[u];
361 362
      Arc e = _data[u][r].pred;
362 363
      _cycle_path->addFront(e);
363 364
      _cycle_length = _length[e];
364 365
      _cycle_size = 1;
365 366
      Node v;
366 367
      while ((v = _gr.source(e)) != u) {
367 368
        e = _data[v][--r].pred;
368 369
        _cycle_path->addFront(e);
369 370
        _cycle_length += _length[e];
370 371
        ++_cycle_size;
371 372
      }
372 373
      return true;
373 374
    }
374 375

	
375 376
    /// @}
376 377

	
377 378
    /// \name Query Functions
378 379
    /// The results of the algorithm can be obtained using these
379 380
    /// functions.\n
380 381
    /// The algorithm should be executed before using them.
381 382

	
382 383
    /// @{
383 384

	
384 385
    /// \brief Return the total length of the found cycle.
385 386
    ///
386 387
    /// This function returns the total length of the found cycle.
387 388
    ///
388 389
    /// \pre \ref run() or \ref findMinMean() must be called before
389 390
    /// using this function.
390 391
    LargeValue cycleLength() const {
391 392
      return _cycle_length;
392 393
    }
393 394

	
394 395
    /// \brief Return the number of arcs on the found cycle.
395 396
    ///
396 397
    /// This function returns the number of arcs on the found cycle.
397 398
    ///
398 399
    /// \pre \ref run() or \ref findMinMean() must be called before
399 400
    /// using this function.
400 401
    int cycleArcNum() const {
401 402
      return _cycle_size;
402 403
    }
403 404

	
404 405
    /// \brief Return the mean length of the found cycle.
405 406
    ///
406 407
    /// This function returns the mean length of the found cycle.
407 408
    ///
408 409
    /// \note <tt>alg.cycleMean()</tt> is just a shortcut of the
409 410
    /// following code.
410 411
    /// \code
411 412
    ///   return static_cast<double>(alg.cycleLength()) / alg.cycleArcNum();
412 413
    /// \endcode
413 414
    ///
414 415
    /// \pre \ref run() or \ref findMinMean() must be called before
415 416
    /// using this function.
416 417
    double cycleMean() const {
417 418
      return static_cast<double>(_cycle_length) / _cycle_size;
418 419
    }
419 420

	
420 421
    /// \brief Return the found cycle.
421 422
    ///
422 423
    /// This function returns a const reference to the path structure
423 424
    /// storing the found cycle.
424 425
    ///
425 426
    /// \pre \ref run() or \ref findCycle() must be called before using
426 427
    /// this function.
427 428
    const Path& cycle() const {
428 429
      return *_cycle_path;
429 430
    }
430 431

	
431 432
    ///@}
432 433

	
433 434
  private:
434 435

	
435 436
    // Initialization
436 437
    void init() {
437 438
      if (!_cycle_path) {
438 439
        _local_path = true;
439 440
        _cycle_path = new Path;
440 441
      }
441 442
      _cycle_path->clear();
442 443
      _cycle_length = 0;
443 444
      _cycle_size = 1;
444 445
      _cycle_node = INVALID;
445 446
      for (NodeIt u(_gr); u != INVALID; ++u)
446 447
        _data[u].clear();
447 448
    }
448 449

	
449 450
    // Find strongly connected components and initialize _comp_nodes
450 451
    // and _out_arcs
451 452
    void findComponents() {
452 453
      _comp_num = stronglyConnectedComponents(_gr, _comp);
453 454
      _comp_nodes.resize(_comp_num);
454 455
      if (_comp_num == 1) {
455 456
        _comp_nodes[0].clear();
456 457
        for (NodeIt n(_gr); n != INVALID; ++n) {
457 458
          _comp_nodes[0].push_back(n);
458 459
          _out_arcs[n].clear();
459 460
          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
460 461
            _out_arcs[n].push_back(a);
461 462
          }
462 463
        }
463 464
      } else {
464 465
        for (int i = 0; i < _comp_num; ++i)
465 466
          _comp_nodes[i].clear();
466 467
        for (NodeIt n(_gr); n != INVALID; ++n) {
467 468
          int k = _comp[n];
468 469
          _comp_nodes[k].push_back(n);
469 470
          _out_arcs[n].clear();
470 471
          for (OutArcIt a(_gr, n); a != INVALID; ++a) {
471 472
            if (_comp[_gr.target(a)] == k) _out_arcs[n].push_back(a);
472 473
          }
473 474
        }
474 475
      }
475 476
    }
476 477

	
477 478
    // Initialize path data for the current component
478 479
    bool initComponent(int comp) {
479 480
      _nodes = &(_comp_nodes[comp]);
480 481
      int n = _nodes->size();
481 482
      if (n < 1 || (n == 1 && _out_arcs[(*_nodes)[0]].size() == 0)) {
482 483
        return false;
483 484
      }      
484 485
      for (int i = 0; i < n; ++i) {
0 comments (0 inline)