↑ 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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
///\ingroup demos
20 20
///\file
21 21
///\brief Argument parser demo
22 22
///
23 23
/// This example shows how the argument parser can be used.
24 24
///
25 25
/// \include arg_parser_demo.cc
26 26

	
27 27
#include <lemon/arg_parser.h>
28 28

	
29 29
using namespace lemon;
30 30
int main(int argc, char **argv)
31 31
{
32 32
  // Initialize the argument parser
33 33
  ArgParser ap(argc, argv);
34 34
  int i;
35 35
  std::string s;
36 36
  double d = 1.0;
37 37
  bool b, nh;
38 38
  bool g1, g2, g3;
39 39

	
40 40
  // Add a mandatory integer option with storage reference
41 41
  ap.refOption("n", "An integer input.", i, true);
42 42
  // Add a double option with storage reference (the default value is 1.0)
43 43
  ap.refOption("val", "A double input.", d);
44 44
  // Add a double option without storage reference (the default value is 3.14)
45 45
  ap.doubleOption("val2", "A double input.", 3.14);
46 46
  // Set synonym for -val option
47 47
  ap.synonym("vals", "val");
48 48
  // Add a string option
49 49
  ap.refOption("name", "A string input.", s);
50 50
  // Add bool options
51 51
  ap.refOption("f", "A switch.", b)
52 52
    .refOption("nohelp", "", nh)
53 53
    .refOption("gra", "Choice A", g1)
54 54
    .refOption("grb", "Choice B", g2)
55 55
    .refOption("grc", "Choice C", g3);
56 56
  // Bundle -gr* options into a group
57 57
  ap.optionGroup("gr", "gra")
58 58
    .optionGroup("gr", "grb")
59 59
    .optionGroup("gr", "grc");
60 60
  // Set the group mandatory
61 61
  ap.mandatoryGroup("gr");
62 62
  // Set the options of the group exclusive (only one option can be given)
63 63
  ap.onlyOneGroup("gr");
64 64
  // Add non-parsed arguments (e.g. input files)
65 65
  ap.other("infile", "The input file.")
66 66
    .other("...");
67 67

	
68 68
  // Throw an exception when problems occurs. The default behavior is to
69 69
  // exit(1) on these cases, but this makes Valgrind falsely warn
70 70
  // about memory leaks.
71 71
  ap.throwOnProblems();
72
  
72

	
73 73
  // Perform the parsing process
74 74
  // (in case of any error it terminates the program)
75 75
  // The try {} construct is necessary only if the ap.trowOnProblems()
76 76
  // setting is in use.
77 77
  try {
78 78
    ap.parse();
79 79
  } catch (ArgParserException &) { return 1; }
80 80

	
81 81
  // Check each option if it has been given and print its value
82 82
  std::cout << "Parameters of '" << ap.commandName() << "':\n";
83 83

	
84 84
  std::cout << "  Value of -n: " << i << std::endl;
85 85
  if(ap.given("val")) std::cout << "  Value of -val: " << d << std::endl;
86 86
  if(ap.given("val2")) {
87 87
    d = ap["val2"];
88 88
    std::cout << "  Value of -val2: " << d << std::endl;
89 89
  }
90 90
  if(ap.given("name")) std::cout << "  Value of -name: " << s << std::endl;
91 91
  if(ap.given("f")) std::cout << "  -f is given\n";
92 92
  if(ap.given("nohelp")) std::cout << "  Value of -nohelp: " << nh << std::endl;
93 93
  if(ap.given("gra")) std::cout << "  -gra is given\n";
94 94
  if(ap.given("grb")) std::cout << "  -grb is given\n";
95 95
  if(ap.given("grc")) std::cout << "  -grc is given\n";
96 96

	
97 97
  switch(ap.files().size()) {
98 98
  case 0:
99 99
    std::cout << "  No file argument was given.\n";
100 100
    break;
101 101
  case 1:
102 102
    std::cout << "  1 file argument was given. It is:\n";
103 103
    break;
104 104
  default:
105 105
    std::cout << "  "
106 106
              << ap.files().size() << " file arguments were given. They are:\n";
107 107
  }
108 108
  for(unsigned int i=0;i<ap.files().size();++i)
109 109
    std::cout << "    '" << ap.files()[i] << "'\n";
110 110

	
111 111
  return 0;
112 112
}
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
namespace lemon {
20 20

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

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

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

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

	
45 45
Alteration of standard containers need a very limited number of
46 46
operations, these together satisfy the everyday requirements.
47 47
In the case of graph structures, different operations are needed which do
48 48
not alter the physical graph, but gives another view. If some nodes or
49 49
arcs have to be hidden or the reverse oriented graph have to be used, then
50 50
this is the case. It also may happen that in a flow implementation
51 51
the residual graph can be accessed by another algorithm, or a node-set
52 52
is to be shrunk for another algorithm.
53 53
LEMON also provides a variety of graphs for these requirements called
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
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
\mainpage LEMON Documentation
21 21

	
22 22
\section intro Introduction
23 23

	
24 24
<b>LEMON</b> stands for <i><b>L</b>ibrary for <b>E</b>fficient <b>M</b>odeling
25 25
and <b>O</b>ptimization in <b>N</b>etworks</i>.
26 26
It is a C++ template library providing efficient implementations of common
27 27
data structures and algorithms with focus on combinatorial optimization
28
tasks connected mainly with graphs and networks. 
28
tasks connected mainly with graphs and networks.
29 29

	
30 30
<b>
31 31
LEMON is an <a class="el" href="http://opensource.org/">open&nbsp;source</a>
32 32
project.
33 33
You are free to use it in your commercial or
34 34
non-commercial applications under very permissive
35 35
\ref license "license terms".
36 36
</b>
37 37

	
38
The project is maintained by the 
38
The project is maintained by the
39 39
<a href="http://www.cs.elte.hu/egres/">Egerv&aacute;ry Research Group on
40 40
Combinatorial Optimization</a> \ref egres
41 41
at the Operations Research Department of the
42 42
<a href="http://www.elte.hu/en/">E&ouml;tv&ouml;s Lor&aacute;nd University</a>,
43 43
Budapest, Hungary.
44 44
LEMON is also a member of the <a href="http://www.coin-or.org/">COIN-OR</a>
45 45
initiative \ref coinor.
46 46

	
47 47
\section howtoread How to Read the Documentation
48 48

	
49 49
If you would like to get to know the library, see
50 50
<a class="el" href="http://lemon.cs.elte.hu/pub/tutorial/">LEMON Tutorial</a>.
51 51

	
52 52
If you are interested in starting to use the library, see the <a class="el"
53 53
href="http://lemon.cs.elte.hu/trac/lemon/wiki/InstallGuide/">Installation
54 54
Guide</a>.
55 55

	
56 56
If you know what you are looking for, then try to find it under the
57 57
<a class="el" href="modules.html">Modules</a> section.
58 58

	
59 59
If you are a user of the old (0.x) series of LEMON, please check out the
60 60
\ref migration "Migration Guide" for the backward incompatibilities.
61 61
*/
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
namespace lemon {
20 20

	
21 21
/**
22 22
\page min_cost_flow Minimum Cost Flow Problem
23 23

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

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

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

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

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

	
59 59

	
60 60
\section mcf_algs Algorithms
61 61

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

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

	
67 67

	
68 68
\section mcf_dual Dual Solution
69 69

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

	
76 76
 - For all \f$uv\in A\f$ arcs:
77 77
   - if \f$cost^\pi(uv)>0\f$, then \f$f(uv)=lower(uv)\f$;
78 78
   - if \f$lower(uv)<f(uv)<upper(uv)\f$, then \f$cost^\pi(uv)=0\f$;
79 79
   - if \f$cost^\pi(uv)<0\f$, then \f$f(uv)=upper(uv)\f$.
80 80
 - For all \f$u\in V\f$ nodes:
81 81
   - \f$\pi(u)\leq 0\f$;
82 82
   - if \f$\sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \neq sup(u)\f$,
83 83
     then \f$\pi(u)=0\f$.
84
 
84

	
85 85
Here \f$cost^\pi(uv)\f$ denotes the \e reduced \e cost of the arc
86 86
\f$uv\in A\f$ with respect to the potential function \f$\pi\f$, i.e.
87 87
\f[ cost^\pi(uv) = cost(uv) + \pi(u) - \pi(v).\f]
88 88

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

	
92 92

	
93 93
\section mcf_eq Equality Form
94 94

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

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

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

	
110 110

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

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

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

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

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

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

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

	
152 152
*/
153 153
}
Ignore white space 6 line context
1 1
/* -*- 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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
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_ADAPTORS_H
20 20
#define LEMON_ADAPTORS_H
21 21

	
22 22
/// \ingroup graph_adaptors
23 23
/// \file
24 24
/// \brief Adaptor classes for digraphs and graphs
25 25
///
26 26
/// This file contains several useful adaptors for digraphs and graphs.
27 27

	
28 28
#include <lemon/core.h>
29 29
#include <lemon/maps.h>
30 30
#include <lemon/bits/variant.h>
31 31

	
32 32
#include <lemon/bits/graph_adaptor_extender.h>
33 33
#include <lemon/bits/map_extender.h>
34 34
#include <lemon/tolerance.h>
35 35

	
36 36
#include <algorithm>
37 37

	
38 38
namespace lemon {
39 39

	
40 40
#ifdef _MSC_VER
41 41
#define LEMON_SCOPE_FIX(OUTER, NESTED) OUTER::NESTED
42 42
#else
43 43
#define LEMON_SCOPE_FIX(OUTER, NESTED) typename OUTER::template NESTED
44 44
#endif
45 45

	
46 46
  template<typename DGR>
47 47
  class DigraphAdaptorBase {
48 48
  public:
49 49
    typedef DGR Digraph;
50 50
    typedef DigraphAdaptorBase Adaptor;
51 51

	
52 52
  protected:
53 53
    DGR* _digraph;
... ...
@@ -376,354 +376,354 @@
376 376
  class ReverseDigraph :
377 377
    public DigraphAdaptorExtender<ReverseDigraphBase<DGR> > {
378 378
#endif
379 379
    typedef DigraphAdaptorExtender<ReverseDigraphBase<DGR> > Parent;
380 380
  public:
381 381
    /// The type of the adapted digraph.
382 382
    typedef DGR Digraph;
383 383
  protected:
384 384
    ReverseDigraph() { }
385 385
  public:
386 386

	
387 387
    /// \brief Constructor
388 388
    ///
389 389
    /// Creates a reverse digraph adaptor for the given digraph.
390 390
    explicit ReverseDigraph(DGR& digraph) {
391 391
      Parent::initialize(digraph);
392 392
    }
393 393
  };
394 394

	
395 395
  /// \brief Returns a read-only ReverseDigraph adaptor
396 396
  ///
397 397
  /// This function just returns a read-only \ref ReverseDigraph adaptor.
398 398
  /// \ingroup graph_adaptors
399 399
  /// \relates ReverseDigraph
400 400
  template<typename DGR>
401 401
  ReverseDigraph<const DGR> reverseDigraph(const DGR& digraph) {
402 402
    return ReverseDigraph<const DGR>(digraph);
403 403
  }
404 404

	
405 405

	
406 406
  template <typename DGR, typename NF, typename AF, bool ch = true>
407 407
  class SubDigraphBase : public DigraphAdaptorBase<DGR> {
408 408
    typedef DigraphAdaptorBase<DGR> Parent;
409 409
  public:
410 410
    typedef DGR Digraph;
411 411
    typedef NF NodeFilterMap;
412 412
    typedef AF ArcFilterMap;
413 413

	
414 414
    typedef SubDigraphBase Adaptor;
415 415
  protected:
416 416
    NF* _node_filter;
417 417
    AF* _arc_filter;
418 418
    SubDigraphBase()
419 419
      : Parent(), _node_filter(0), _arc_filter(0) { }
420 420

	
421 421
    void initialize(DGR& digraph, NF& node_filter, AF& arc_filter) {
422 422
      Parent::initialize(digraph);
423 423
      _node_filter = &node_filter;
424
      _arc_filter = &arc_filter;      
424
      _arc_filter = &arc_filter;
425 425
    }
426 426

	
427 427
  public:
428 428

	
429 429
    typedef typename Parent::Node Node;
430 430
    typedef typename Parent::Arc Arc;
431 431

	
432 432
    void first(Node& i) const {
433 433
      Parent::first(i);
434 434
      while (i != INVALID && !(*_node_filter)[i]) Parent::next(i);
435 435
    }
436 436

	
437 437
    void first(Arc& i) const {
438 438
      Parent::first(i);
439 439
      while (i != INVALID && (!(*_arc_filter)[i]
440 440
                              || !(*_node_filter)[Parent::source(i)]
441 441
                              || !(*_node_filter)[Parent::target(i)]))
442 442
        Parent::next(i);
443 443
    }
444 444

	
445 445
    void firstIn(Arc& i, const Node& n) const {
446 446
      Parent::firstIn(i, n);
447 447
      while (i != INVALID && (!(*_arc_filter)[i]
448 448
                              || !(*_node_filter)[Parent::source(i)]))
449 449
        Parent::nextIn(i);
450 450
    }
451 451

	
452 452
    void firstOut(Arc& i, const Node& n) const {
453 453
      Parent::firstOut(i, n);
454 454
      while (i != INVALID && (!(*_arc_filter)[i]
455 455
                              || !(*_node_filter)[Parent::target(i)]))
456 456
        Parent::nextOut(i);
457 457
    }
458 458

	
459 459
    void next(Node& i) const {
460 460
      Parent::next(i);
461 461
      while (i != INVALID && !(*_node_filter)[i]) Parent::next(i);
462 462
    }
463 463

	
464 464
    void next(Arc& i) const {
465 465
      Parent::next(i);
466 466
      while (i != INVALID && (!(*_arc_filter)[i]
467 467
                              || !(*_node_filter)[Parent::source(i)]
468 468
                              || !(*_node_filter)[Parent::target(i)]))
469 469
        Parent::next(i);
470 470
    }
471 471

	
472 472
    void nextIn(Arc& i) const {
473 473
      Parent::nextIn(i);
474 474
      while (i != INVALID && (!(*_arc_filter)[i]
475 475
                              || !(*_node_filter)[Parent::source(i)]))
476 476
        Parent::nextIn(i);
477 477
    }
478 478

	
479 479
    void nextOut(Arc& i) const {
480 480
      Parent::nextOut(i);
481 481
      while (i != INVALID && (!(*_arc_filter)[i]
482 482
                              || !(*_node_filter)[Parent::target(i)]))
483 483
        Parent::nextOut(i);
484 484
    }
485 485

	
486 486
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
487 487
    void status(const Arc& a, bool v) const { _arc_filter->set(a, v); }
488 488

	
489 489
    bool status(const Node& n) const { return (*_node_filter)[n]; }
490 490
    bool status(const Arc& a) const { return (*_arc_filter)[a]; }
491 491

	
492 492
    typedef False NodeNumTag;
493 493
    typedef False ArcNumTag;
494 494

	
495 495
    typedef FindArcTagIndicator<DGR> FindArcTag;
496 496
    Arc findArc(const Node& source, const Node& target,
497 497
                const Arc& prev = INVALID) const {
498 498
      if (!(*_node_filter)[source] || !(*_node_filter)[target]) {
499 499
        return INVALID;
500 500
      }
501 501
      Arc arc = Parent::findArc(source, target, prev);
502 502
      while (arc != INVALID && !(*_arc_filter)[arc]) {
503 503
        arc = Parent::findArc(source, target, arc);
504 504
      }
505 505
      return arc;
506 506
    }
507 507

	
508 508
  public:
509 509

	
510 510
    template <typename V>
511
    class NodeMap 
512
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>, 
513
	      LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> {
511
    class NodeMap
512
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>,
513
              LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> {
514 514
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>,
515
	LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> Parent;
515
        LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> Parent;
516 516

	
517 517
    public:
518 518
      typedef V Value;
519 519

	
520 520
      NodeMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor)
521 521
        : Parent(adaptor) {}
522 522
      NodeMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor, const V& value)
523 523
        : Parent(adaptor, value) {}
524 524

	
525 525
    private:
526 526
      NodeMap& operator=(const NodeMap& cmap) {
527 527
        return operator=<NodeMap>(cmap);
528 528
      }
529 529

	
530 530
      template <typename CMap>
531 531
      NodeMap& operator=(const CMap& cmap) {
532 532
        Parent::operator=(cmap);
533 533
        return *this;
534 534
      }
535 535
    };
536 536

	
537 537
    template <typename V>
538
    class ArcMap 
538
    class ArcMap
539 539
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>,
540
	      LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> {
540
              LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> {
541 541
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, ch>,
542 542
        LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> Parent;
543 543

	
544 544
    public:
545 545
      typedef V Value;
546 546

	
547 547
      ArcMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor)
548 548
        : Parent(adaptor) {}
549 549
      ArcMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor, const V& value)
550 550
        : Parent(adaptor, value) {}
551 551

	
552 552
    private:
553 553
      ArcMap& operator=(const ArcMap& cmap) {
554 554
        return operator=<ArcMap>(cmap);
555 555
      }
556 556

	
557 557
      template <typename CMap>
558 558
      ArcMap& operator=(const CMap& cmap) {
559 559
        Parent::operator=(cmap);
560 560
        return *this;
561 561
      }
562 562
    };
563 563

	
564 564
  };
565 565

	
566 566
  template <typename DGR, typename NF, typename AF>
567 567
  class SubDigraphBase<DGR, NF, AF, false>
568 568
    : public DigraphAdaptorBase<DGR> {
569 569
    typedef DigraphAdaptorBase<DGR> Parent;
570 570
  public:
571 571
    typedef DGR Digraph;
572 572
    typedef NF NodeFilterMap;
573 573
    typedef AF ArcFilterMap;
574 574

	
575 575
    typedef SubDigraphBase Adaptor;
576 576
  protected:
577 577
    NF* _node_filter;
578 578
    AF* _arc_filter;
579 579
    SubDigraphBase()
580 580
      : Parent(), _node_filter(0), _arc_filter(0) { }
581 581

	
582 582
    void initialize(DGR& digraph, NF& node_filter, AF& arc_filter) {
583 583
      Parent::initialize(digraph);
584 584
      _node_filter = &node_filter;
585
      _arc_filter = &arc_filter;      
585
      _arc_filter = &arc_filter;
586 586
    }
587 587

	
588 588
  public:
589 589

	
590 590
    typedef typename Parent::Node Node;
591 591
    typedef typename Parent::Arc Arc;
592 592

	
593 593
    void first(Node& i) const {
594 594
      Parent::first(i);
595 595
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
596 596
    }
597 597

	
598 598
    void first(Arc& i) const {
599 599
      Parent::first(i);
600 600
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::next(i);
601 601
    }
602 602

	
603 603
    void firstIn(Arc& i, const Node& n) const {
604 604
      Parent::firstIn(i, n);
605 605
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextIn(i);
606 606
    }
607 607

	
608 608
    void firstOut(Arc& i, const Node& n) const {
609 609
      Parent::firstOut(i, n);
610 610
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextOut(i);
611 611
    }
612 612

	
613 613
    void next(Node& i) const {
614 614
      Parent::next(i);
615 615
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
616 616
    }
617 617
    void next(Arc& i) const {
618 618
      Parent::next(i);
619 619
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::next(i);
620 620
    }
621 621
    void nextIn(Arc& i) const {
622 622
      Parent::nextIn(i);
623 623
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextIn(i);
624 624
    }
625 625

	
626 626
    void nextOut(Arc& i) const {
627 627
      Parent::nextOut(i);
628 628
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextOut(i);
629 629
    }
630 630

	
631 631
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
632 632
    void status(const Arc& a, bool v) const { _arc_filter->set(a, v); }
633 633

	
634 634
    bool status(const Node& n) const { return (*_node_filter)[n]; }
635 635
    bool status(const Arc& a) const { return (*_arc_filter)[a]; }
636 636

	
637 637
    typedef False NodeNumTag;
638 638
    typedef False ArcNumTag;
639 639

	
640 640
    typedef FindArcTagIndicator<DGR> FindArcTag;
641 641
    Arc findArc(const Node& source, const Node& target,
642 642
                const Arc& prev = INVALID) const {
643 643
      if (!(*_node_filter)[source] || !(*_node_filter)[target]) {
644 644
        return INVALID;
645 645
      }
646 646
      Arc arc = Parent::findArc(source, target, prev);
647 647
      while (arc != INVALID && !(*_arc_filter)[arc]) {
648 648
        arc = Parent::findArc(source, target, arc);
649 649
      }
650 650
      return arc;
651 651
    }
652 652

	
653 653
    template <typename V>
654
    class NodeMap 
654
    class NodeMap
655 655
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, false>,
656 656
          LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> {
657
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, false>, 
657
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, false>,
658 658
        LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, NodeMap<V>)> Parent;
659 659

	
660 660
    public:
661 661
      typedef V Value;
662 662

	
663 663
      NodeMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor)
664 664
        : Parent(adaptor) {}
665 665
      NodeMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor, const V& value)
666 666
        : Parent(adaptor, value) {}
667 667

	
668 668
    private:
669 669
      NodeMap& operator=(const NodeMap& cmap) {
670 670
        return operator=<NodeMap>(cmap);
671 671
      }
672 672

	
673 673
      template <typename CMap>
674 674
      NodeMap& operator=(const CMap& cmap) {
675 675
        Parent::operator=(cmap);
676 676
        return *this;
677 677
      }
678 678
    };
679 679

	
680 680
    template <typename V>
681
    class ArcMap 
681
    class ArcMap
682 682
      : public SubMapExtender<SubDigraphBase<DGR, NF, AF, false>,
683 683
          LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> {
684 684
      typedef SubMapExtender<SubDigraphBase<DGR, NF, AF, false>,
685 685
        LEMON_SCOPE_FIX(DigraphAdaptorBase<DGR>, ArcMap<V>)> Parent;
686 686

	
687 687
    public:
688 688
      typedef V Value;
689 689

	
690 690
      ArcMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor)
691 691
        : Parent(adaptor) {}
692 692
      ArcMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor, const V& value)
693 693
        : Parent(adaptor, value) {}
694 694

	
695 695
    private:
696 696
      ArcMap& operator=(const ArcMap& cmap) {
697 697
        return operator=<ArcMap>(cmap);
698 698
      }
699 699

	
700 700
      template <typename CMap>
701 701
      ArcMap& operator=(const CMap& cmap) {
702 702
        Parent::operator=(cmap);
703 703
        return *this;
704 704
      }
705 705
    };
706 706

	
707 707
  };
708 708

	
709 709
  /// \ingroup graph_adaptors
710 710
  ///
711 711
  /// \brief Adaptor class for hiding nodes and arcs in a digraph
712 712
  ///
713 713
  /// SubDigraph can be used for hiding nodes and arcs in a digraph.
714 714
  /// A \c bool node map and a \c bool arc map must be specified, which
715 715
  /// define the filters for nodes and arcs.
716 716
  /// Only the nodes and arcs with \c true filter value are
717 717
  /// shown in the subdigraph. The arcs that are incident to hidden
718 718
  /// nodes are also filtered out.
719 719
  /// This adaptor conforms to the \ref concepts::Digraph "Digraph" concept.
720 720
  ///
721 721
  /// The adapted digraph can also be modified through this adaptor
722 722
  /// by adding or removing nodes or arcs, unless the \c GR template
723 723
  /// parameter is set to be \c const.
724 724
  ///
725 725
  /// This class provides only linear time counting for nodes and arcs.
726 726
  ///
727 727
  /// \tparam DGR The type of the adapted digraph.
728 728
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
729 729
  /// It can also be specified to be \c const.
... ...
@@ -976,194 +976,194 @@
976 976
        Parent::nextOut(i);
977 977
    }
978 978

	
979 979
    void nextInc(Edge& i, bool& d) const {
980 980
      Parent::nextInc(i, d);
981 981
      while (i!=INVALID && (!(*_edge_filter)[i]
982 982
                            || !(*_node_filter)[Parent::u(i)]
983 983
                            || !(*_node_filter)[Parent::v(i)]))
984 984
        Parent::nextInc(i, d);
985 985
    }
986 986

	
987 987
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
988 988
    void status(const Edge& e, bool v) const { _edge_filter->set(e, v); }
989 989

	
990 990
    bool status(const Node& n) const { return (*_node_filter)[n]; }
991 991
    bool status(const Edge& e) const { return (*_edge_filter)[e]; }
992 992

	
993 993
    typedef False NodeNumTag;
994 994
    typedef False ArcNumTag;
995 995
    typedef False EdgeNumTag;
996 996

	
997 997
    typedef FindArcTagIndicator<Graph> FindArcTag;
998 998
    Arc findArc(const Node& u, const Node& v,
999 999
                const Arc& prev = INVALID) const {
1000 1000
      if (!(*_node_filter)[u] || !(*_node_filter)[v]) {
1001 1001
        return INVALID;
1002 1002
      }
1003 1003
      Arc arc = Parent::findArc(u, v, prev);
1004 1004
      while (arc != INVALID && !(*_edge_filter)[arc]) {
1005 1005
        arc = Parent::findArc(u, v, arc);
1006 1006
      }
1007 1007
      return arc;
1008 1008
    }
1009 1009

	
1010 1010
    typedef FindEdgeTagIndicator<Graph> FindEdgeTag;
1011 1011
    Edge findEdge(const Node& u, const Node& v,
1012 1012
                  const Edge& prev = INVALID) const {
1013 1013
      if (!(*_node_filter)[u] || !(*_node_filter)[v]) {
1014 1014
        return INVALID;
1015 1015
      }
1016 1016
      Edge edge = Parent::findEdge(u, v, prev);
1017 1017
      while (edge != INVALID && !(*_edge_filter)[edge]) {
1018 1018
        edge = Parent::findEdge(u, v, edge);
1019 1019
      }
1020 1020
      return edge;
1021 1021
    }
1022 1022

	
1023 1023
    template <typename V>
1024
    class NodeMap 
1024
    class NodeMap
1025 1025
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1026 1026
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> {
1027
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1027
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1028 1028
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> Parent;
1029 1029

	
1030 1030
    public:
1031 1031
      typedef V Value;
1032 1032

	
1033 1033
      NodeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1034 1034
        : Parent(adaptor) {}
1035 1035
      NodeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1036 1036
        : Parent(adaptor, value) {}
1037 1037

	
1038 1038
    private:
1039 1039
      NodeMap& operator=(const NodeMap& cmap) {
1040 1040
        return operator=<NodeMap>(cmap);
1041 1041
      }
1042 1042

	
1043 1043
      template <typename CMap>
1044 1044
      NodeMap& operator=(const CMap& cmap) {
1045 1045
        Parent::operator=(cmap);
1046 1046
        return *this;
1047 1047
      }
1048 1048
    };
1049 1049

	
1050 1050
    template <typename V>
1051
    class ArcMap 
1051
    class ArcMap
1052 1052
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1053 1053
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> {
1054
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1054
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1055 1055
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> Parent;
1056 1056

	
1057 1057
    public:
1058 1058
      typedef V Value;
1059 1059

	
1060 1060
      ArcMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1061 1061
        : Parent(adaptor) {}
1062 1062
      ArcMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1063 1063
        : Parent(adaptor, value) {}
1064 1064

	
1065 1065
    private:
1066 1066
      ArcMap& operator=(const ArcMap& cmap) {
1067 1067
        return operator=<ArcMap>(cmap);
1068 1068
      }
1069 1069

	
1070 1070
      template <typename CMap>
1071 1071
      ArcMap& operator=(const CMap& cmap) {
1072 1072
        Parent::operator=(cmap);
1073 1073
        return *this;
1074 1074
      }
1075 1075
    };
1076 1076

	
1077 1077
    template <typename V>
1078
    class EdgeMap 
1078
    class EdgeMap
1079 1079
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1080 1080
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> {
1081
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1081
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1082 1082
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> Parent;
1083 1083

	
1084 1084
    public:
1085 1085
      typedef V Value;
1086 1086

	
1087 1087
      EdgeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1088 1088
        : Parent(adaptor) {}
1089 1089

	
1090 1090
      EdgeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1091 1091
        : Parent(adaptor, value) {}
1092 1092

	
1093 1093
    private:
1094 1094
      EdgeMap& operator=(const EdgeMap& cmap) {
1095 1095
        return operator=<EdgeMap>(cmap);
1096 1096
      }
1097 1097

	
1098 1098
      template <typename CMap>
1099 1099
      EdgeMap& operator=(const CMap& cmap) {
1100 1100
        Parent::operator=(cmap);
1101 1101
        return *this;
1102 1102
      }
1103 1103
    };
1104 1104

	
1105 1105
  };
1106 1106

	
1107 1107
  template <typename GR, typename NF, typename EF>
1108 1108
  class SubGraphBase<GR, NF, EF, false>
1109 1109
    : public GraphAdaptorBase<GR> {
1110 1110
    typedef GraphAdaptorBase<GR> Parent;
1111 1111
  public:
1112 1112
    typedef GR Graph;
1113 1113
    typedef NF NodeFilterMap;
1114 1114
    typedef EF EdgeFilterMap;
1115 1115

	
1116 1116
    typedef SubGraphBase Adaptor;
1117 1117
  protected:
1118 1118
    NF* _node_filter;
1119 1119
    EF* _edge_filter;
1120
    SubGraphBase() 
1121
	  : Parent(), _node_filter(0), _edge_filter(0) { }
1120
    SubGraphBase()
1121
          : Parent(), _node_filter(0), _edge_filter(0) { }
1122 1122

	
1123 1123
    void initialize(GR& graph, NF& node_filter, EF& edge_filter) {
1124 1124
      Parent::initialize(graph);
1125 1125
      _node_filter = &node_filter;
1126 1126
      _edge_filter = &edge_filter;
1127 1127
    }
1128 1128

	
1129 1129
  public:
1130 1130

	
1131 1131
    typedef typename Parent::Node Node;
1132 1132
    typedef typename Parent::Arc Arc;
1133 1133
    typedef typename Parent::Edge Edge;
1134 1134

	
1135 1135
    void first(Node& i) const {
1136 1136
      Parent::first(i);
1137 1137
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
1138 1138
    }
1139 1139

	
1140 1140
    void first(Arc& i) const {
1141 1141
      Parent::first(i);
1142 1142
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1143 1143
    }
1144 1144

	
1145 1145
    void first(Edge& i) const {
1146 1146
      Parent::first(i);
1147 1147
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1148 1148
    }
1149 1149

	
1150 1150
    void firstIn(Arc& i, const Node& n) const {
1151 1151
      Parent::firstIn(i, n);
1152 1152
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextIn(i);
1153 1153
    }
1154 1154

	
1155 1155
    void firstOut(Arc& i, const Node& n) const {
1156 1156
      Parent::firstOut(i, n);
1157 1157
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextOut(i);
1158 1158
    }
1159 1159

	
1160 1160
    void firstInc(Edge& i, bool& d, const Node& n) const {
1161 1161
      Parent::firstInc(i, d, n);
1162 1162
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextInc(i, d);
1163 1163
    }
1164 1164

	
1165 1165
    void next(Node& i) const {
1166 1166
      Parent::next(i);
1167 1167
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
1168 1168
    }
1169 1169
    void next(Arc& i) const {
... ...
@@ -1174,155 +1174,155 @@
1174 1174
      Parent::next(i);
1175 1175
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1176 1176
    }
1177 1177
    void nextIn(Arc& i) const {
1178 1178
      Parent::nextIn(i);
1179 1179
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextIn(i);
1180 1180
    }
1181 1181

	
1182 1182
    void nextOut(Arc& i) const {
1183 1183
      Parent::nextOut(i);
1184 1184
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextOut(i);
1185 1185
    }
1186 1186
    void nextInc(Edge& i, bool& d) const {
1187 1187
      Parent::nextInc(i, d);
1188 1188
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextInc(i, d);
1189 1189
    }
1190 1190

	
1191 1191
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
1192 1192
    void status(const Edge& e, bool v) const { _edge_filter->set(e, v); }
1193 1193

	
1194 1194
    bool status(const Node& n) const { return (*_node_filter)[n]; }
1195 1195
    bool status(const Edge& e) const { return (*_edge_filter)[e]; }
1196 1196

	
1197 1197
    typedef False NodeNumTag;
1198 1198
    typedef False ArcNumTag;
1199 1199
    typedef False EdgeNumTag;
1200 1200

	
1201 1201
    typedef FindArcTagIndicator<Graph> FindArcTag;
1202 1202
    Arc findArc(const Node& u, const Node& v,
1203 1203
                const Arc& prev = INVALID) const {
1204 1204
      Arc arc = Parent::findArc(u, v, prev);
1205 1205
      while (arc != INVALID && !(*_edge_filter)[arc]) {
1206 1206
        arc = Parent::findArc(u, v, arc);
1207 1207
      }
1208 1208
      return arc;
1209 1209
    }
1210 1210

	
1211 1211
    typedef FindEdgeTagIndicator<Graph> FindEdgeTag;
1212 1212
    Edge findEdge(const Node& u, const Node& v,
1213 1213
                  const Edge& prev = INVALID) const {
1214 1214
      Edge edge = Parent::findEdge(u, v, prev);
1215 1215
      while (edge != INVALID && !(*_edge_filter)[edge]) {
1216 1216
        edge = Parent::findEdge(u, v, edge);
1217 1217
      }
1218 1218
      return edge;
1219 1219
    }
1220 1220

	
1221 1221
    template <typename V>
1222
    class NodeMap 
1222
    class NodeMap
1223 1223
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1224 1224
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> {
1225
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1225
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1226 1226
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> Parent;
1227 1227

	
1228 1228
    public:
1229 1229
      typedef V Value;
1230 1230

	
1231 1231
      NodeMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1232 1232
        : Parent(adaptor) {}
1233 1233
      NodeMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1234 1234
        : Parent(adaptor, value) {}
1235 1235

	
1236 1236
    private:
1237 1237
      NodeMap& operator=(const NodeMap& cmap) {
1238 1238
        return operator=<NodeMap>(cmap);
1239 1239
      }
1240 1240

	
1241 1241
      template <typename CMap>
1242 1242
      NodeMap& operator=(const CMap& cmap) {
1243 1243
        Parent::operator=(cmap);
1244 1244
        return *this;
1245 1245
      }
1246 1246
    };
1247 1247

	
1248 1248
    template <typename V>
1249
    class ArcMap 
1249
    class ArcMap
1250 1250
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1251 1251
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> {
1252
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1252
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1253 1253
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> Parent;
1254 1254

	
1255 1255
    public:
1256 1256
      typedef V Value;
1257 1257

	
1258 1258
      ArcMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1259 1259
        : Parent(adaptor) {}
1260 1260
      ArcMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1261 1261
        : Parent(adaptor, value) {}
1262 1262

	
1263 1263
    private:
1264 1264
      ArcMap& operator=(const ArcMap& cmap) {
1265 1265
        return operator=<ArcMap>(cmap);
1266 1266
      }
1267 1267

	
1268 1268
      template <typename CMap>
1269 1269
      ArcMap& operator=(const CMap& cmap) {
1270 1270
        Parent::operator=(cmap);
1271 1271
        return *this;
1272 1272
      }
1273 1273
    };
1274 1274

	
1275 1275
    template <typename V>
1276
    class EdgeMap 
1276
    class EdgeMap
1277 1277
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1278 1278
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> {
1279
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1280
	LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> Parent;
1279
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1280
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> Parent;
1281 1281

	
1282 1282
    public:
1283 1283
      typedef V Value;
1284 1284

	
1285 1285
      EdgeMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1286 1286
        : Parent(adaptor) {}
1287 1287

	
1288 1288
      EdgeMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1289 1289
        : Parent(adaptor, value) {}
1290 1290

	
1291 1291
    private:
1292 1292
      EdgeMap& operator=(const EdgeMap& cmap) {
1293 1293
        return operator=<EdgeMap>(cmap);
1294 1294
      }
1295 1295

	
1296 1296
      template <typename CMap>
1297 1297
      EdgeMap& operator=(const CMap& cmap) {
1298 1298
        Parent::operator=(cmap);
1299 1299
        return *this;
1300 1300
      }
1301 1301
    };
1302 1302

	
1303 1303
  };
1304 1304

	
1305 1305
  /// \ingroup graph_adaptors
1306 1306
  ///
1307 1307
  /// \brief Adaptor class for hiding nodes and edges in an undirected
1308 1308
  /// graph.
1309 1309
  ///
1310 1310
  /// SubGraph can be used for hiding nodes and edges in a graph.
1311 1311
  /// A \c bool node map and a \c bool edge map must be specified, which
1312 1312
  /// define the filters for nodes and edges.
1313 1313
  /// Only the nodes and edges with \c true filter value are
1314 1314
  /// shown in the subgraph. The edges that are incident to hidden
1315 1315
  /// nodes are also filtered out.
1316 1316
  /// This adaptor conforms to the \ref concepts::Graph "Graph" concept.
1317 1317
  ///
1318 1318
  /// The adapted graph can also be modified through this adaptor
1319 1319
  /// by adding or removing nodes or edges, unless the \c GR template
1320 1320
  /// parameter is set to be \c const.
1321 1321
  ///
1322 1322
  /// This class provides only linear time counting for nodes, edges and arcs.
1323 1323
  ///
1324 1324
  /// \tparam GR The type of the adapted graph.
1325 1325
  /// It must conform to the \ref concepts::Graph "Graph" concept.
1326 1326
  /// It can also be specified to be \c const.
1327 1327
  /// \tparam NF The type of the node filter map.
1328 1328
  /// It must be a \c bool (or convertible) node map of the
... ...
@@ -1459,246 +1459,246 @@
1459 1459
  subGraph(const GR& graph, const NF& node_filter, const EF& edge_filter) {
1460 1460
    return SubGraph<const GR, const NF, const EF>
1461 1461
      (graph, node_filter, edge_filter);
1462 1462
  }
1463 1463

	
1464 1464

	
1465 1465
  /// \ingroup graph_adaptors
1466 1466
  ///
1467 1467
  /// \brief Adaptor class for hiding nodes in a digraph or a graph.
1468 1468
  ///
1469 1469
  /// FilterNodes adaptor can be used for hiding nodes in a digraph or a
1470 1470
  /// graph. A \c bool node map must be specified, which defines the filter
1471 1471
  /// for the nodes. Only the nodes with \c true filter value and the
1472 1472
  /// arcs/edges incident to nodes both with \c true filter value are shown
1473 1473
  /// in the subgraph. This adaptor conforms to the \ref concepts::Digraph
1474 1474
  /// "Digraph" concept or the \ref concepts::Graph "Graph" concept
1475 1475
  /// depending on the \c GR template parameter.
1476 1476
  ///
1477 1477
  /// The adapted (di)graph can also be modified through this adaptor
1478 1478
  /// by adding or removing nodes or arcs/edges, unless the \c GR template
1479 1479
  /// parameter is set to be \c const.
1480 1480
  ///
1481 1481
  /// This class provides only linear time item counting.
1482 1482
  ///
1483 1483
  /// \tparam GR The type of the adapted digraph or graph.
1484 1484
  /// It must conform to the \ref concepts::Digraph "Digraph" concept
1485 1485
  /// or the \ref concepts::Graph "Graph" concept.
1486 1486
  /// It can also be specified to be \c const.
1487 1487
  /// \tparam NF The type of the node filter map.
1488 1488
  /// It must be a \c bool (or convertible) node map of the
1489 1489
  /// adapted (di)graph. The default type is
1490 1490
  /// \ref concepts::Graph::NodeMap "GR::NodeMap<bool>".
1491 1491
  ///
1492 1492
  /// \note The \c Node and <tt>Arc/Edge</tt> types of this adaptor and the
1493 1493
  /// adapted (di)graph are convertible to each other.
1494 1494
#ifdef DOXYGEN
1495 1495
  template<typename GR, typename NF>
1496 1496
  class FilterNodes {
1497 1497
#else
1498 1498
  template<typename GR,
1499 1499
           typename NF = typename GR::template NodeMap<bool>,
1500 1500
           typename Enable = void>
1501 1501
  class FilterNodes :
1502 1502
    public DigraphAdaptorExtender<
1503 1503
      SubDigraphBase<GR, NF, ConstMap<typename GR::Arc, Const<bool, true> >,
1504 1504
                     true> > {
1505 1505
#endif
1506 1506
    typedef DigraphAdaptorExtender<
1507
      SubDigraphBase<GR, NF, ConstMap<typename GR::Arc, Const<bool, true> >, 
1507
      SubDigraphBase<GR, NF, ConstMap<typename GR::Arc, Const<bool, true> >,
1508 1508
                     true> > Parent;
1509 1509

	
1510 1510
  public:
1511 1511

	
1512 1512
    typedef GR Digraph;
1513 1513
    typedef NF NodeFilterMap;
1514 1514

	
1515 1515
    typedef typename Parent::Node Node;
1516 1516

	
1517 1517
  protected:
1518 1518
    ConstMap<typename Digraph::Arc, Const<bool, true> > const_true_map;
1519 1519

	
1520 1520
    FilterNodes() : const_true_map() {}
1521 1521

	
1522 1522
  public:
1523 1523

	
1524 1524
    /// \brief Constructor
1525 1525
    ///
1526 1526
    /// Creates a subgraph for the given digraph or graph with the
1527 1527
    /// given node filter map.
1528
    FilterNodes(GR& graph, NF& node_filter) 
1528
    FilterNodes(GR& graph, NF& node_filter)
1529 1529
      : Parent(), const_true_map()
1530 1530
    {
1531 1531
      Parent::initialize(graph, node_filter, const_true_map);
1532 1532
    }
1533 1533

	
1534 1534
    /// \brief Sets the status of the given node
1535 1535
    ///
1536 1536
    /// This function sets the status of the given node.
1537 1537
    /// It is done by simply setting the assigned value of \c n
1538 1538
    /// to \c v in the node filter map.
1539 1539
    void status(const Node& n, bool v) const { Parent::status(n, v); }
1540 1540

	
1541 1541
    /// \brief Returns the status of the given node
1542 1542
    ///
1543 1543
    /// This function returns the status of the given node.
1544 1544
    /// It is \c true if the given node is enabled (i.e. not hidden).
1545 1545
    bool status(const Node& n) const { return Parent::status(n); }
1546 1546

	
1547 1547
    /// \brief Disables the given node
1548 1548
    ///
1549 1549
    /// This function disables the given node, so the iteration
1550 1550
    /// jumps over it.
1551 1551
    /// It is the same as \ref status() "status(n, false)".
1552 1552
    void disable(const Node& n) const { Parent::status(n, false); }
1553 1553

	
1554 1554
    /// \brief Enables the given node
1555 1555
    ///
1556 1556
    /// This function enables the given node.
1557 1557
    /// It is the same as \ref status() "status(n, true)".
1558 1558
    void enable(const Node& n) const { Parent::status(n, true); }
1559 1559

	
1560 1560
  };
1561 1561

	
1562 1562
  template<typename GR, typename NF>
1563 1563
  class FilterNodes<GR, NF,
1564 1564
                    typename enable_if<UndirectedTagIndicator<GR> >::type> :
1565 1565
    public GraphAdaptorExtender<
1566
      SubGraphBase<GR, NF, ConstMap<typename GR::Edge, Const<bool, true> >, 
1566
      SubGraphBase<GR, NF, ConstMap<typename GR::Edge, Const<bool, true> >,
1567 1567
                   true> > {
1568 1568

	
1569 1569
    typedef GraphAdaptorExtender<
1570
      SubGraphBase<GR, NF, ConstMap<typename GR::Edge, Const<bool, true> >, 
1570
      SubGraphBase<GR, NF, ConstMap<typename GR::Edge, Const<bool, true> >,
1571 1571
                   true> > Parent;
1572 1572

	
1573 1573
  public:
1574 1574

	
1575 1575
    typedef GR Graph;
1576 1576
    typedef NF NodeFilterMap;
1577 1577

	
1578 1578
    typedef typename Parent::Node Node;
1579 1579

	
1580 1580
  protected:
1581 1581
    ConstMap<typename GR::Edge, Const<bool, true> > const_true_map;
1582 1582

	
1583 1583
    FilterNodes() : const_true_map() {}
1584 1584

	
1585 1585
  public:
1586 1586

	
1587 1587
    FilterNodes(GR& graph, NodeFilterMap& node_filter) :
1588 1588
      Parent(), const_true_map() {
1589 1589
      Parent::initialize(graph, node_filter, const_true_map);
1590 1590
    }
1591 1591

	
1592 1592
    void status(const Node& n, bool v) const { Parent::status(n, v); }
1593 1593
    bool status(const Node& n) const { return Parent::status(n); }
1594 1594
    void disable(const Node& n) const { Parent::status(n, false); }
1595 1595
    void enable(const Node& n) const { Parent::status(n, true); }
1596 1596

	
1597 1597
  };
1598 1598

	
1599 1599

	
1600 1600
  /// \brief Returns a read-only FilterNodes adaptor
1601 1601
  ///
1602 1602
  /// This function just returns a read-only \ref FilterNodes adaptor.
1603 1603
  /// \ingroup graph_adaptors
1604 1604
  /// \relates FilterNodes
1605 1605
  template<typename GR, typename NF>
1606 1606
  FilterNodes<const GR, NF>
1607 1607
  filterNodes(const GR& graph, NF& node_filter) {
1608 1608
    return FilterNodes<const GR, NF>(graph, node_filter);
1609 1609
  }
1610 1610

	
1611 1611
  template<typename GR, typename NF>
1612 1612
  FilterNodes<const GR, const NF>
1613 1613
  filterNodes(const GR& graph, const NF& node_filter) {
1614 1614
    return FilterNodes<const GR, const NF>(graph, node_filter);
1615 1615
  }
1616 1616

	
1617 1617
  /// \ingroup graph_adaptors
1618 1618
  ///
1619 1619
  /// \brief Adaptor class for hiding arcs in a digraph.
1620 1620
  ///
1621 1621
  /// FilterArcs adaptor can be used for hiding arcs in a digraph.
1622 1622
  /// A \c bool arc map must be specified, which defines the filter for
1623 1623
  /// the arcs. Only the arcs with \c true filter value are shown in the
1624 1624
  /// subdigraph. This adaptor conforms to the \ref concepts::Digraph
1625 1625
  /// "Digraph" concept.
1626 1626
  ///
1627 1627
  /// The adapted digraph can also be modified through this adaptor
1628 1628
  /// by adding or removing nodes or arcs, unless the \c GR template
1629 1629
  /// parameter is set to be \c const.
1630 1630
  ///
1631 1631
  /// This class provides only linear time counting for nodes and arcs.
1632 1632
  ///
1633 1633
  /// \tparam DGR The type of the adapted digraph.
1634 1634
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
1635 1635
  /// It can also be specified to be \c const.
1636 1636
  /// \tparam AF The type of the arc filter map.
1637 1637
  /// It must be a \c bool (or convertible) arc map of the
1638 1638
  /// adapted digraph. The default type is
1639 1639
  /// \ref concepts::Digraph::ArcMap "DGR::ArcMap<bool>".
1640 1640
  ///
1641 1641
  /// \note The \c Node and \c Arc types of this adaptor and the adapted
1642 1642
  /// digraph are convertible to each other.
1643 1643
#ifdef DOXYGEN
1644 1644
  template<typename DGR,
1645 1645
           typename AF>
1646 1646
  class FilterArcs {
1647 1647
#else
1648 1648
  template<typename DGR,
1649 1649
           typename AF = typename DGR::template ArcMap<bool> >
1650 1650
  class FilterArcs :
1651 1651
    public DigraphAdaptorExtender<
1652 1652
      SubDigraphBase<DGR, ConstMap<typename DGR::Node, Const<bool, true> >,
1653 1653
                     AF, false> > {
1654 1654
#endif
1655 1655
    typedef DigraphAdaptorExtender<
1656
      SubDigraphBase<DGR, ConstMap<typename DGR::Node, Const<bool, true> >, 
1656
      SubDigraphBase<DGR, ConstMap<typename DGR::Node, Const<bool, true> >,
1657 1657
                     AF, false> > Parent;
1658 1658

	
1659 1659
  public:
1660 1660

	
1661 1661
    /// The type of the adapted digraph.
1662 1662
    typedef DGR Digraph;
1663 1663
    /// The type of the arc filter map.
1664 1664
    typedef AF ArcFilterMap;
1665 1665

	
1666 1666
    typedef typename Parent::Arc Arc;
1667 1667

	
1668 1668
  protected:
1669 1669
    ConstMap<typename DGR::Node, Const<bool, true> > const_true_map;
1670 1670

	
1671 1671
    FilterArcs() : const_true_map() {}
1672 1672

	
1673 1673
  public:
1674 1674

	
1675 1675
    /// \brief Constructor
1676 1676
    ///
1677 1677
    /// Creates a subdigraph for the given digraph with the given arc
1678 1678
    /// filter map.
1679 1679
    FilterArcs(DGR& digraph, ArcFilterMap& arc_filter)
1680 1680
      : Parent(), const_true_map() {
1681 1681
      Parent::initialize(digraph, const_true_map, arc_filter);
1682 1682
    }
1683 1683

	
1684 1684
    /// \brief Sets the status of the given arc
1685 1685
    ///
1686 1686
    /// This function sets the status of the given arc.
1687 1687
    /// It is done by simply setting the assigned value of \c a
1688 1688
    /// to \c v in the arc filter map.
1689 1689
    void status(const Arc& a, bool v) const { Parent::status(a, v); }
1690 1690

	
1691 1691
    /// \brief Returns the status of the given arc
1692 1692
    ///
1693 1693
    /// This function returns the status of the given arc.
1694 1694
    /// It is \c true if the given arc is enabled (i.e. not hidden).
1695 1695
    bool status(const Arc& a) const { return Parent::status(a); }
1696 1696

	
1697 1697
    /// \brief Disables the given arc
1698 1698
    ///
1699 1699
    /// This function disables the given arc in the subdigraph,
1700 1700
    /// so the iteration jumps over it.
1701 1701
    /// It is the same as \ref status() "status(a, false)".
1702 1702
    void disable(const Arc& a) const { Parent::status(a, false); }
1703 1703

	
1704 1704
    /// \brief Enables the given arc
... ...
@@ -1716,194 +1716,194 @@
1716 1716
  /// \relates FilterArcs
1717 1717
  template<typename DGR, typename AF>
1718 1718
  FilterArcs<const DGR, AF>
1719 1719
  filterArcs(const DGR& digraph, AF& arc_filter) {
1720 1720
    return FilterArcs<const DGR, AF>(digraph, arc_filter);
1721 1721
  }
1722 1722

	
1723 1723
  template<typename DGR, typename AF>
1724 1724
  FilterArcs<const DGR, const AF>
1725 1725
  filterArcs(const DGR& digraph, const AF& arc_filter) {
1726 1726
    return FilterArcs<const DGR, const AF>(digraph, arc_filter);
1727 1727
  }
1728 1728

	
1729 1729
  /// \ingroup graph_adaptors
1730 1730
  ///
1731 1731
  /// \brief Adaptor class for hiding edges in a graph.
1732 1732
  ///
1733 1733
  /// FilterEdges adaptor can be used for hiding edges in a graph.
1734 1734
  /// A \c bool edge map must be specified, which defines the filter for
1735 1735
  /// the edges. Only the edges with \c true filter value are shown in the
1736 1736
  /// subgraph. This adaptor conforms to the \ref concepts::Graph
1737 1737
  /// "Graph" concept.
1738 1738
  ///
1739 1739
  /// The adapted graph can also be modified through this adaptor
1740 1740
  /// by adding or removing nodes or edges, unless the \c GR template
1741 1741
  /// parameter is set to be \c const.
1742 1742
  ///
1743 1743
  /// This class provides only linear time counting for nodes, edges and arcs.
1744 1744
  ///
1745 1745
  /// \tparam GR The type of the adapted graph.
1746 1746
  /// It must conform to the \ref concepts::Graph "Graph" concept.
1747 1747
  /// It can also be specified to be \c const.
1748 1748
  /// \tparam EF The type of the edge filter map.
1749 1749
  /// It must be a \c bool (or convertible) edge map of the
1750 1750
  /// adapted graph. The default type is
1751 1751
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<bool>".
1752 1752
  ///
1753 1753
  /// \note The \c Node, \c Edge and \c Arc types of this adaptor and the
1754 1754
  /// adapted graph are convertible to each other.
1755 1755
#ifdef DOXYGEN
1756 1756
  template<typename GR,
1757 1757
           typename EF>
1758 1758
  class FilterEdges {
1759 1759
#else
1760 1760
  template<typename GR,
1761 1761
           typename EF = typename GR::template EdgeMap<bool> >
1762 1762
  class FilterEdges :
1763 1763
    public GraphAdaptorExtender<
1764
      SubGraphBase<GR, ConstMap<typename GR::Node, Const<bool, true> >, 
1764
      SubGraphBase<GR, ConstMap<typename GR::Node, Const<bool, true> >,
1765 1765
                   EF, false> > {
1766 1766
#endif
1767 1767
    typedef GraphAdaptorExtender<
1768
      SubGraphBase<GR, ConstMap<typename GR::Node, Const<bool, true > >, 
1768
      SubGraphBase<GR, ConstMap<typename GR::Node, Const<bool, true > >,
1769 1769
                   EF, false> > Parent;
1770 1770

	
1771 1771
  public:
1772 1772

	
1773 1773
    /// The type of the adapted graph.
1774 1774
    typedef GR Graph;
1775 1775
    /// The type of the edge filter map.
1776 1776
    typedef EF EdgeFilterMap;
1777 1777

	
1778 1778
    typedef typename Parent::Edge Edge;
1779 1779

	
1780 1780
  protected:
1781 1781
    ConstMap<typename GR::Node, Const<bool, true> > const_true_map;
1782 1782

	
1783 1783
    FilterEdges() : const_true_map(true) {
1784 1784
      Parent::setNodeFilterMap(const_true_map);
1785 1785
    }
1786 1786

	
1787 1787
  public:
1788 1788

	
1789 1789
    /// \brief Constructor
1790 1790
    ///
1791 1791
    /// Creates a subgraph for the given graph with the given edge
1792 1792
    /// filter map.
1793
    FilterEdges(GR& graph, EF& edge_filter) 
1793
    FilterEdges(GR& graph, EF& edge_filter)
1794 1794
      : Parent(), const_true_map() {
1795 1795
      Parent::initialize(graph, const_true_map, edge_filter);
1796 1796
    }
1797 1797

	
1798 1798
    /// \brief Sets the status of the given edge
1799 1799
    ///
1800 1800
    /// This function sets the status of the given edge.
1801 1801
    /// It is done by simply setting the assigned value of \c e
1802 1802
    /// to \c v in the edge filter map.
1803 1803
    void status(const Edge& e, bool v) const { Parent::status(e, v); }
1804 1804

	
1805 1805
    /// \brief Returns the status of the given edge
1806 1806
    ///
1807 1807
    /// This function returns the status of the given edge.
1808 1808
    /// It is \c true if the given edge is enabled (i.e. not hidden).
1809 1809
    bool status(const Edge& e) const { return Parent::status(e); }
1810 1810

	
1811 1811
    /// \brief Disables the given edge
1812 1812
    ///
1813 1813
    /// This function disables the given edge in the subgraph,
1814 1814
    /// so the iteration jumps over it.
1815 1815
    /// It is the same as \ref status() "status(e, false)".
1816 1816
    void disable(const Edge& e) const { Parent::status(e, false); }
1817 1817

	
1818 1818
    /// \brief Enables the given edge
1819 1819
    ///
1820 1820
    /// This function enables the given edge in the subgraph.
1821 1821
    /// It is the same as \ref status() "status(e, true)".
1822 1822
    void enable(const Edge& e) const { Parent::status(e, true); }
1823 1823

	
1824 1824
  };
1825 1825

	
1826 1826
  /// \brief Returns a read-only FilterEdges adaptor
1827 1827
  ///
1828 1828
  /// This function just returns a read-only \ref FilterEdges adaptor.
1829 1829
  /// \ingroup graph_adaptors
1830 1830
  /// \relates FilterEdges
1831 1831
  template<typename GR, typename EF>
1832 1832
  FilterEdges<const GR, EF>
1833 1833
  filterEdges(const GR& graph, EF& edge_filter) {
1834 1834
    return FilterEdges<const GR, EF>(graph, edge_filter);
1835 1835
  }
1836 1836

	
1837 1837
  template<typename GR, typename EF>
1838 1838
  FilterEdges<const GR, const EF>
1839 1839
  filterEdges(const GR& graph, const EF& edge_filter) {
1840 1840
    return FilterEdges<const GR, const EF>(graph, edge_filter);
1841 1841
  }
1842 1842

	
1843 1843

	
1844 1844
  template <typename DGR>
1845 1845
  class UndirectorBase {
1846 1846
  public:
1847 1847
    typedef DGR Digraph;
1848 1848
    typedef UndirectorBase Adaptor;
1849 1849

	
1850 1850
    typedef True UndirectedTag;
1851 1851

	
1852 1852
    typedef typename Digraph::Arc Edge;
1853 1853
    typedef typename Digraph::Node Node;
1854 1854

	
1855 1855
    class Arc {
1856 1856
      friend class UndirectorBase;
1857 1857
    protected:
1858 1858
      Edge _edge;
1859 1859
      bool _forward;
1860 1860

	
1861
      Arc(const Edge& edge, bool forward) 
1861
      Arc(const Edge& edge, bool forward)
1862 1862
        : _edge(edge), _forward(forward) {}
1863 1863

	
1864 1864
    public:
1865 1865
      Arc() {}
1866 1866

	
1867 1867
      Arc(Invalid) : _edge(INVALID), _forward(true) {}
1868 1868

	
1869 1869
      operator const Edge&() const { return _edge; }
1870 1870

	
1871 1871
      bool operator==(const Arc &other) const {
1872 1872
        return _forward == other._forward && _edge == other._edge;
1873 1873
      }
1874 1874
      bool operator!=(const Arc &other) const {
1875 1875
        return _forward != other._forward || _edge != other._edge;
1876 1876
      }
1877 1877
      bool operator<(const Arc &other) const {
1878 1878
        return _forward < other._forward ||
1879 1879
          (_forward == other._forward && _edge < other._edge);
1880 1880
      }
1881 1881
    };
1882 1882

	
1883 1883
    void first(Node& n) const {
1884 1884
      _digraph->first(n);
1885 1885
    }
1886 1886

	
1887 1887
    void next(Node& n) const {
1888 1888
      _digraph->next(n);
1889 1889
    }
1890 1890

	
1891 1891
    void first(Arc& a) const {
1892 1892
      _digraph->first(a._edge);
1893 1893
      a._forward = true;
1894 1894
    }
1895 1895

	
1896 1896
    void next(Arc& a) const {
1897 1897
      if (a._forward) {
1898 1898
        a._forward = false;
1899 1899
      } else {
1900 1900
        _digraph->next(a._edge);
1901 1901
        a._forward = true;
1902 1902
      }
1903 1903
    }
1904 1904

	
1905 1905
    void first(Edge& e) const {
1906 1906
      _digraph->first(e);
1907 1907
    }
1908 1908

	
1909 1909
    void next(Edge& e) const {
... ...
@@ -2053,97 +2053,97 @@
2053 2053
    }
2054 2054

	
2055 2055
    typedef FindArcTag FindEdgeTag;
2056 2056
    Edge findEdge(Node s, Node t, Edge p = INVALID) const {
2057 2057
      if (s != t) {
2058 2058
        if (p == INVALID) {
2059 2059
          Edge arc = _digraph->findArc(s, t);
2060 2060
          if (arc != INVALID) return arc;
2061 2061
          arc = _digraph->findArc(t, s);
2062 2062
          if (arc != INVALID) return arc;
2063 2063
        } else if (_digraph->source(p) == s) {
2064 2064
          Edge arc = _digraph->findArc(s, t, p);
2065 2065
          if (arc != INVALID) return arc;
2066 2066
          arc = _digraph->findArc(t, s);
2067 2067
          if (arc != INVALID) return arc;
2068 2068
        } else {
2069 2069
          Edge arc = _digraph->findArc(t, s, p);
2070 2070
          if (arc != INVALID) return arc;
2071 2071
        }
2072 2072
      } else {
2073 2073
        return _digraph->findArc(s, t, p);
2074 2074
      }
2075 2075
      return INVALID;
2076 2076
    }
2077 2077

	
2078 2078
  private:
2079 2079

	
2080 2080
    template <typename V>
2081 2081
    class ArcMapBase {
2082 2082
    private:
2083 2083

	
2084 2084
      typedef typename DGR::template ArcMap<V> MapImpl;
2085 2085

	
2086 2086
    public:
2087 2087

	
2088 2088
      typedef typename MapTraits<MapImpl>::ReferenceMapTag ReferenceMapTag;
2089 2089

	
2090 2090
      typedef V Value;
2091 2091
      typedef Arc Key;
2092 2092
      typedef typename MapTraits<MapImpl>::ConstReturnValue ConstReturnValue;
2093 2093
      typedef typename MapTraits<MapImpl>::ReturnValue ReturnValue;
2094 2094
      typedef typename MapTraits<MapImpl>::ConstReturnValue ConstReference;
2095 2095
      typedef typename MapTraits<MapImpl>::ReturnValue Reference;
2096 2096

	
2097 2097
      ArcMapBase(const UndirectorBase<DGR>& adaptor) :
2098 2098
        _forward(*adaptor._digraph), _backward(*adaptor._digraph) {}
2099 2099

	
2100 2100
      ArcMapBase(const UndirectorBase<DGR>& adaptor, const V& value)
2101
        : _forward(*adaptor._digraph, value), 
2101
        : _forward(*adaptor._digraph, value),
2102 2102
          _backward(*adaptor._digraph, value) {}
2103 2103

	
2104 2104
      void set(const Arc& a, const V& value) {
2105 2105
        if (direction(a)) {
2106 2106
          _forward.set(a, value);
2107 2107
        } else {
2108 2108
          _backward.set(a, value);
2109 2109
        }
2110 2110
      }
2111 2111

	
2112 2112
      ConstReturnValue operator[](const Arc& a) const {
2113 2113
        if (direction(a)) {
2114 2114
          return _forward[a];
2115 2115
        } else {
2116 2116
          return _backward[a];
2117 2117
        }
2118 2118
      }
2119 2119

	
2120 2120
      ReturnValue operator[](const Arc& a) {
2121 2121
        if (direction(a)) {
2122 2122
          return _forward[a];
2123 2123
        } else {
2124 2124
          return _backward[a];
2125 2125
        }
2126 2126
      }
2127 2127

	
2128 2128
    protected:
2129 2129

	
2130 2130
      MapImpl _forward, _backward;
2131 2131

	
2132 2132
    };
2133 2133

	
2134 2134
  public:
2135 2135

	
2136 2136
    template <typename V>
2137 2137
    class NodeMap : public DGR::template NodeMap<V> {
2138 2138
      typedef typename DGR::template NodeMap<V> Parent;
2139 2139

	
2140 2140
    public:
2141 2141
      typedef V Value;
2142 2142

	
2143 2143
      explicit NodeMap(const UndirectorBase<DGR>& adaptor)
2144 2144
        : Parent(*adaptor._digraph) {}
2145 2145

	
2146 2146
      NodeMap(const UndirectorBase<DGR>& adaptor, const V& value)
2147 2147
        : Parent(*adaptor._digraph, value) { }
2148 2148

	
2149 2149
    private:
... ...
@@ -2171,97 +2171,97 @@
2171 2171
        : Parent(adaptor) {}
2172 2172

	
2173 2173
      ArcMap(const UndirectorBase<DGR>& adaptor, const V& value)
2174 2174
        : Parent(adaptor, value) {}
2175 2175

	
2176 2176
    private:
2177 2177
      ArcMap& operator=(const ArcMap& cmap) {
2178 2178
        return operator=<ArcMap>(cmap);
2179 2179
      }
2180 2180

	
2181 2181
      template <typename CMap>
2182 2182
      ArcMap& operator=(const CMap& cmap) {
2183 2183
        Parent::operator=(cmap);
2184 2184
        return *this;
2185 2185
      }
2186 2186
    };
2187 2187

	
2188 2188
    template <typename V>
2189 2189
    class EdgeMap : public Digraph::template ArcMap<V> {
2190 2190
      typedef typename Digraph::template ArcMap<V> Parent;
2191 2191

	
2192 2192
    public:
2193 2193
      typedef V Value;
2194 2194

	
2195 2195
      explicit EdgeMap(const UndirectorBase<DGR>& adaptor)
2196 2196
        : Parent(*adaptor._digraph) {}
2197 2197

	
2198 2198
      EdgeMap(const UndirectorBase<DGR>& adaptor, const V& value)
2199 2199
        : Parent(*adaptor._digraph, value) {}
2200 2200

	
2201 2201
    private:
2202 2202
      EdgeMap& operator=(const EdgeMap& cmap) {
2203 2203
        return operator=<EdgeMap>(cmap);
2204 2204
      }
2205 2205

	
2206 2206
      template <typename CMap>
2207 2207
      EdgeMap& operator=(const CMap& cmap) {
2208 2208
        Parent::operator=(cmap);
2209 2209
        return *this;
2210 2210
      }
2211 2211

	
2212 2212
    };
2213 2213

	
2214 2214
    typedef typename ItemSetTraits<DGR, Node>::ItemNotifier NodeNotifier;
2215 2215
    NodeNotifier& notifier(Node) const { return _digraph->notifier(Node()); }
2216 2216

	
2217 2217
    typedef typename ItemSetTraits<DGR, Edge>::ItemNotifier EdgeNotifier;
2218 2218
    EdgeNotifier& notifier(Edge) const { return _digraph->notifier(Edge()); }
2219
    
2219

	
2220 2220
    typedef EdgeNotifier ArcNotifier;
2221 2221
    ArcNotifier& notifier(Arc) const { return _digraph->notifier(Edge()); }
2222 2222

	
2223 2223
  protected:
2224 2224

	
2225 2225
    UndirectorBase() : _digraph(0) {}
2226 2226

	
2227 2227
    DGR* _digraph;
2228 2228

	
2229 2229
    void initialize(DGR& digraph) {
2230 2230
      _digraph = &digraph;
2231 2231
    }
2232 2232

	
2233 2233
  };
2234 2234

	
2235 2235
  /// \ingroup graph_adaptors
2236 2236
  ///
2237 2237
  /// \brief Adaptor class for viewing a digraph as an undirected graph.
2238 2238
  ///
2239 2239
  /// Undirector adaptor can be used for viewing a digraph as an undirected
2240 2240
  /// graph. All arcs of the underlying digraph are showed in the
2241 2241
  /// adaptor as an edge (and also as a pair of arcs, of course).
2242 2242
  /// This adaptor conforms to the \ref concepts::Graph "Graph" concept.
2243 2243
  ///
2244 2244
  /// The adapted digraph can also be modified through this adaptor
2245 2245
  /// by adding or removing nodes or edges, unless the \c GR template
2246 2246
  /// parameter is set to be \c const.
2247 2247
  ///
2248 2248
  /// This class provides item counting in the same time as the adapted
2249 2249
  /// digraph structure.
2250 2250
  ///
2251 2251
  /// \tparam DGR The type of the adapted digraph.
2252 2252
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
2253 2253
  /// It can also be specified to be \c const.
2254 2254
  ///
2255 2255
  /// \note The \c Node type of this adaptor and the adapted digraph are
2256 2256
  /// convertible to each other, moreover the \c Edge type of the adaptor
2257 2257
  /// and the \c Arc type of the adapted digraph are also convertible to
2258 2258
  /// each other.
2259 2259
  /// (Thus the \c Arc type of the adaptor is convertible to the \c Arc type
2260 2260
  /// of the adapted digraph.)
2261 2261
  template<typename DGR>
2262 2262
#ifdef DOXYGEN
2263 2263
  class Undirector {
2264 2264
#else
2265 2265
  class Undirector :
2266 2266
    public GraphAdaptorExtender<UndirectorBase<DGR> > {
2267 2267
#endif
... ...
@@ -2683,236 +2683,236 @@
2683 2683
  /// flow and circulation problems.
2684 2684
  ///
2685 2685
  /// ResidualDigraph can be used for composing the \e residual digraph
2686 2686
  /// for directed flow and circulation problems. Let \f$ G=(V, A) \f$
2687 2687
  /// be a directed graph and let \f$ F \f$ be a number type.
2688 2688
  /// Let \f$ flow, cap: A\to F \f$ be functions on the arcs.
2689 2689
  /// This adaptor implements a digraph structure with node set \f$ V \f$
2690 2690
  /// and arc set \f$ A_{forward}\cup A_{backward} \f$,
2691 2691
  /// where \f$ A_{forward}=\{uv : uv\in A, flow(uv)<cap(uv)\} \f$ and
2692 2692
  /// \f$ A_{backward}=\{vu : uv\in A, flow(uv)>0\} \f$, i.e. the so
2693 2693
  /// called residual digraph.
2694 2694
  /// When the union \f$ A_{forward}\cup A_{backward} \f$ is taken,
2695 2695
  /// multiplicities are counted, i.e. the adaptor has exactly
2696 2696
  /// \f$ |A_{forward}| + |A_{backward}|\f$ arcs (it may have parallel
2697 2697
  /// arcs).
2698 2698
  /// This class conforms to the \ref concepts::Digraph "Digraph" concept.
2699 2699
  ///
2700 2700
  /// This class provides only linear time counting for nodes and arcs.
2701 2701
  ///
2702 2702
  /// \tparam DGR The type of the adapted digraph.
2703 2703
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
2704 2704
  /// It is implicitly \c const.
2705 2705
  /// \tparam CM The type of the capacity map.
2706 2706
  /// It must be an arc map of some numerical type, which defines
2707 2707
  /// the capacities in the flow problem. It is implicitly \c const.
2708 2708
  /// The default type is
2709 2709
  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
2710 2710
  /// \tparam FM The type of the flow map.
2711 2711
  /// It must be an arc map of some numerical type, which defines
2712 2712
  /// the flow values in the flow problem. The default type is \c CM.
2713 2713
  /// \tparam TL The tolerance type for handling inexact computation.
2714 2714
  /// The default tolerance type depends on the value type of the
2715 2715
  /// capacity map.
2716 2716
  ///
2717 2717
  /// \note This adaptor is implemented using Undirector and FilterArcs
2718 2718
  /// adaptors.
2719 2719
  ///
2720 2720
  /// \note The \c Node type of this adaptor and the adapted digraph are
2721 2721
  /// convertible to each other, moreover the \c Arc type of the adaptor
2722 2722
  /// is convertible to the \c Arc type of the adapted digraph.
2723 2723
#ifdef DOXYGEN
2724 2724
  template<typename DGR, typename CM, typename FM, typename TL>
2725 2725
  class ResidualDigraph
2726 2726
#else
2727 2727
  template<typename DGR,
2728 2728
           typename CM = typename DGR::template ArcMap<int>,
2729 2729
           typename FM = CM,
2730 2730
           typename TL = Tolerance<typename CM::Value> >
2731
  class ResidualDigraph 
2731
  class ResidualDigraph
2732 2732
    : public SubDigraph<
2733 2733
        Undirector<const DGR>,
2734 2734
        ConstMap<typename DGR::Node, Const<bool, true> >,
2735 2735
        typename Undirector<const DGR>::template CombinedArcMap<
2736 2736
          _adaptor_bits::ResForwardFilter<const DGR, CM, FM, TL>,
2737 2737
          _adaptor_bits::ResBackwardFilter<const DGR, CM, FM, TL> > >
2738 2738
#endif
2739 2739
  {
2740 2740
  public:
2741 2741

	
2742 2742
    /// The type of the underlying digraph.
2743 2743
    typedef DGR Digraph;
2744 2744
    /// The type of the capacity map.
2745 2745
    typedef CM CapacityMap;
2746 2746
    /// The type of the flow map.
2747 2747
    typedef FM FlowMap;
2748 2748
    /// The tolerance type.
2749 2749
    typedef TL Tolerance;
2750 2750

	
2751 2751
    typedef typename CapacityMap::Value Value;
2752 2752
    typedef ResidualDigraph Adaptor;
2753 2753

	
2754 2754
  protected:
2755 2755

	
2756 2756
    typedef Undirector<const Digraph> Undirected;
2757 2757

	
2758 2758
    typedef ConstMap<typename DGR::Node, Const<bool, true> > NodeFilter;
2759 2759

	
2760 2760
    typedef _adaptor_bits::ResForwardFilter<const DGR, CM,
2761 2761
                                            FM, TL> ForwardFilter;
2762 2762

	
2763 2763
    typedef _adaptor_bits::ResBackwardFilter<const DGR, CM,
2764 2764
                                             FM, TL> BackwardFilter;
2765 2765

	
2766 2766
    typedef typename Undirected::
2767 2767
      template CombinedArcMap<ForwardFilter, BackwardFilter> ArcFilter;
2768 2768

	
2769 2769
    typedef SubDigraph<Undirected, NodeFilter, ArcFilter> Parent;
2770 2770

	
2771 2771
    const CapacityMap* _capacity;
2772 2772
    FlowMap* _flow;
2773 2773

	
2774 2774
    Undirected _graph;
2775 2775
    NodeFilter _node_filter;
2776 2776
    ForwardFilter _forward_filter;
2777 2777
    BackwardFilter _backward_filter;
2778 2778
    ArcFilter _arc_filter;
2779 2779

	
2780 2780
  public:
2781 2781

	
2782 2782
    /// \brief Constructor
2783 2783
    ///
2784 2784
    /// Constructor of the residual digraph adaptor. The parameters are the
2785 2785
    /// digraph, the capacity map, the flow map, and a tolerance object.
2786 2786
    ResidualDigraph(const DGR& digraph, const CM& capacity,
2787 2787
                    FM& flow, const TL& tolerance = Tolerance())
2788
      : Parent(), _capacity(&capacity), _flow(&flow), 
2788
      : Parent(), _capacity(&capacity), _flow(&flow),
2789 2789
        _graph(digraph), _node_filter(),
2790 2790
        _forward_filter(capacity, flow, tolerance),
2791 2791
        _backward_filter(capacity, flow, tolerance),
2792 2792
        _arc_filter(_forward_filter, _backward_filter)
2793 2793
    {
2794 2794
      Parent::initialize(_graph, _node_filter, _arc_filter);
2795 2795
    }
2796 2796

	
2797 2797
    typedef typename Parent::Arc Arc;
2798 2798

	
2799 2799
    /// \brief Returns the residual capacity of the given arc.
2800 2800
    ///
2801 2801
    /// Returns the residual capacity of the given arc.
2802 2802
    Value residualCapacity(const Arc& a) const {
2803 2803
      if (Undirected::direction(a)) {
2804 2804
        return (*_capacity)[a] - (*_flow)[a];
2805 2805
      } else {
2806 2806
        return (*_flow)[a];
2807 2807
      }
2808 2808
    }
2809 2809

	
2810 2810
    /// \brief Augments on the given arc in the residual digraph.
2811 2811
    ///
2812 2812
    /// Augments on the given arc in the residual digraph. It increases
2813 2813
    /// or decreases the flow value on the original arc according to the
2814 2814
    /// direction of the residual arc.
2815 2815
    void augment(const Arc& a, const Value& v) const {
2816 2816
      if (Undirected::direction(a)) {
2817 2817
        _flow->set(a, (*_flow)[a] + v);
2818 2818
      } else {
2819 2819
        _flow->set(a, (*_flow)[a] - v);
2820 2820
      }
2821 2821
    }
2822 2822

	
2823 2823
    /// \brief Returns \c true if the given residual arc is a forward arc.
2824 2824
    ///
2825 2825
    /// Returns \c true if the given residual arc has the same orientation
2826 2826
    /// as the original arc, i.e. it is a so called forward arc.
2827 2827
    static bool forward(const Arc& a) {
2828 2828
      return Undirected::direction(a);
2829 2829
    }
2830 2830

	
2831 2831
    /// \brief Returns \c true if the given residual arc is a backward arc.
2832 2832
    ///
2833 2833
    /// Returns \c true if the given residual arc has the opposite orientation
2834 2834
    /// than the original arc, i.e. it is a so called backward arc.
2835 2835
    static bool backward(const Arc& a) {
2836 2836
      return !Undirected::direction(a);
2837 2837
    }
2838 2838

	
2839 2839
    /// \brief Returns the forward oriented residual arc.
2840 2840
    ///
2841 2841
    /// Returns the forward oriented residual arc related to the given
2842 2842
    /// arc of the underlying digraph.
2843 2843
    static Arc forward(const typename Digraph::Arc& a) {
2844 2844
      return Undirected::direct(a, true);
2845 2845
    }
2846 2846

	
2847 2847
    /// \brief Returns the backward oriented residual arc.
2848 2848
    ///
2849 2849
    /// Returns the backward oriented residual arc related to the given
2850 2850
    /// arc of the underlying digraph.
2851 2851
    static Arc backward(const typename Digraph::Arc& a) {
2852 2852
      return Undirected::direct(a, false);
2853 2853
    }
2854 2854

	
2855 2855
    /// \brief Residual capacity map.
2856 2856
    ///
2857 2857
    /// This map adaptor class can be used for obtaining the residual
2858 2858
    /// capacities as an arc map of the residual digraph.
2859 2859
    /// Its value type is inherited from the capacity map.
2860 2860
    class ResidualCapacity {
2861 2861
    protected:
2862 2862
      const Adaptor* _adaptor;
2863 2863
    public:
2864 2864
      /// The key type of the map
2865 2865
      typedef Arc Key;
2866 2866
      /// The value type of the map
2867 2867
      typedef typename CapacityMap::Value Value;
2868 2868

	
2869 2869
      /// Constructor
2870
      ResidualCapacity(const ResidualDigraph<DGR, CM, FM, TL>& adaptor) 
2870
      ResidualCapacity(const ResidualDigraph<DGR, CM, FM, TL>& adaptor)
2871 2871
        : _adaptor(&adaptor) {}
2872 2872

	
2873 2873
      /// Returns the value associated with the given residual arc
2874 2874
      Value operator[](const Arc& a) const {
2875 2875
        return _adaptor->residualCapacity(a);
2876 2876
      }
2877 2877

	
2878 2878
    };
2879 2879

	
2880 2880
    /// \brief Returns a residual capacity map
2881 2881
    ///
2882 2882
    /// This function just returns a residual capacity map.
2883 2883
    ResidualCapacity residualCapacity() const {
2884 2884
      return ResidualCapacity(*this);
2885 2885
    }
2886 2886

	
2887 2887
  };
2888 2888

	
2889 2889
  /// \brief Returns a (read-only) Residual adaptor
2890 2890
  ///
2891 2891
  /// This function just returns a (read-only) \ref ResidualDigraph adaptor.
2892 2892
  /// \ingroup graph_adaptors
2893 2893
  /// \relates ResidualDigraph
2894 2894
    template<typename DGR, typename CM, typename FM>
2895 2895
  ResidualDigraph<DGR, CM, FM>
2896 2896
  residualDigraph(const DGR& digraph, const CM& capacity_map, FM& flow_map) {
2897 2897
    return ResidualDigraph<DGR, CM, FM> (digraph, capacity_map, flow_map);
2898 2898
  }
2899 2899

	
2900 2900

	
2901 2901
  template <typename DGR>
2902 2902
  class SplitNodesBase {
2903 2903
    typedef DigraphAdaptorBase<const DGR> Parent;
2904 2904

	
2905 2905
  public:
2906 2906

	
2907 2907
    typedef DGR Digraph;
2908 2908
    typedef SplitNodesBase Adaptor;
2909 2909

	
2910 2910
    typedef typename DGR::Node DigraphNode;
2911 2911
    typedef typename DGR::Arc DigraphArc;
2912 2912

	
2913 2913
    class Node;
2914 2914
    class Arc;
2915 2915

	
2916 2916
  private:
2917 2917

	
2918 2918
    template <typename T> class NodeMapBase;
... ...
@@ -3402,97 +3402,97 @@
3402 3402
      return Parent::origArc(a);
3403 3403
    }
3404 3404

	
3405 3405
    /// \brief Returns \c true if the given arc is a bind arc.
3406 3406
    ///
3407 3407
    /// Returns \c true if the given arc is a bind arc, i.e. it connects
3408 3408
    /// an in-node and an out-node.
3409 3409
    static bool bindArc(const Arc& a) {
3410 3410
      return Parent::bindArc(a);
3411 3411
    }
3412 3412

	
3413 3413
    /// \brief Returns the in-node created from the given original node.
3414 3414
    ///
3415 3415
    /// Returns the in-node created from the given original node.
3416 3416
    static Node inNode(const DigraphNode& n) {
3417 3417
      return Parent::inNode(n);
3418 3418
    }
3419 3419

	
3420 3420
    /// \brief Returns the out-node created from the given original node.
3421 3421
    ///
3422 3422
    /// Returns the out-node created from the given original node.
3423 3423
    static Node outNode(const DigraphNode& n) {
3424 3424
      return Parent::outNode(n);
3425 3425
    }
3426 3426

	
3427 3427
    /// \brief Returns the bind arc that corresponds to the given
3428 3428
    /// original node.
3429 3429
    ///
3430 3430
    /// Returns the bind arc in the adaptor that corresponds to the given
3431 3431
    /// original node, i.e. the arc connecting the in-node and out-node
3432 3432
    /// of \c n.
3433 3433
    static Arc arc(const DigraphNode& n) {
3434 3434
      return Parent::arc(n);
3435 3435
    }
3436 3436

	
3437 3437
    /// \brief Returns the arc that corresponds to the given original arc.
3438 3438
    ///
3439 3439
    /// Returns the arc in the adaptor that corresponds to the given
3440 3440
    /// original arc.
3441 3441
    static Arc arc(const DigraphArc& a) {
3442 3442
      return Parent::arc(a);
3443 3443
    }
3444 3444

	
3445 3445
    /// \brief Node map combined from two original node maps
3446 3446
    ///
3447 3447
    /// This map adaptor class adapts two node maps of the original digraph
3448 3448
    /// to get a node map of the split digraph.
3449 3449
    /// Its value type is inherited from the first node map type (\c IN).
3450
    /// \tparam IN The type of the node map for the in-nodes. 
3450
    /// \tparam IN The type of the node map for the in-nodes.
3451 3451
    /// \tparam OUT The type of the node map for the out-nodes.
3452 3452
    template <typename IN, typename OUT>
3453 3453
    class CombinedNodeMap {
3454 3454
    public:
3455 3455

	
3456 3456
      /// The key type of the map
3457 3457
      typedef Node Key;
3458 3458
      /// The value type of the map
3459 3459
      typedef typename IN::Value Value;
3460 3460

	
3461 3461
      typedef typename MapTraits<IN>::ReferenceMapTag ReferenceMapTag;
3462 3462
      typedef typename MapTraits<IN>::ReturnValue ReturnValue;
3463 3463
      typedef typename MapTraits<IN>::ConstReturnValue ConstReturnValue;
3464 3464
      typedef typename MapTraits<IN>::ReturnValue Reference;
3465 3465
      typedef typename MapTraits<IN>::ConstReturnValue ConstReference;
3466 3466

	
3467 3467
      /// Constructor
3468 3468
      CombinedNodeMap(IN& in_map, OUT& out_map)
3469 3469
        : _in_map(in_map), _out_map(out_map) {}
3470 3470

	
3471 3471
      /// Returns the value associated with the given key.
3472 3472
      Value operator[](const Key& key) const {
3473 3473
        if (SplitNodesBase<const DGR>::inNode(key)) {
3474 3474
          return _in_map[key];
3475 3475
        } else {
3476 3476
          return _out_map[key];
3477 3477
        }
3478 3478
      }
3479 3479

	
3480 3480
      /// Returns a reference to the value associated with the given key.
3481 3481
      Value& operator[](const Key& key) {
3482 3482
        if (SplitNodesBase<const DGR>::inNode(key)) {
3483 3483
          return _in_map[key];
3484 3484
        } else {
3485 3485
          return _out_map[key];
3486 3486
        }
3487 3487
      }
3488 3488

	
3489 3489
      /// Sets the value associated with the given key.
3490 3490
      void set(const Key& key, const Value& value) {
3491 3491
        if (SplitNodesBase<const DGR>::inNode(key)) {
3492 3492
          _in_map.set(key, value);
3493 3493
        } else {
3494 3494
          _out_map.set(key, value);
3495 3495
        }
3496 3496
      }
3497 3497

	
3498 3498
    private:
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
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::_terminate(ArgParserException::Reason reason) const
24 24
  {
25 25
    if(_exit_on_problems)
26 26
      exit(1);
27 27
    else throw(ArgParserException(reason));
28 28
  }
29
  
30
  
29

	
30

	
31 31
  void ArgParser::_showHelp(void *p)
32 32
  {
33 33
    (static_cast<ArgParser*>(p))->showHelp();
34 34
    (static_cast<ArgParser*>(p))->_terminate(ArgParserException::HELP);
35 35
  }
36 36

	
37 37
  ArgParser::ArgParser(int argc, const char * const *argv)
38 38
    :_argc(argc), _argv(argv), _command_name(argv[0]),
39 39
    _exit_on_problems(true) {
40 40
    funcOption("-help","Print a short help message",_showHelp,this);
41 41
    synonym("help","-help");
42 42
    synonym("h","-help");
43 43
  }
44 44

	
45 45
  ArgParser::~ArgParser()
46 46
  {
47 47
    for(Opts::iterator i=_opts.begin();i!=_opts.end();++i)
48 48
      if(i->second.self_delete)
49 49
        switch(i->second.type) {
50 50
        case BOOL:
51 51
          delete i->second.bool_p;
52 52
          break;
53 53
        case STRING:
54 54
          delete i->second.string_p;
55 55
          break;
56 56
        case DOUBLE:
57 57
          delete i->second.double_p;
58 58
          break;
59 59
        case INTEGER:
60 60
          delete i->second.int_p;
61 61
          break;
62 62
        case UNKNOWN:
63 63
          break;
64 64
        case FUNC:
65 65
          break;
66 66
        }
67 67
  }
68 68

	
69 69

	
70 70
  ArgParser &ArgParser::intOption(const std::string &name,
71 71
                               const std::string &help,
72 72
                               int value, bool obl)
73 73
  {
74 74
    ParData p;
75 75
    p.int_p=new int(value);
76 76
    p.self_delete=true;
77 77
    p.help=help;
78 78
    p.type=INTEGER;
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
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_ARG_PARSER_H
20 20
#define LEMON_ARG_PARSER_H
21 21

	
22 22
#include <vector>
23 23
#include <map>
24 24
#include <list>
25 25
#include <string>
26 26
#include <iostream>
27 27
#include <sstream>
28 28
#include <algorithm>
29 29
#include <lemon/assert.h>
30 30

	
31 31
///\ingroup misc
32 32
///\file
33 33
///\brief A tool to parse command line arguments.
34 34

	
35 35
namespace lemon {
36 36

	
37 37
  ///Exception used by ArgParser
38 38
  class ArgParserException : public Exception {
39 39
  public:
40 40
    enum Reason {
41 41
      HELP,         /// <tt>--help</tt> option was given
42 42
      UNKNOWN_OPT,  /// Unknown option was given
43 43
      INVALID_OPT   /// Invalid combination of options
44 44
    };
45
    
45

	
46 46
  private:
47 47
    Reason _reason;
48
    
48

	
49 49
  public:
50 50
    ///Constructor
51 51
    ArgParserException(Reason r) throw() : _reason(r) {}
52 52
    ///Virtual destructor
53 53
    virtual ~ArgParserException() throw() {}
54 54
    ///A short description of the exception
55 55
    virtual const char* what() const throw() {
56 56
      switch(_reason)
57 57
        {
58 58
        case HELP:
59 59
          return "lemon::ArgParseException: ask for help";
60 60
          break;
61 61
        case UNKNOWN_OPT:
62 62
          return "lemon::ArgParseException: unknown option";
63 63
          break;
64 64
        case INVALID_OPT:
65 65
          return "lemon::ArgParseException: invalid combination of options";
66 66
          break;
67 67
        }
68 68
      return "";
69 69
    }
70 70
    ///Return the reason for the failure
71 71
    Reason reason() const {return _reason; }
72 72
  };
73 73

	
74 74

	
75 75
  ///Command line arguments parser
76 76

	
77 77
  ///\ingroup misc
78 78
  ///Command line arguments parser.
79 79
  ///
80 80
  ///For a complete example see the \ref arg_parser_demo.cc demo file.
81 81
  class ArgParser {
82 82

	
83 83
    static void _showHelp(void *p);
84 84
  protected:
85 85

	
86 86
    int _argc;
87 87
    const char * const *_argv;
88 88

	
89 89
    enum OptType { UNKNOWN=0, BOOL=1, STRING=2, DOUBLE=3, INTEGER=4, FUNC=5 };
90 90

	
91 91
    class ParData {
92 92
    public:
93 93
      union {
94 94
        bool *bool_p;
95 95
        int *int_p;
96 96
        double *double_p;
97 97
        std::string *string_p;
98 98
        struct {
99 99
          void (*p)(void *);
100 100
          void *data;
101 101
        } func_p;
102 102

	
103 103
      };
104 104
      std::string help;
105 105
      bool mandatory;
106 106
      OptType type;
107 107
      bool set;
108 108
      bool ingroup;
109 109
      bool has_syn;
110 110
      bool syn;
111 111
      bool self_delete;
112 112
      ParData() : mandatory(false), type(UNKNOWN), set(false), ingroup(false),
113 113
                  has_syn(false), syn(false), self_delete(false) {}
114 114
    };
115 115

	
116 116
    typedef std::map<std::string,ParData> Opts;
117 117
    Opts _opts;
118 118

	
119 119
    class GroupData
120 120
    {
121 121
    public:
122 122
      typedef std::list<std::string> Opts;
123 123
      Opts opts;
124 124
      bool only_one;
125 125
      bool mandatory;
126 126
      GroupData() :only_one(false), mandatory(false) {}
127 127
    };
128 128

	
129 129
    typedef std::map<std::string,GroupData> Groups;
130 130
    Groups _groups;
131 131

	
132 132
    struct OtherArg
133 133
    {
134 134
      std::string name;
135 135
      std::string help;
136 136
      OtherArg(std::string n, std::string h) :name(n), help(h) {}
137 137

	
138 138
    };
139 139

	
140 140
    std::vector<OtherArg> _others_help;
141 141
    std::vector<std::string> _file_args;
142 142
    std::string _command_name;
143 143

	
144
    
144

	
145 145
  private:
146 146
    //Bind a function to an option.
147 147

	
148 148
    //\param name The name of the option. The leading '-' must be omitted.
149 149
    //\param help A help string.
150 150
    //\retval func The function to be called when the option is given. It
151 151
    //  must be of type "void f(void *)"
152 152
    //\param data Data to be passed to \c func
153 153
    ArgParser &funcOption(const std::string &name,
154 154
                    const std::string &help,
155 155
                    void (*func)(void *),void *data);
156 156

	
157 157
    bool _exit_on_problems;
158
    
158

	
159 159
    void _terminate(ArgParserException::Reason reason) const;
160 160

	
161 161
  public:
162 162

	
163 163
    ///Constructor
164 164
    ArgParser(int argc, const char * const *argv);
165 165

	
166 166
    ~ArgParser();
167 167

	
168 168
    ///\name Options
169 169
    ///
170 170

	
171 171
    ///@{
172 172

	
173 173
    ///Add a new integer type option
174 174

	
175 175
    ///Add a new integer type option.
176 176
    ///\param name The name of the option. The leading '-' must be omitted.
177 177
    ///\param help A help string.
178 178
    ///\param value A default value for the option.
179 179
    ///\param obl Indicate if the option is mandatory.
180 180
    ArgParser &intOption(const std::string &name,
181 181
                    const std::string &help,
182 182
                    int value=0, bool obl=false);
183 183

	
184 184
    ///Add a new floating point type option
185 185

	
186 186
    ///Add a new floating point type option.
187 187
    ///\param name The name of the option. The leading '-' must be omitted.
188 188
    ///\param help A help string.
189 189
    ///\param value A default value for the option.
190 190
    ///\param obl Indicate if the option is mandatory.
191 191
    ArgParser &doubleOption(const std::string &name,
192 192
                      const std::string &help,
193 193
                      double value=0, bool obl=false);
194 194

	
195 195
    ///Add a new bool type option
196 196

	
197 197
    ///Add a new bool type option.
198 198
    ///\param name The name of the option. The leading '-' must be omitted.
199 199
    ///\param help A help string.
200 200
    ///\param value A default value for the option.
201 201
    ///\param obl Indicate if the option is mandatory.
202 202
    ///\note A mandatory bool obtion is of very little use.
203 203
    ArgParser &boolOption(const std::string &name,
204 204
                      const std::string &help,
205 205
                      bool value=false, bool obl=false);
206 206

	
... ...
@@ -378,56 +378,56 @@
378 378
        Opts::const_iterator i = _parser._opts.find(_name);
379 379
        LEMON_ASSERT(i!=_parser._opts.end(),
380 380
                     std::string()+"Unkown option: '"+_name+"'");
381 381
        LEMON_ASSERT(i->second.type==ArgParser::STRING,
382 382
                     std::string()+"'"+_name+"' is a string option");
383 383
        return *(i->second.string_p);
384 384
      }
385 385
      ///\e
386 386
      operator double()
387 387
      {
388 388
        Opts::const_iterator i = _parser._opts.find(_name);
389 389
        LEMON_ASSERT(i!=_parser._opts.end(),
390 390
                     std::string()+"Unkown option: '"+_name+"'");
391 391
        LEMON_ASSERT(i->second.type==ArgParser::DOUBLE ||
392 392
                     i->second.type==ArgParser::INTEGER,
393 393
                     std::string()+"'"+_name+"' is a floating point option");
394 394
        return i->second.type==ArgParser::DOUBLE ?
395 395
          *(i->second.double_p) : *(i->second.int_p);
396 396
      }
397 397
      ///\e
398 398
      operator int()
399 399
      {
400 400
        Opts::const_iterator i = _parser._opts.find(_name);
401 401
        LEMON_ASSERT(i!=_parser._opts.end(),
402 402
                     std::string()+"Unkown option: '"+_name+"'");
403 403
        LEMON_ASSERT(i->second.type==ArgParser::INTEGER,
404 404
                     std::string()+"'"+_name+"' is an integer option");
405 405
        return *(i->second.int_p);
406 406
      }
407 407

	
408 408
    };
409 409

	
410 410
    ///Give back the value of an option
411 411

	
412 412
    ///Give back the value of an option.
413 413
    ///\sa RefType
414 414
    RefType operator[](const std::string &n) const
415 415
    {
416 416
      return RefType(*this, n);
417 417
    }
418 418

	
419 419
    ///Give back the non-option type arguments.
420 420

	
421 421
    ///Give back a reference to a vector consisting of the program arguments
422 422
    ///not starting with a '-' character.
423 423
    const std::vector<std::string> &files() const { return _file_args; }
424 424

	
425 425
    ///Throw instead of exit in case of problems
426
    void throwOnProblems() 
426
    void throwOnProblems()
427 427
    {
428 428
      _exit_on_problems=false;
429 429
    }
430 430
  };
431 431
}
432 432

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

	
19 19
#ifndef LEMON_BELLMAN_FORD_H
20 20
#define LEMON_BELLMAN_FORD_H
21 21

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

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

	
34 34
#include <limits>
35 35

	
36 36
namespace lemon {
37 37

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

	
72 72
  template <typename V>
73 73
  struct BellmanFordDefaultOperationTraits<V, false> {
74 74
    typedef V Value;
75 75
    static Value zero() {
76 76
      return static_cast<Value>(0);
77 77
    }
78 78
    static Value infinity() {
79 79
      return std::numeric_limits<Value>::max();
80 80
    }
81 81
    static Value plus(const Value& left, const Value& right) {
82 82
      if (left == infinity() || right == infinity()) return infinity();
83 83
      return left + right;
84 84
    }
85 85
    static bool less(const Value& left, const Value& right) {
86 86
      return left < right;
87 87
    }
88 88
  };
89
  
89

	
90 90
  /// \brief Operation traits for the BellmanFord algorithm class
91 91
  /// using tolerance.
92 92
  ///
93 93
  /// This operation traits class defines all computational operations
94 94
  /// and constants that are used in the Bellman-Ford algorithm.
95 95
  /// The only difference between this implementation and
96 96
  /// \ref BellmanFordDefaultOperationTraits is that this class uses
97 97
  /// the \ref Tolerance "tolerance technique" in its \ref less()
98 98
  /// function.
99 99
  ///
100 100
  /// \tparam V The value type.
101 101
  /// \tparam eps The epsilon value for the \ref less() function.
102 102
  /// By default, it is the epsilon value used by \ref Tolerance
103 103
  /// "Tolerance<V>".
104 104
  ///
105 105
  /// \see BellmanFordDefaultOperationTraits
106 106
#ifdef DOXYGEN
107 107
  template <typename V, V eps>
108 108
#else
109 109
  template <
110 110
    typename V,
111 111
    V eps = Tolerance<V>::def_epsilon>
112 112
#endif
113 113
  struct BellmanFordToleranceOperationTraits {
114 114
    /// \brief Value type for the algorithm.
115 115
    typedef V Value;
116 116
    /// \brief Gives back the zero value of the type.
117 117
    static Value zero() {
118 118
      return static_cast<Value>(0);
119 119
    }
120 120
    /// \brief Gives back the positive infinity value of the type.
121 121
    static Value infinity() {
122 122
      return std::numeric_limits<Value>::infinity();
123 123
    }
124 124
    /// \brief Gives back the sum of the given two elements.
125 125
    static Value plus(const Value& left, const Value& right) {
126 126
      return left + right;
127 127
    }
128 128
    /// \brief Gives back \c true only if the first value is less than
129 129
    /// the second.
130 130
    static bool less(const Value& left, const Value& right) {
131 131
      return left + eps < right;
132 132
    }
133 133
  };
134 134

	
135 135
  /// \brief Default traits class of BellmanFord class.
136 136
  ///
137 137
  /// Default traits class of BellmanFord class.
138 138
  /// \param GR The type of the digraph.
139 139
  /// \param LEN The type of the length map.
140 140
  template<typename GR, typename LEN>
141 141
  struct BellmanFordDefaultTraits {
142
    /// The type of the digraph the algorithm runs on. 
142
    /// The type of the digraph the algorithm runs on.
143 143
    typedef GR Digraph;
144 144

	
145 145
    /// \brief The type of the map that stores the arc lengths.
146 146
    ///
147 147
    /// The type of the map that stores the arc lengths.
148 148
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
149 149
    typedef LEN LengthMap;
150 150

	
151 151
    /// The type of the arc lengths.
152 152
    typedef typename LEN::Value Value;
153 153

	
154 154
    /// \brief Operation traits for Bellman-Ford algorithm.
155 155
    ///
156 156
    /// It defines the used operations and the infinity value for the
157 157
    /// given \c Value type.
158 158
    /// \see BellmanFordDefaultOperationTraits,
159 159
    /// BellmanFordToleranceOperationTraits
160 160
    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
161
 
162
    /// \brief The type of the map that stores the last arcs of the 
161

	
162
    /// \brief The type of the map that stores the last arcs of the
163 163
    /// shortest paths.
164
    /// 
164
    ///
165 165
    /// The type of the map that stores the last
166 166
    /// arcs of the shortest paths.
167 167
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
168 168
    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
169 169

	
170 170
    /// \brief Instantiates a \c PredMap.
171
    /// 
172
    /// This function instantiates a \ref PredMap. 
171
    ///
172
    /// This function instantiates a \ref PredMap.
173 173
    /// \param g is the digraph to which we would like to define the
174 174
    /// \ref PredMap.
175 175
    static PredMap *createPredMap(const GR& g) {
176 176
      return new PredMap(g);
177 177
    }
178 178

	
179 179
    /// \brief The type of the map that stores the distances of the nodes.
180 180
    ///
181 181
    /// The type of the map that stores the distances of the nodes.
182 182
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
183 183
    typedef typename GR::template NodeMap<typename LEN::Value> DistMap;
184 184

	
185 185
    /// \brief Instantiates a \c DistMap.
186 186
    ///
187
    /// This function instantiates a \ref DistMap. 
188
    /// \param g is the digraph to which we would like to define the 
187
    /// This function instantiates a \ref DistMap.
188
    /// \param g is the digraph to which we would like to define the
189 189
    /// \ref DistMap.
190 190
    static DistMap *createDistMap(const GR& g) {
191 191
      return new DistMap(g);
192 192
    }
193 193

	
194 194
  };
195
  
195

	
196 196
  /// \brief %BellmanFord algorithm class.
197 197
  ///
198 198
  /// \ingroup shortest_path
199
  /// This class provides an efficient implementation of the Bellman-Ford 
199
  /// This class provides an efficient implementation of the Bellman-Ford
200 200
  /// algorithm. The maximum time complexity of the algorithm is
201 201
  /// <tt>O(ne)</tt>.
202 202
  ///
203 203
  /// The Bellman-Ford algorithm solves the single-source shortest path
204 204
  /// problem when the arcs can have negative lengths, but the digraph
205 205
  /// should not contain directed cycles with negative total length.
206 206
  /// If all arc costs are non-negative, consider to use the Dijkstra
207 207
  /// algorithm instead, since it is more efficient.
208 208
  ///
209 209
  /// The arc lengths are passed to the algorithm using a
210
  /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any 
210
  /// \ref concepts::ReadMap "ReadMap", so it is easy to change it to any
211 211
  /// kind of length. The type of the length values is determined by the
212 212
  /// \ref concepts::ReadMap::Value "Value" type of the length map.
213 213
  ///
214 214
  /// There is also a \ref bellmanFord() "function-type interface" for the
215 215
  /// Bellman-Ford algorithm, which is convenient in the simplier cases and
216 216
  /// it can be used easier.
217 217
  ///
218 218
  /// \tparam GR The type of the digraph the algorithm runs on.
219 219
  /// The default type is \ref ListDigraph.
220 220
  /// \tparam LEN A \ref concepts::ReadMap "readable" arc map that specifies
221 221
  /// the lengths of the arcs. The default map type is
222 222
  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
223 223
  /// \tparam TR The traits class that defines various types used by the
224 224
  /// algorithm. By default, it is \ref BellmanFordDefaultTraits
225 225
  /// "BellmanFordDefaultTraits<GR, LEN>".
226 226
  /// In most cases, this parameter should not be set directly,
227 227
  /// consider to use the named template parameters instead.
228 228
#ifdef DOXYGEN
229 229
  template <typename GR, typename LEN, typename TR>
230 230
#else
231 231
  template <typename GR=ListDigraph,
232 232
            typename LEN=typename GR::template ArcMap<int>,
233 233
            typename TR=BellmanFordDefaultTraits<GR,LEN> >
234 234
#endif
235 235
  class BellmanFord {
236 236
  public:
237 237

	
238 238
    ///The type of the underlying digraph.
239 239
    typedef typename TR::Digraph Digraph;
240
    
240

	
241 241
    /// \brief The type of the arc lengths.
242 242
    typedef typename TR::LengthMap::Value Value;
243 243
    /// \brief The type of the map that stores the arc lengths.
244 244
    typedef typename TR::LengthMap LengthMap;
245 245
    /// \brief The type of the map that stores the last
246 246
    /// arcs of the shortest paths.
247 247
    typedef typename TR::PredMap PredMap;
248 248
    /// \brief The type of the map that stores the distances of the nodes.
249 249
    typedef typename TR::DistMap DistMap;
250 250
    /// The type of the paths.
251 251
    typedef PredMapPath<Digraph, PredMap> Path;
252 252
    ///\brief The \ref BellmanFordDefaultOperationTraits
253 253
    /// "operation traits class" of the algorithm.
254 254
    typedef typename TR::OperationTraits OperationTraits;
255 255

	
256 256
    ///The \ref BellmanFordDefaultTraits "traits class" of the algorithm.
257 257
    typedef TR Traits;
258 258

	
259 259
  private:
260 260

	
261 261
    typedef typename Digraph::Node Node;
262 262
    typedef typename Digraph::NodeIt NodeIt;
263 263
    typedef typename Digraph::Arc Arc;
264 264
    typedef typename Digraph::OutArcIt OutArcIt;
265 265

	
266 266
    // Pointer to the underlying digraph.
267 267
    const Digraph *_gr;
268 268
    // Pointer to the length map
269 269
    const LengthMap *_length;
270 270
    // Pointer to the map of predecessors arcs.
271 271
    PredMap *_pred;
272 272
    // Indicates if _pred is locally allocated (true) or not.
273 273
    bool _local_pred;
274 274
    // Pointer to the map of distances.
275 275
    DistMap *_dist;
276 276
    // Indicates if _dist is locally allocated (true) or not.
277 277
    bool _local_dist;
278 278

	
279 279
    typedef typename Digraph::template NodeMap<bool> MaskMap;
280 280
    MaskMap *_mask;
281 281

	
282 282
    std::vector<Node> _process;
283 283

	
284 284
    // Creates the maps if necessary.
285 285
    void create_maps() {
286 286
      if(!_pred) {
287
	_local_pred = true;
288
	_pred = Traits::createPredMap(*_gr);
287
        _local_pred = true;
288
        _pred = Traits::createPredMap(*_gr);
289 289
      }
290 290
      if(!_dist) {
291
	_local_dist = true;
292
	_dist = Traits::createDistMap(*_gr);
291
        _local_dist = true;
292
        _dist = Traits::createDistMap(*_gr);
293 293
      }
294 294
      if(!_mask) {
295 295
        _mask = new MaskMap(*_gr);
296 296
      }
297 297
    }
298
    
298

	
299 299
  public :
300
 
300

	
301 301
    typedef BellmanFord Create;
302 302

	
303 303
    /// \name Named Template Parameters
304 304

	
305 305
    ///@{
306 306

	
307 307
    template <class T>
308 308
    struct SetPredMapTraits : public Traits {
309 309
      typedef T PredMap;
310 310
      static PredMap *createPredMap(const Digraph&) {
311 311
        LEMON_ASSERT(false, "PredMap is not initialized");
312 312
        return 0; // ignore warnings
313 313
      }
314 314
    };
315 315

	
316 316
    /// \brief \ref named-templ-param "Named parameter" for setting
317 317
    /// \c PredMap type.
318 318
    ///
319 319
    /// \ref named-templ-param "Named parameter" for setting
320 320
    /// \c PredMap type.
321 321
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
322 322
    template <class T>
323
    struct SetPredMap 
323
    struct SetPredMap
324 324
      : public BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > {
325 325
      typedef BellmanFord< Digraph, LengthMap, SetPredMapTraits<T> > Create;
326 326
    };
327
    
327

	
328 328
    template <class T>
329 329
    struct SetDistMapTraits : public Traits {
330 330
      typedef T DistMap;
331 331
      static DistMap *createDistMap(const Digraph&) {
332 332
        LEMON_ASSERT(false, "DistMap is not initialized");
333 333
        return 0; // ignore warnings
334 334
      }
335 335
    };
336 336

	
337 337
    /// \brief \ref named-templ-param "Named parameter" for setting
338 338
    /// \c DistMap type.
339 339
    ///
340 340
    /// \ref named-templ-param "Named parameter" for setting
341 341
    /// \c DistMap type.
342 342
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
343 343
    template <class T>
344
    struct SetDistMap 
344
    struct SetDistMap
345 345
      : public BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > {
346 346
      typedef BellmanFord< Digraph, LengthMap, SetDistMapTraits<T> > Create;
347 347
    };
348 348

	
349 349
    template <class T>
350 350
    struct SetOperationTraitsTraits : public Traits {
351 351
      typedef T OperationTraits;
352 352
    };
353
    
354
    /// \brief \ref named-templ-param "Named parameter" for setting 
353

	
354
    /// \brief \ref named-templ-param "Named parameter" for setting
355 355
    /// \c OperationTraits type.
356 356
    ///
357 357
    /// \ref named-templ-param "Named parameter" for setting
358 358
    /// \c OperationTraits type.
359 359
    /// For more information, see \ref BellmanFordDefaultOperationTraits.
360 360
    template <class T>
361 361
    struct SetOperationTraits
362 362
      : public BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> > {
363 363
      typedef BellmanFord< Digraph, LengthMap, SetOperationTraitsTraits<T> >
364 364
      Create;
365 365
    };
366
    
366

	
367 367
    ///@}
368 368

	
369 369
  protected:
370
    
370

	
371 371
    BellmanFord() {}
372 372

	
373
  public:      
374
    
373
  public:
374

	
375 375
    /// \brief Constructor.
376 376
    ///
377 377
    /// Constructor.
378 378
    /// \param g The digraph the algorithm runs on.
379 379
    /// \param length The length map used by the algorithm.
380 380
    BellmanFord(const Digraph& g, const LengthMap& length) :
381 381
      _gr(&g), _length(&length),
382 382
      _pred(0), _local_pred(false),
383 383
      _dist(0), _local_dist(false), _mask(0) {}
384
    
384

	
385 385
    ///Destructor.
386 386
    ~BellmanFord() {
387 387
      if(_local_pred) delete _pred;
388 388
      if(_local_dist) delete _dist;
389 389
      if(_mask) delete _mask;
390 390
    }
391 391

	
392 392
    /// \brief Sets the length map.
393 393
    ///
394 394
    /// Sets the length map.
395 395
    /// \return <tt>(*this)</tt>
396 396
    BellmanFord &lengthMap(const LengthMap &map) {
397 397
      _length = &map;
398 398
      return *this;
399 399
    }
400 400

	
401 401
    /// \brief Sets the map that stores the predecessor arcs.
402 402
    ///
403 403
    /// Sets the map that stores the predecessor arcs.
404 404
    /// If you don't use this function before calling \ref run()
405 405
    /// or \ref init(), an instance will be allocated automatically.
406 406
    /// The destructor deallocates this automatically allocated map,
407 407
    /// of course.
408 408
    /// \return <tt>(*this)</tt>
409 409
    BellmanFord &predMap(PredMap &map) {
410 410
      if(_local_pred) {
411
	delete _pred;
412
	_local_pred=false;
411
        delete _pred;
412
        _local_pred=false;
413 413
      }
414 414
      _pred = &map;
415 415
      return *this;
416 416
    }
417 417

	
418 418
    /// \brief Sets the map that stores the distances of the nodes.
419 419
    ///
420 420
    /// Sets the map that stores the distances of the nodes calculated
421 421
    /// by the algorithm.
422 422
    /// If you don't use this function before calling \ref run()
423 423
    /// or \ref init(), an instance will be allocated automatically.
424 424
    /// The destructor deallocates this automatically allocated map,
425 425
    /// of course.
426 426
    /// \return <tt>(*this)</tt>
427 427
    BellmanFord &distMap(DistMap &map) {
428 428
      if(_local_dist) {
429
	delete _dist;
430
	_local_dist=false;
429
        delete _dist;
430
        _local_dist=false;
431 431
      }
432 432
      _dist = &map;
433 433
      return *this;
434 434
    }
435 435

	
436 436
    /// \name Execution Control
437 437
    /// The simplest way to execute the Bellman-Ford algorithm is to use
438 438
    /// one of the member functions called \ref run().\n
439 439
    /// If you need better control on the execution, you have to call
440 440
    /// \ref init() first, then you can add several source nodes
441 441
    /// with \ref addSource(). Finally the actual path computation can be
442 442
    /// performed with \ref start(), \ref checkedStart() or
443 443
    /// \ref limitedStart().
444 444

	
445 445
    ///@{
446 446

	
447 447
    /// \brief Initializes the internal data structures.
448
    /// 
448
    ///
449 449
    /// Initializes the internal data structures. The optional parameter
450 450
    /// is the initial distance of each node.
451 451
    void init(const Value value = OperationTraits::infinity()) {
452 452
      create_maps();
453 453
      for (NodeIt it(*_gr); it != INVALID; ++it) {
454
	_pred->set(it, INVALID);
455
	_dist->set(it, value);
454
        _pred->set(it, INVALID);
455
        _dist->set(it, value);
456 456
      }
457 457
      _process.clear();
458 458
      if (OperationTraits::less(value, OperationTraits::infinity())) {
459
	for (NodeIt it(*_gr); it != INVALID; ++it) {
460
	  _process.push_back(it);
461
	  _mask->set(it, true);
462
	}
459
        for (NodeIt it(*_gr); it != INVALID; ++it) {
460
          _process.push_back(it);
461
          _mask->set(it, true);
462
        }
463 463
      } else {
464
	for (NodeIt it(*_gr); it != INVALID; ++it) {
465
	  _mask->set(it, false);
466
	}
464
        for (NodeIt it(*_gr); it != INVALID; ++it) {
465
          _mask->set(it, false);
466
        }
467 467
      }
468 468
    }
469
    
469

	
470 470
    /// \brief Adds a new source node.
471 471
    ///
472 472
    /// This function adds a new source node. The optional second parameter
473 473
    /// is the initial distance of the node.
474 474
    void addSource(Node source, Value dst = OperationTraits::zero()) {
475 475
      _dist->set(source, dst);
476 476
      if (!(*_mask)[source]) {
477
	_process.push_back(source);
478
	_mask->set(source, true);
477
        _process.push_back(source);
478
        _mask->set(source, true);
479 479
      }
480 480
    }
481 481

	
482 482
    /// \brief Executes one round from the Bellman-Ford algorithm.
483 483
    ///
484 484
    /// If the algoritm calculated the distances in the previous round
485 485
    /// exactly for the paths of at most \c k arcs, then this function
486 486
    /// will calculate the distances exactly for the paths of at most
487 487
    /// <tt>k+1</tt> arcs. Performing \c k iterations using this function
488 488
    /// calculates the shortest path distances exactly for the paths
489 489
    /// consisting of at most \c k arcs.
490 490
    ///
491 491
    /// \warning The paths with limited arc number cannot be retrieved
492 492
    /// easily with \ref path() or \ref predArc() functions. If you also
493 493
    /// need the shortest paths and not only the distances, you should
494 494
    /// store the \ref predMap() "predecessor map" after each iteration
495 495
    /// and build the path manually.
496 496
    ///
497 497
    /// \return \c true when the algorithm have not found more shorter
498 498
    /// paths.
499 499
    ///
500 500
    /// \see ActiveIt
501 501
    bool processNextRound() {
502 502
      for (int i = 0; i < int(_process.size()); ++i) {
503
	_mask->set(_process[i], false);
503
        _mask->set(_process[i], false);
504 504
      }
505 505
      std::vector<Node> nextProcess;
506 506
      std::vector<Value> values(_process.size());
507 507
      for (int i = 0; i < int(_process.size()); ++i) {
508
	values[i] = (*_dist)[_process[i]];
508
        values[i] = (*_dist)[_process[i]];
509 509
      }
510 510
      for (int i = 0; i < int(_process.size()); ++i) {
511
	for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
512
	  Node target = _gr->target(it);
513
	  Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
514
	  if (OperationTraits::less(relaxed, (*_dist)[target])) {
515
	    _pred->set(target, it);
516
	    _dist->set(target, relaxed);
517
	    if (!(*_mask)[target]) {
518
	      _mask->set(target, true);
519
	      nextProcess.push_back(target);
520
	    }
521
	  }	  
522
	}
511
        for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
512
          Node target = _gr->target(it);
513
          Value relaxed = OperationTraits::plus(values[i], (*_length)[it]);
514
          if (OperationTraits::less(relaxed, (*_dist)[target])) {
515
            _pred->set(target, it);
516
            _dist->set(target, relaxed);
517
            if (!(*_mask)[target]) {
518
              _mask->set(target, true);
519
              nextProcess.push_back(target);
520
            }
521
          }
522
        }
523 523
      }
524 524
      _process.swap(nextProcess);
525 525
      return _process.empty();
526 526
    }
527 527

	
528 528
    /// \brief Executes one weak round from the Bellman-Ford algorithm.
529 529
    ///
530 530
    /// If the algorithm calculated the distances in the previous round
531 531
    /// at least for the paths of at most \c k arcs, then this function
532 532
    /// will calculate the distances at least for the paths of at most
533 533
    /// <tt>k+1</tt> arcs.
534 534
    /// This function does not make it possible to calculate the shortest
535 535
    /// path distances exactly for paths consisting of at most \c k arcs,
536 536
    /// this is why it is called weak round.
537 537
    ///
538 538
    /// \return \c true when the algorithm have not found more shorter
539 539
    /// paths.
540 540
    ///
541 541
    /// \see ActiveIt
542 542
    bool processNextWeakRound() {
543 543
      for (int i = 0; i < int(_process.size()); ++i) {
544
	_mask->set(_process[i], false);
544
        _mask->set(_process[i], false);
545 545
      }
546 546
      std::vector<Node> nextProcess;
547 547
      for (int i = 0; i < int(_process.size()); ++i) {
548
	for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
549
	  Node target = _gr->target(it);
550
	  Value relaxed = 
551
	    OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
552
	  if (OperationTraits::less(relaxed, (*_dist)[target])) {
553
	    _pred->set(target, it);
554
	    _dist->set(target, relaxed);
555
	    if (!(*_mask)[target]) {
556
	      _mask->set(target, true);
557
	      nextProcess.push_back(target);
558
	    }
559
	  }	  
560
	}
548
        for (OutArcIt it(*_gr, _process[i]); it != INVALID; ++it) {
549
          Node target = _gr->target(it);
550
          Value relaxed =
551
            OperationTraits::plus((*_dist)[_process[i]], (*_length)[it]);
552
          if (OperationTraits::less(relaxed, (*_dist)[target])) {
553
            _pred->set(target, it);
554
            _dist->set(target, relaxed);
555
            if (!(*_mask)[target]) {
556
              _mask->set(target, true);
557
              nextProcess.push_back(target);
558
            }
559
          }
560
        }
561 561
      }
562 562
      _process.swap(nextProcess);
563 563
      return _process.empty();
564 564
    }
565 565

	
566 566
    /// \brief Executes the algorithm.
567 567
    ///
568 568
    /// Executes the algorithm.
569 569
    ///
570 570
    /// This method runs the Bellman-Ford algorithm from the root node(s)
571 571
    /// in order to compute the shortest path to each node.
572 572
    ///
573 573
    /// The algorithm computes
574 574
    /// - the shortest path tree (forest),
575 575
    /// - the distance of each node from the root(s).
576 576
    ///
577 577
    /// \pre init() must be called and at least one root node should be
578 578
    /// added with addSource() before using this function.
579 579
    void start() {
580 580
      int num = countNodes(*_gr) - 1;
581 581
      for (int i = 0; i < num; ++i) {
582
	if (processNextWeakRound()) break;
582
        if (processNextWeakRound()) break;
583 583
      }
584 584
    }
585 585

	
586 586
    /// \brief Executes the algorithm and checks the negative cycles.
587 587
    ///
588 588
    /// Executes the algorithm and checks the negative cycles.
589 589
    ///
590 590
    /// This method runs the Bellman-Ford algorithm from the root node(s)
591 591
    /// in order to compute the shortest path to each node and also checks
592 592
    /// if the digraph contains cycles with negative total length.
593 593
    ///
594
    /// The algorithm computes 
594
    /// The algorithm computes
595 595
    /// - the shortest path tree (forest),
596 596
    /// - the distance of each node from the root(s).
597
    /// 
597
    ///
598 598
    /// \return \c false if there is a negative cycle in the digraph.
599 599
    ///
600 600
    /// \pre init() must be called and at least one root node should be
601
    /// added with addSource() before using this function. 
601
    /// added with addSource() before using this function.
602 602
    bool checkedStart() {
603 603
      int num = countNodes(*_gr);
604 604
      for (int i = 0; i < num; ++i) {
605
	if (processNextWeakRound()) return true;
605
        if (processNextWeakRound()) return true;
606 606
      }
607 607
      return _process.empty();
608 608
    }
609 609

	
610 610
    /// \brief Executes the algorithm with arc number limit.
611 611
    ///
612 612
    /// Executes the algorithm with arc number limit.
613 613
    ///
614 614
    /// This method runs the Bellman-Ford algorithm from the root node(s)
615 615
    /// in order to compute the shortest path distance for each node
616 616
    /// using only the paths consisting of at most \c num arcs.
617 617
    ///
618 618
    /// The algorithm computes
619 619
    /// - the limited distance of each node from the root(s),
620 620
    /// - the predecessor arc for each node.
621 621
    ///
622 622
    /// \warning The paths with limited arc number cannot be retrieved
623 623
    /// easily with \ref path() or \ref predArc() functions. If you also
624 624
    /// need the shortest paths and not only the distances, you should
625 625
    /// store the \ref predMap() "predecessor map" after each iteration
626 626
    /// and build the path manually.
627 627
    ///
628 628
    /// \pre init() must be called and at least one root node should be
629
    /// added with addSource() before using this function. 
629
    /// added with addSource() before using this function.
630 630
    void limitedStart(int num) {
631 631
      for (int i = 0; i < num; ++i) {
632
	if (processNextRound()) break;
632
        if (processNextRound()) break;
633 633
      }
634 634
    }
635
    
635

	
636 636
    /// \brief Runs the algorithm from the given root node.
637
    ///    
637
    ///
638 638
    /// This method runs the Bellman-Ford algorithm from the given root
639 639
    /// node \c s in order to compute the shortest path to each node.
640 640
    ///
641 641
    /// The algorithm computes
642 642
    /// - the shortest path tree (forest),
643 643
    /// - the distance of each node from the root(s).
644 644
    ///
645 645
    /// \note bf.run(s) is just a shortcut of the following code.
646 646
    /// \code
647 647
    ///   bf.init();
648 648
    ///   bf.addSource(s);
649 649
    ///   bf.start();
650 650
    /// \endcode
651 651
    void run(Node s) {
652 652
      init();
653 653
      addSource(s);
654 654
      start();
655 655
    }
656
    
656

	
657 657
    /// \brief Runs the algorithm from the given root node with arc
658 658
    /// number limit.
659
    ///    
659
    ///
660 660
    /// This method runs the Bellman-Ford algorithm from the given root
661 661
    /// node \c s in order to compute the shortest path distance for each
662 662
    /// node using only the paths consisting of at most \c num arcs.
663 663
    ///
664 664
    /// The algorithm computes
665 665
    /// - the limited distance of each node from the root(s),
666 666
    /// - the predecessor arc for each node.
667 667
    ///
668 668
    /// \warning The paths with limited arc number cannot be retrieved
669 669
    /// easily with \ref path() or \ref predArc() functions. If you also
670 670
    /// need the shortest paths and not only the distances, you should
671 671
    /// store the \ref predMap() "predecessor map" after each iteration
672 672
    /// and build the path manually.
673 673
    ///
674 674
    /// \note bf.run(s, num) is just a shortcut of the following code.
675 675
    /// \code
676 676
    ///   bf.init();
677 677
    ///   bf.addSource(s);
678 678
    ///   bf.limitedStart(num);
679 679
    /// \endcode
680 680
    void run(Node s, int num) {
681 681
      init();
682 682
      addSource(s);
683 683
      limitedStart(num);
684 684
    }
685
    
685

	
686 686
    ///@}
687 687

	
688 688
    /// \brief LEMON iterator for getting the active nodes.
689 689
    ///
690 690
    /// This class provides a common style LEMON iterator that traverses
691 691
    /// the active nodes of the Bellman-Ford algorithm after the last
692 692
    /// phase. These nodes should be checked in the next phase to
693 693
    /// find augmenting arcs outgoing from them.
694 694
    class ActiveIt {
695 695
    public:
696 696

	
697 697
      /// \brief Constructor.
698 698
      ///
699 699
      /// Constructor for getting the active nodes of the given BellmanFord
700
      /// instance. 
700
      /// instance.
701 701
      ActiveIt(const BellmanFord& algorithm) : _algorithm(&algorithm)
702 702
      {
703 703
        _index = _algorithm->_process.size() - 1;
704 704
      }
705 705

	
706 706
      /// \brief Invalid constructor.
707 707
      ///
708 708
      /// Invalid constructor.
709 709
      ActiveIt(Invalid) : _algorithm(0), _index(-1) {}
710 710

	
711 711
      /// \brief Conversion to \c Node.
712 712
      ///
713 713
      /// Conversion to \c Node.
714
      operator Node() const { 
714
      operator Node() const {
715 715
        return _index >= 0 ? _algorithm->_process[_index] : INVALID;
716 716
      }
717 717

	
718 718
      /// \brief Increment operator.
719 719
      ///
720 720
      /// Increment operator.
721 721
      ActiveIt& operator++() {
722 722
        --_index;
723
        return *this; 
723
        return *this;
724 724
      }
725 725

	
726
      bool operator==(const ActiveIt& it) const { 
727
        return static_cast<Node>(*this) == static_cast<Node>(it); 
726
      bool operator==(const ActiveIt& it) const {
727
        return static_cast<Node>(*this) == static_cast<Node>(it);
728 728
      }
729
      bool operator!=(const ActiveIt& it) const { 
730
        return static_cast<Node>(*this) != static_cast<Node>(it); 
729
      bool operator!=(const ActiveIt& it) const {
730
        return static_cast<Node>(*this) != static_cast<Node>(it);
731 731
      }
732
      bool operator<(const ActiveIt& it) const { 
733
        return static_cast<Node>(*this) < static_cast<Node>(it); 
732
      bool operator<(const ActiveIt& it) const {
733
        return static_cast<Node>(*this) < static_cast<Node>(it);
734 734
      }
735
      
735

	
736 736
    private:
737 737
      const BellmanFord* _algorithm;
738 738
      int _index;
739 739
    };
740
    
740

	
741 741
    /// \name Query Functions
742 742
    /// The result of the Bellman-Ford algorithm can be obtained using these
743 743
    /// functions.\n
744 744
    /// Either \ref run() or \ref init() should be called before using them.
745
    
745

	
746 746
    ///@{
747 747

	
748 748
    /// \brief The shortest path to the given node.
749
    ///    
749
    ///
750 750
    /// Gives back the shortest path to the given node from the root(s).
751 751
    ///
752 752
    /// \warning \c t should be reached from the root(s).
753 753
    ///
754 754
    /// \pre Either \ref run() or \ref init() must be called before
755 755
    /// using this function.
756 756
    Path path(Node t) const
757 757
    {
758 758
      return Path(*_gr, *_pred, t);
759 759
    }
760
	  
760

	
761 761
    /// \brief The distance of the given node from the root(s).
762 762
    ///
763 763
    /// Returns the distance of the given node from the root(s).
764 764
    ///
765 765
    /// \warning If node \c v is not reached from the root(s), then
766 766
    /// the return value of this function is undefined.
767 767
    ///
768 768
    /// \pre Either \ref run() or \ref init() must be called before
769 769
    /// using this function.
770 770
    Value dist(Node v) const { return (*_dist)[v]; }
771 771

	
772 772
    /// \brief Returns the 'previous arc' of the shortest path tree for
773 773
    /// the given node.
774 774
    ///
775 775
    /// This function returns the 'previous arc' of the shortest path
776 776
    /// tree for node \c v, i.e. it returns the last arc of a
777 777
    /// shortest path from a root to \c v. It is \c INVALID if \c v
778 778
    /// is not reached from the root(s) or if \c v is a root.
779 779
    ///
780 780
    /// The shortest path tree used here is equal to the shortest path
781 781
    /// tree used in \ref predNode() and \ref predMap().
782 782
    ///
783 783
    /// \pre Either \ref run() or \ref init() must be called before
784 784
    /// using this function.
785 785
    Arc predArc(Node v) const { return (*_pred)[v]; }
786 786

	
787 787
    /// \brief Returns the 'previous node' of the shortest path tree for
788 788
    /// the given node.
789 789
    ///
790 790
    /// This function returns the 'previous node' of the shortest path
791 791
    /// tree for node \c v, i.e. it returns the last but one node of
792 792
    /// a shortest path from a root to \c v. It is \c INVALID if \c v
793 793
    /// is not reached from the root(s) or if \c v is a root.
794 794
    ///
795 795
    /// The shortest path tree used here is equal to the shortest path
796 796
    /// tree used in \ref predArc() and \ref predMap().
797 797
    ///
798 798
    /// \pre Either \ref run() or \ref init() must be called before
799 799
    /// using this function.
800
    Node predNode(Node v) const { 
801
      return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]); 
800
    Node predNode(Node v) const {
801
      return (*_pred)[v] == INVALID ? INVALID : _gr->source((*_pred)[v]);
802 802
    }
803
    
803

	
804 804
    /// \brief Returns a const reference to the node map that stores the
805 805
    /// distances of the nodes.
806 806
    ///
807 807
    /// Returns a const reference to the node map that stores the distances
808 808
    /// of the nodes calculated by the algorithm.
809 809
    ///
810 810
    /// \pre Either \ref run() or \ref init() must be called before
811 811
    /// using this function.
812 812
    const DistMap &distMap() const { return *_dist;}
813
 
813

	
814 814
    /// \brief Returns a const reference to the node map that stores the
815 815
    /// predecessor arcs.
816 816
    ///
817 817
    /// Returns a const reference to the node map that stores the predecessor
818 818
    /// arcs, which form the shortest path tree (forest).
819 819
    ///
820 820
    /// \pre Either \ref run() or \ref init() must be called before
821 821
    /// using this function.
822 822
    const PredMap &predMap() const { return *_pred; }
823
 
823

	
824 824
    /// \brief Checks if a node is reached from the root(s).
825 825
    ///
826 826
    /// Returns \c true if \c v is reached from the root(s).
827 827
    ///
828 828
    /// \pre Either \ref run() or \ref init() must be called before
829 829
    /// using this function.
830 830
    bool reached(Node v) const {
831 831
      return (*_dist)[v] != OperationTraits::infinity();
832 832
    }
833 833

	
834 834
    /// \brief Gives back a negative cycle.
835
    ///    
835
    ///
836 836
    /// This function gives back a directed cycle with negative total
837 837
    /// length if the algorithm has already found one.
838 838
    /// Otherwise it gives back an empty path.
839 839
    lemon::Path<Digraph> negativeCycle() const {
840 840
      typename Digraph::template NodeMap<int> state(*_gr, -1);
841 841
      lemon::Path<Digraph> cycle;
842 842
      for (int i = 0; i < int(_process.size()); ++i) {
843 843
        if (state[_process[i]] != -1) continue;
844 844
        for (Node v = _process[i]; (*_pred)[v] != INVALID;
845 845
             v = _gr->source((*_pred)[v])) {
846 846
          if (state[v] == i) {
847 847
            cycle.addFront((*_pred)[v]);
848 848
            for (Node u = _gr->source((*_pred)[v]); u != v;
849 849
                 u = _gr->source((*_pred)[u])) {
850 850
              cycle.addFront((*_pred)[u]);
851 851
            }
852 852
            return cycle;
853 853
          }
854 854
          else if (state[v] >= 0) {
855 855
            break;
856 856
          }
857 857
          state[v] = i;
858 858
        }
859 859
      }
860 860
      return cycle;
861 861
    }
862
    
862

	
863 863
    ///@}
864 864
  };
865
 
865

	
866 866
  /// \brief Default traits class of bellmanFord() function.
867 867
  ///
868 868
  /// Default traits class of bellmanFord() function.
869 869
  /// \tparam GR The type of the digraph.
870 870
  /// \tparam LEN The type of the length map.
871 871
  template <typename GR, typename LEN>
872 872
  struct BellmanFordWizardDefaultTraits {
873
    /// The type of the digraph the algorithm runs on. 
873
    /// The type of the digraph the algorithm runs on.
874 874
    typedef GR Digraph;
875 875

	
876 876
    /// \brief The type of the map that stores the arc lengths.
877 877
    ///
878 878
    /// The type of the map that stores the arc lengths.
879 879
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
880 880
    typedef LEN LengthMap;
881 881

	
882 882
    /// The type of the arc lengths.
883 883
    typedef typename LEN::Value Value;
884 884

	
885 885
    /// \brief Operation traits for Bellman-Ford algorithm.
886 886
    ///
887 887
    /// It defines the used operations and the infinity value for the
888 888
    /// given \c Value type.
889 889
    /// \see BellmanFordDefaultOperationTraits,
890 890
    /// BellmanFordToleranceOperationTraits
891 891
    typedef BellmanFordDefaultOperationTraits<Value> OperationTraits;
892 892

	
893 893
    /// \brief The type of the map that stores the last
894 894
    /// arcs of the shortest paths.
895
    /// 
895
    ///
896 896
    /// The type of the map that stores the last arcs of the shortest paths.
897 897
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
898 898
    typedef typename GR::template NodeMap<typename GR::Arc> PredMap;
899 899

	
900 900
    /// \brief Instantiates a \c PredMap.
901
    /// 
901
    ///
902 902
    /// This function instantiates a \ref PredMap.
903 903
    /// \param g is the digraph to which we would like to define the
904 904
    /// \ref PredMap.
905 905
    static PredMap *createPredMap(const GR &g) {
906 906
      return new PredMap(g);
907 907
    }
908 908

	
909 909
    /// \brief The type of the map that stores the distances of the nodes.
910 910
    ///
911 911
    /// The type of the map that stores the distances of the nodes.
912 912
    /// It must conform to the \ref concepts::WriteMap "WriteMap" concept.
913 913
    typedef typename GR::template NodeMap<Value> DistMap;
914 914

	
915 915
    /// \brief Instantiates a \c DistMap.
916 916
    ///
917
    /// This function instantiates a \ref DistMap. 
917
    /// This function instantiates a \ref DistMap.
918 918
    /// \param g is the digraph to which we would like to define the
919 919
    /// \ref DistMap.
920 920
    static DistMap *createDistMap(const GR &g) {
921 921
      return new DistMap(g);
922 922
    }
923 923

	
924 924
    ///The type of the shortest paths.
925 925

	
926 926
    ///The type of the shortest paths.
927 927
    ///It must meet the \ref concepts::Path "Path" concept.
928 928
    typedef lemon::Path<Digraph> Path;
929 929
  };
930
  
930

	
931 931
  /// \brief Default traits class used by BellmanFordWizard.
932 932
  ///
933 933
  /// Default traits class used by BellmanFordWizard.
934 934
  /// \tparam GR The type of the digraph.
935 935
  /// \tparam LEN The type of the length map.
936 936
  template <typename GR, typename LEN>
937
  class BellmanFordWizardBase 
937
  class BellmanFordWizardBase
938 938
    : public BellmanFordWizardDefaultTraits<GR, LEN> {
939 939

	
940 940
    typedef BellmanFordWizardDefaultTraits<GR, LEN> Base;
941 941
  protected:
942 942
    // Type of the nodes in the digraph.
943 943
    typedef typename Base::Digraph::Node Node;
944 944

	
945 945
    // Pointer to the underlying digraph.
946 946
    void *_graph;
947 947
    // Pointer to the length map
948 948
    void *_length;
949 949
    // Pointer to the map of predecessors arcs.
950 950
    void *_pred;
951 951
    // Pointer to the map of distances.
952 952
    void *_dist;
953 953
    //Pointer to the shortest path to the target node.
954 954
    void *_path;
955 955
    //Pointer to the distance of the target node.
956 956
    void *_di;
957 957

	
958 958
    public:
959 959
    /// Constructor.
960
    
960

	
961 961
    /// This constructor does not require parameters, it initiates
962 962
    /// all of the attributes to default values \c 0.
963 963
    BellmanFordWizardBase() :
964 964
      _graph(0), _length(0), _pred(0), _dist(0), _path(0), _di(0) {}
965 965

	
966 966
    /// Constructor.
967
    
967

	
968 968
    /// This constructor requires two parameters,
969 969
    /// others are initiated to \c 0.
970 970
    /// \param gr The digraph the algorithm runs on.
971 971
    /// \param len The length map.
972
    BellmanFordWizardBase(const GR& gr, 
973
			  const LEN& len) :
974
      _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))), 
975
      _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))), 
972
    BellmanFordWizardBase(const GR& gr,
973
                          const LEN& len) :
974
      _graph(reinterpret_cast<void*>(const_cast<GR*>(&gr))),
975
      _length(reinterpret_cast<void*>(const_cast<LEN*>(&len))),
976 976
      _pred(0), _dist(0), _path(0), _di(0) {}
977 977

	
978 978
  };
979
  
979

	
980 980
  /// \brief Auxiliary class for the function-type interface of the
981 981
  /// \ref BellmanFord "Bellman-Ford" algorithm.
982 982
  ///
983 983
  /// This auxiliary class is created to implement the
984 984
  /// \ref bellmanFord() "function-type interface" of the
985 985
  /// \ref BellmanFord "Bellman-Ford" algorithm.
986 986
  /// It does not have own \ref run() method, it uses the
987 987
  /// functions and features of the plain \ref BellmanFord.
988 988
  ///
989 989
  /// This class should only be used through the \ref bellmanFord()
990 990
  /// function, which makes it easier to use the algorithm.
991 991
  ///
992 992
  /// \tparam TR The traits class that defines various types used by the
993 993
  /// algorithm.
994 994
  template<class TR>
995 995
  class BellmanFordWizard : public TR {
996 996
    typedef TR Base;
997 997

	
998 998
    typedef typename TR::Digraph Digraph;
999 999

	
1000 1000
    typedef typename Digraph::Node Node;
1001 1001
    typedef typename Digraph::NodeIt NodeIt;
1002 1002
    typedef typename Digraph::Arc Arc;
1003 1003
    typedef typename Digraph::OutArcIt ArcIt;
1004
    
1004

	
1005 1005
    typedef typename TR::LengthMap LengthMap;
1006 1006
    typedef typename LengthMap::Value Value;
1007 1007
    typedef typename TR::PredMap PredMap;
1008 1008
    typedef typename TR::DistMap DistMap;
1009 1009
    typedef typename TR::Path Path;
1010 1010

	
1011 1011
  public:
1012 1012
    /// Constructor.
1013 1013
    BellmanFordWizard() : TR() {}
1014 1014

	
1015 1015
    /// \brief Constructor that requires parameters.
1016 1016
    ///
1017 1017
    /// Constructor that requires parameters.
1018 1018
    /// These parameters will be the default values for the traits class.
1019 1019
    /// \param gr The digraph the algorithm runs on.
1020 1020
    /// \param len The length map.
1021
    BellmanFordWizard(const Digraph& gr, const LengthMap& len) 
1021
    BellmanFordWizard(const Digraph& gr, const LengthMap& len)
1022 1022
      : TR(gr, len) {}
1023 1023

	
1024 1024
    /// \brief Copy constructor
1025 1025
    BellmanFordWizard(const TR &b) : TR(b) {}
1026 1026

	
1027 1027
    ~BellmanFordWizard() {}
1028 1028

	
1029 1029
    /// \brief Runs the Bellman-Ford algorithm from the given source node.
1030
    ///    
1030
    ///
1031 1031
    /// This method runs the Bellman-Ford algorithm from the given source
1032 1032
    /// node in order to compute the shortest path to each node.
1033 1033
    void run(Node s) {
1034
      BellmanFord<Digraph,LengthMap,TR> 
1035
	bf(*reinterpret_cast<const Digraph*>(Base::_graph), 
1034
      BellmanFord<Digraph,LengthMap,TR>
1035
        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1036 1036
           *reinterpret_cast<const LengthMap*>(Base::_length));
1037 1037
      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1038 1038
      if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1039 1039
      bf.run(s);
1040 1040
    }
1041 1041

	
1042 1042
    /// \brief Runs the Bellman-Ford algorithm to find the shortest path
1043 1043
    /// between \c s and \c t.
1044 1044
    ///
1045 1045
    /// This method runs the Bellman-Ford algorithm from node \c s
1046 1046
    /// in order to compute the shortest path to node \c t.
1047 1047
    /// Actually, it computes the shortest path to each node, but using
1048 1048
    /// this function you can retrieve the distance and the shortest path
1049 1049
    /// for a single target node easier.
1050 1050
    ///
1051 1051
    /// \return \c true if \c t is reachable form \c s.
1052 1052
    bool run(Node s, Node t) {
1053 1053
      BellmanFord<Digraph,LengthMap,TR>
1054 1054
        bf(*reinterpret_cast<const Digraph*>(Base::_graph),
1055 1055
           *reinterpret_cast<const LengthMap*>(Base::_length));
1056 1056
      if (Base::_pred) bf.predMap(*reinterpret_cast<PredMap*>(Base::_pred));
1057 1057
      if (Base::_dist) bf.distMap(*reinterpret_cast<DistMap*>(Base::_dist));
1058 1058
      bf.run(s);
1059 1059
      if (Base::_path) *reinterpret_cast<Path*>(Base::_path) = bf.path(t);
1060 1060
      if (Base::_di) *reinterpret_cast<Value*>(Base::_di) = bf.dist(t);
1061 1061
      return bf.reached(t);
1062 1062
    }
1063 1063

	
1064 1064
    template<class T>
1065 1065
    struct SetPredMapBase : public Base {
1066 1066
      typedef T PredMap;
1067 1067
      static PredMap *createPredMap(const Digraph &) { return 0; };
1068 1068
      SetPredMapBase(const TR &b) : TR(b) {}
1069 1069
    };
1070
    
1070

	
1071 1071
    /// \brief \ref named-templ-param "Named parameter" for setting
1072 1072
    /// the predecessor map.
1073 1073
    ///
1074 1074
    /// \ref named-templ-param "Named parameter" for setting
1075 1075
    /// the map that stores the predecessor arcs of the nodes.
1076 1076
    template<class T>
1077 1077
    BellmanFordWizard<SetPredMapBase<T> > predMap(const T &t) {
1078 1078
      Base::_pred=reinterpret_cast<void*>(const_cast<T*>(&t));
1079 1079
      return BellmanFordWizard<SetPredMapBase<T> >(*this);
1080 1080
    }
1081
    
1081

	
1082 1082
    template<class T>
1083 1083
    struct SetDistMapBase : public Base {
1084 1084
      typedef T DistMap;
1085 1085
      static DistMap *createDistMap(const Digraph &) { return 0; };
1086 1086
      SetDistMapBase(const TR &b) : TR(b) {}
1087 1087
    };
1088
    
1088

	
1089 1089
    /// \brief \ref named-templ-param "Named parameter" for setting
1090 1090
    /// the distance map.
1091 1091
    ///
1092 1092
    /// \ref named-templ-param "Named parameter" for setting
1093 1093
    /// the map that stores the distances of the nodes calculated
1094 1094
    /// by the algorithm.
1095 1095
    template<class T>
1096 1096
    BellmanFordWizard<SetDistMapBase<T> > distMap(const T &t) {
1097 1097
      Base::_dist=reinterpret_cast<void*>(const_cast<T*>(&t));
1098 1098
      return BellmanFordWizard<SetDistMapBase<T> >(*this);
1099 1099
    }
1100 1100

	
1101 1101
    template<class T>
1102 1102
    struct SetPathBase : public Base {
1103 1103
      typedef T Path;
1104 1104
      SetPathBase(const TR &b) : TR(b) {}
1105 1105
    };
1106 1106

	
1107 1107
    /// \brief \ref named-func-param "Named parameter" for getting
1108 1108
    /// the shortest path to the target node.
1109 1109
    ///
1110 1110
    /// \ref named-func-param "Named parameter" for getting
1111 1111
    /// the shortest path to the target node.
1112 1112
    template<class T>
1113 1113
    BellmanFordWizard<SetPathBase<T> > path(const T &t)
1114 1114
    {
1115 1115
      Base::_path=reinterpret_cast<void*>(const_cast<T*>(&t));
1116 1116
      return BellmanFordWizard<SetPathBase<T> >(*this);
1117 1117
    }
1118 1118

	
1119 1119
    /// \brief \ref named-func-param "Named parameter" for getting
1120 1120
    /// the distance of the target node.
1121 1121
    ///
1122 1122
    /// \ref named-func-param "Named parameter" for getting
1123 1123
    /// the distance of the target node.
1124 1124
    BellmanFordWizard dist(const Value &d)
1125 1125
    {
1126 1126
      Base::_di=reinterpret_cast<void*>(const_cast<Value*>(&d));
1127 1127
      return *this;
1128 1128
    }
1129
    
1129

	
1130 1130
  };
1131
  
1131

	
1132 1132
  /// \brief Function type interface for the \ref BellmanFord "Bellman-Ford"
1133 1133
  /// algorithm.
1134 1134
  ///
1135 1135
  /// \ingroup shortest_path
1136 1136
  /// Function type interface for the \ref BellmanFord "Bellman-Ford"
1137 1137
  /// algorithm.
1138 1138
  ///
1139
  /// This function also has several \ref named-templ-func-param 
1140
  /// "named parameters", they are declared as the members of class 
1139
  /// This function also has several \ref named-templ-func-param
1140
  /// "named parameters", they are declared as the members of class
1141 1141
  /// \ref BellmanFordWizard.
1142 1142
  /// The following examples show how to use these parameters.
1143 1143
  /// \code
1144 1144
  ///   // Compute shortest path from node s to each node
1145 1145
  ///   bellmanFord(g,length).predMap(preds).distMap(dists).run(s);
1146 1146
  ///
1147 1147
  ///   // Compute shortest path from s to t
1148 1148
  ///   bool reached = bellmanFord(g,length).path(p).dist(d).run(s,t);
1149 1149
  /// \endcode
1150 1150
  /// \warning Don't forget to put the \ref BellmanFordWizard::run() "run()"
1151 1151
  /// to the end of the parameter list.
1152 1152
  /// \sa BellmanFordWizard
1153 1153
  /// \sa BellmanFord
1154 1154
  template<typename GR, typename LEN>
1155 1155
  BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >
1156 1156
  bellmanFord(const GR& digraph,
1157
	      const LEN& length)
1157
              const LEN& length)
1158 1158
  {
1159 1159
    return BellmanFordWizard<BellmanFordWizardBase<GR,LEN> >(digraph, length);
1160 1160
  }
1161 1161

	
1162 1162
} //END OF NAMESPACE LEMON
1163 1163

	
1164 1164
#endif
1165 1165

	
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BFS_H
20 20
#define LEMON_BFS_H
21 21

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

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

	
33 33
namespace lemon {
34 34

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

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

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

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

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

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

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

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

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

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

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

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

	
104 105
    ///This function instantiates a \ref DistMap.
105 106
    ///\param g is the digraph, to which we would like to define the
106 107
    ///\ref DistMap.
107 108
    static DistMap *createDistMap(const Digraph &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
  ///There is also a \ref bfs() "function-type interface" for the BFS
119 120
  ///algorithm, which is convenient in the simplier cases and it can be
120 121
  ///used easier.
121 122
  ///
122 123
  ///\tparam GR The type of the digraph the algorithm runs on.
123 124
  ///The default type is \ref ListDigraph.
124 125
  ///\tparam TR The traits class that defines various types used by the
125 126
  ///algorithm. By default, it is \ref BfsDefaultTraits
126 127
  ///"BfsDefaultTraits<GR>".
127 128
  ///In most cases, this parameter should not be set directly,
128 129
  ///consider to use the named template parameters instead.
129 130
#ifdef DOXYGEN
130 131
  template <typename GR,
131 132
            typename TR>
132 133
#else
133 134
  template <typename GR=ListDigraph,
... ...
@@ -226,97 +227,98 @@
226 227
        return 0; // ignore warnings
227 228
      }
228 229
    };
229 230
    ///\brief \ref named-templ-param "Named parameter" for setting
230 231
    ///\c PredMap type.
231 232
    ///
232 233
    ///\ref named-templ-param "Named parameter" for setting
233 234
    ///\c PredMap type.
234 235
    ///It must conform to the \ref concepts::WriteMap "WriteMap" concept.
235 236
    template <class T>
236 237
    struct SetPredMap : public Bfs< Digraph, SetPredMapTraits<T> > {
237 238
      typedef Bfs< Digraph, SetPredMapTraits<T> > Create;
238 239
    };
239 240

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

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

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

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

	
319 321
    ///@}
320 322

	
321 323
  public:
322 324

	
... ...
@@ -827,97 +829,98 @@
827 829
  ///Default traits class of bfs() function.
828 830
  ///\tparam GR Digraph type.
829 831
  template<class GR>
830 832
  struct BfsWizardDefaultTraits
831 833
  {
832 834
    ///The type of the digraph the algorithm runs on.
833 835
    typedef GR Digraph;
834 836

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

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

	
852 854
    ///The type of the map that indicates which nodes are processed.
853 855

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

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

	
872 874
    ///The type of the map that indicates which nodes are reached.
873 875

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

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

	
887 890
    ///The type of the map that stores the distances of the nodes.
888 891

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

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

	
902 905
    ///The type of the shortest paths.
903 906

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

	
909 912
  /// Default traits class used by BfsWizard
910 913

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

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

	
922 925
    //Pointer to the digraph the algorithm runs on.
923 926
    void *_g;
... ...
@@ -1220,97 +1223,98 @@
1220 1223
    /// \brief Called when an arc is examined but its target node is
1221 1224
    /// already discovered.
1222 1225
    ///
1223 1226
    /// This function is called when an arc is examined but its target node is
1224 1227
    /// already discovered.
1225 1228
    void examine(const Arc& arc) {}
1226 1229
  };
1227 1230
#else
1228 1231
  template <typename GR>
1229 1232
  struct BfsVisitor {
1230 1233
    typedef GR Digraph;
1231 1234
    typedef typename Digraph::Arc Arc;
1232 1235
    typedef typename Digraph::Node Node;
1233 1236
    void start(const Node&) {}
1234 1237
    void reach(const Node&) {}
1235 1238
    void process(const Node&) {}
1236 1239
    void discover(const Arc&) {}
1237 1240
    void examine(const Arc&) {}
1238 1241

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

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

	
1262 1265
    /// \brief The type of the digraph the algorithm runs on.
1263 1266
    typedef GR Digraph;
1264 1267

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

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

	
1280 1284
  };
1281 1285

	
1282 1286
  /// \ingroup search
1283 1287
  ///
1284 1288
  /// \brief BFS algorithm class with visitor interface.
1285 1289
  ///
1286 1290
  /// This class provides an efficient implementation of the BFS algorithm
1287 1291
  /// with visitor interface.
1288 1292
  ///
1289 1293
  /// The BfsVisit class provides an alternative interface to the Bfs
1290 1294
  /// class. It works with callback mechanism, the BfsVisit object calls
1291 1295
  /// the member functions of the \c Visitor class on every BFS event.
1292 1296
  ///
1293 1297
  /// This interface of the BFS algorithm should be used in special cases
1294 1298
  /// when extra actions have to be performed in connection with certain
1295 1299
  /// events of the BFS algorithm. Otherwise consider to use Bfs or bfs()
1296 1300
  /// instead.
1297 1301
  ///
1298 1302
  /// \tparam GR The type of the digraph the algorithm runs on.
1299 1303
  /// The default type is \ref ListDigraph.
1300 1304
  /// The value of GR is not used directly by \ref BfsVisit,
1301 1305
  /// it is only passed to \ref BfsVisitDefaultTraits.
1302 1306
  /// \tparam VS The Visitor type that is used by the algorithm.
1303 1307
  /// \ref BfsVisitor "BfsVisitor<GR>" is an empty visitor, which
1304 1308
  /// does not observe the BFS events. If you want to observe the BFS
1305 1309
  /// events, you should implement your own visitor class.
1306 1310
  /// \tparam TR The traits class that defines various types used by the
1307 1311
  /// algorithm. By default, it is \ref BfsVisitDefaultTraits
1308 1312
  /// "BfsVisitDefaultTraits<GR>".
1309 1313
  /// In most cases, this parameter should not be set directly,
1310 1314
  /// consider to use the named template parameters instead.
1311 1315
#ifdef DOXYGEN
1312 1316
  template <typename GR, typename VS, typename TR>
1313 1317
#else
1314 1318
  template <typename GR = ListDigraph,
1315 1319
            typename VS = BfsVisitor<GR>,
1316 1320
            typename TR = BfsVisitDefaultTraits<GR> >
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
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_BINOMIAL_HEAP_H
20 20
#define LEMON_BINOMIAL_HEAP_H
21 21

	
22 22
///\file
23 23
///\ingroup heaps
24 24
///\brief Binomial Heap implementation.
25 25

	
26 26
#include <vector>
27 27
#include <utility>
28 28
#include <functional>
29 29
#include <lemon/math.h>
30 30
#include <lemon/counter.h>
31 31

	
32 32
namespace lemon {
33 33

	
34 34
  /// \ingroup heaps
35 35
  ///
36 36
  ///\brief Binomial heap data structure.
37 37
  ///
38 38
  /// This class implements the \e binomial \e heap data structure.
39 39
  /// It fully conforms to the \ref concepts::Heap "heap concept".
40 40
  ///
41 41
  /// The methods \ref increase() and \ref erase() are not efficient
42 42
  /// in a binomial heap. In case of many calls of these operations,
43 43
  /// it is better to use other heap structure, e.g. \ref BinHeap
44 44
  /// "binary heap".
45 45
  ///
46 46
  /// \tparam PR Type of the priorities of the items.
47 47
  /// \tparam IM A read-writable item map with \c int values, used
48 48
  /// internally to handle the cross references.
49 49
  /// \tparam CMP A functor class for comparing the priorities.
50 50
  /// The default is \c std::less<PR>.
51 51
#ifdef DOXYGEN
52 52
  template <typename PR, typename IM, typename CMP>
53 53
#else
... ...
@@ -213,233 +213,233 @@
213 213
        int neighb;
214 214
        while( child!=-1 ) {
215 215
          neighb=_data[child].right_neighbor;
216 216
          _data[child].parent=-1;
217 217
          _data[child].right_neighbor=head_child;
218 218
          head_child=child;
219 219
          child=neighb;
220 220
        }
221 221
      }
222 222

	
223 223
      if ( _data[_head].right_neighbor==-1 ) {
224 224
        // there was only one root
225 225
        _head=head_child;
226 226
      }
227 227
      else {
228 228
        // there were more roots
229 229
        if( _head!=_min )  { unlace(_min); }
230 230
        else { _head=_data[_head].right_neighbor; }
231 231
        merge(head_child);
232 232
      }
233 233
      _min=findMin();
234 234
      --_num_items;
235 235
    }
236 236

	
237 237
    /// \brief Remove the given item from the heap.
238 238
    ///
239 239
    /// This function removes the given item from the heap if it is
240 240
    /// already stored.
241 241
    /// \param item The item to delete.
242 242
    /// \pre \e item must be in the heap.
243 243
    void erase (const Item& item) {
244 244
      int i=_iim[item];
245 245
      if ( i >= 0 && _data[i].in ) {
246 246
        decrease( item, _data[_min].prio-1 );
247 247
        pop();
248 248
      }
249 249
    }
250 250

	
251 251
    /// \brief Decrease the priority of an item to the given value.
252 252
    ///
253 253
    /// This function decreases the priority of an item to the given value.
254 254
    /// \param item The item.
255 255
    /// \param value The priority.
256 256
    /// \pre \e item must be stored in the heap with priority at least \e value.
257 257
    void decrease (Item item, const Prio& value) {
258 258
      int i=_iim[item];
259 259
      int p=_data[i].parent;
260 260
      _data[i].prio=value;
261
      
261

	
262 262
      while( p!=-1 && _comp(value, _data[p].prio) ) {
263 263
        _data[i].name=_data[p].name;
264 264
        _data[i].prio=_data[p].prio;
265 265
        _data[p].name=item;
266 266
        _data[p].prio=value;
267 267
        _iim[_data[i].name]=i;
268 268
        i=p;
269 269
        p=_data[p].parent;
270 270
      }
271 271
      _iim[item]=i;
272 272
      if ( _comp(value, _data[_min].prio) ) _min=i;
273 273
    }
274 274

	
275 275
    /// \brief Increase the priority of an item to the given value.
276 276
    ///
277 277
    /// This function increases the priority of an item to the given value.
278 278
    /// \param item The item.
279 279
    /// \param value The priority.
280 280
    /// \pre \e item must be stored in the heap with priority at most \e value.
281 281
    void increase (Item item, const Prio& value) {
282 282
      erase(item);
283 283
      push(item, value);
284 284
    }
285 285

	
286 286
    /// \brief Return the state of an item.
287 287
    ///
288 288
    /// This method returns \c PRE_HEAP if the given item has never
289 289
    /// been in the heap, \c IN_HEAP if it is in the heap at the moment,
290 290
    /// and \c POST_HEAP otherwise.
291 291
    /// In the latter case it is possible that the item will get back
292 292
    /// to the heap again.
293 293
    /// \param item The item.
294 294
    State state(const Item &item) const {
295 295
      int i=_iim[item];
296 296
      if( i>=0 ) {
297 297
        if ( _data[i].in ) i=0;
298 298
        else i=-2;
299 299
      }
300 300
      return State(i);
301 301
    }
302 302

	
303 303
    /// \brief Set the state of an item in the heap.
304 304
    ///
305 305
    /// This function sets the state of the given item in the heap.
306 306
    /// It can be used to manually clear the heap when it is important
307 307
    /// to achive better time complexity.
308 308
    /// \param i The item.
309 309
    /// \param st The state. It should not be \c IN_HEAP.
310 310
    void state(const Item& i, State st) {
311 311
      switch (st) {
312 312
      case POST_HEAP:
313 313
      case PRE_HEAP:
314 314
        if (state(i) == IN_HEAP) {
315 315
          erase(i);
316 316
        }
317 317
        _iim[i] = st;
318 318
        break;
319 319
      case IN_HEAP:
320 320
        break;
321 321
      }
322 322
    }
323 323

	
324 324
  private:
325
    
325

	
326 326
    // Find the minimum of the roots
327 327
    int findMin() {
328 328
      if( _head!=-1 ) {
329 329
        int min_loc=_head, min_val=_data[_head].prio;
330 330
        for( int x=_data[_head].right_neighbor; x!=-1;
331 331
             x=_data[x].right_neighbor ) {
332 332
          if( _comp( _data[x].prio,min_val ) ) {
333 333
            min_val=_data[x].prio;
334 334
            min_loc=x;
335 335
          }
336 336
        }
337 337
        return min_loc;
338 338
      }
339 339
      else return -1;
340 340
    }
341 341

	
342 342
    // Merge the heap with another heap starting at the given position
343 343
    void merge(int a) {
344 344
      if( _head==-1 || a==-1 ) return;
345 345
      if( _data[a].right_neighbor==-1 &&
346 346
          _data[a].degree<=_data[_head].degree ) {
347 347
        _data[a].right_neighbor=_head;
348 348
        _head=a;
349 349
      } else {
350 350
        interleave(a);
351 351
      }
352 352
      if( _data[_head].right_neighbor==-1 ) return;
353
      
353

	
354 354
      int x=_head;
355 355
      int x_prev=-1, x_next=_data[x].right_neighbor;
356 356
      while( x_next!=-1 ) {
357 357
        if( _data[x].degree!=_data[x_next].degree ||
358 358
            ( _data[x_next].right_neighbor!=-1 &&
359 359
              _data[_data[x_next].right_neighbor].degree==_data[x].degree ) ) {
360 360
          x_prev=x;
361 361
          x=x_next;
362 362
        }
363 363
        else {
364 364
          if( _comp(_data[x_next].prio,_data[x].prio) ) {
365 365
            if( x_prev==-1 ) {
366 366
              _head=x_next;
367 367
            } else {
368 368
              _data[x_prev].right_neighbor=x_next;
369 369
            }
370 370
            fuse(x,x_next);
371 371
            x=x_next;
372 372
          }
373 373
          else {
374 374
            _data[x].right_neighbor=_data[x_next].right_neighbor;
375 375
            fuse(x_next,x);
376 376
          }
377 377
        }
378 378
        x_next=_data[x].right_neighbor;
379 379
      }
380 380
    }
381 381

	
382 382
    // Interleave the elements of the given list into the list of the roots
383 383
    void interleave(int a) {
384 384
      int p=_head, q=a;
385 385
      int curr=_data.size();
386 386
      _data.push_back(Store());
387
      
387

	
388 388
      while( p!=-1 || q!=-1 ) {
389 389
        if( q==-1 || ( p!=-1 && _data[p].degree<_data[q].degree ) ) {
390 390
          _data[curr].right_neighbor=p;
391 391
          curr=p;
392 392
          p=_data[p].right_neighbor;
393 393
        }
394 394
        else {
395 395
          _data[curr].right_neighbor=q;
396 396
          curr=q;
397 397
          q=_data[q].right_neighbor;
398 398
        }
399 399
      }
400
      
400

	
401 401
      _head=_data.back().right_neighbor;
402 402
      _data.pop_back();
403 403
    }
404 404

	
405 405
    // Lace node a under node b
406 406
    void fuse(int a, int b) {
407 407
      _data[a].parent=b;
408 408
      _data[a].right_neighbor=_data[b].child;
409 409
      _data[b].child=a;
410 410

	
411 411
      ++_data[b].degree;
412 412
    }
413 413

	
414 414
    // Unlace node a (if it has siblings)
415 415
    void unlace(int a) {
416 416
      int neighb=_data[a].right_neighbor;
417 417
      int other=_head;
418 418

	
419 419
      while( _data[other].right_neighbor!=a )
420 420
        other=_data[other].right_neighbor;
421 421
      _data[other].right_neighbor=neighb;
422 422
    }
423 423

	
424 424
  private:
425 425

	
426 426
    class Store {
427 427
      friend class BinomialHeap;
428 428

	
429 429
      Item name;
430 430
      int parent;
431 431
      int right_neighbor;
432 432
      int child;
433 433
      int degree;
434 434
      bool in;
435 435
      Prio prio;
436 436

	
437 437
      Store() : parent(-1), right_neighbor(-1), child(-1), degree(0),
438 438
        in(true) {}
439 439
    };
440 440
  };
441 441

	
442 442
} //namespace lemon
443 443

	
444 444
#endif //LEMON_BINOMIAL_HEAP_H
445 445

	
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_ARRAY_MAP_H
20 20
#define LEMON_BITS_ARRAY_MAP_H
21 21

	
22 22
#include <memory>
23 23

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

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

	
33 33
namespace lemon {
34 34

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

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

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

	
66 66
    // The map type.
67 67
    typedef ArrayMap Map;
68 68

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

	
72 72
  private:
73
  
73

	
74 74
    // The MapBase of the Map which imlements the core regisitry function.
75 75
    typedef typename Notifier::ObserverBase Parent;
76 76

	
77 77
    typedef std::allocator<Value> Allocator;
78 78

	
79 79
  public:
80 80

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

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

	
109 109
  private:
110 110
    // \brief Constructor to copy a map of the same map type.
111 111
    //
112 112
    // Constructor to copy a map of the same map type.
113 113
    ArrayMap(const ArrayMap& copy) : Parent() {
114 114
      if (copy.attached()) {
115 115
        attach(*copy.notifier());
116 116
      }
117 117
      capacity = copy.capacity;
118 118
      if (capacity == 0) return;
119 119
      values = allocator.allocate(capacity);
120 120
      Notifier* nf = Parent::notifier();
121 121
      Item it;
Ignore white space 96 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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_DEFAULT_MAP_H
20 20
#define LEMON_BITS_DEFAULT_MAP_H
21 21

	
22 22
#include <lemon/config.h>
23 23
#include <lemon/bits/array_map.h>
24 24
#include <lemon/bits/vector_map.h>
25 25
//#include <lemon/bits/debug_map.h>
26 26

	
27 27
//\ingroup graphbits
28 28
//\file
29 29
//\brief Graph maps that construct and destruct their elements dynamically.
30 30

	
31 31
namespace lemon {
32 32

	
33 33

	
34 34
  //#ifndef LEMON_USE_DEBUG_MAP
35 35

	
36 36
  template <typename _Graph, typename _Item, typename _Value>
37 37
  struct DefaultMapSelector {
38 38
    typedef ArrayMap<_Graph, _Item, _Value> Map;
39 39
  };
40 40

	
41 41
  // bool
42 42
  template <typename _Graph, typename _Item>
43 43
  struct DefaultMapSelector<_Graph, _Item, bool> {
44 44
    typedef VectorMap<_Graph, _Item, bool> Map;
45 45
  };
46 46

	
47 47
  // char
48 48
  template <typename _Graph, typename _Item>
49 49
  struct DefaultMapSelector<_Graph, _Item, char> {
50 50
    typedef VectorMap<_Graph, _Item, char> Map;
51 51
  };
52 52

	
53 53
  template <typename _Graph, typename _Item>
... ...
@@ -112,71 +112,71 @@
112 112

	
113 113
#endif
114 114

	
115 115

	
116 116
  // float
117 117
  template <typename _Graph, typename _Item>
118 118
  struct DefaultMapSelector<_Graph, _Item, float> {
119 119
    typedef VectorMap<_Graph, _Item, float> Map;
120 120
  };
121 121

	
122 122

	
123 123
  // double
124 124
  template <typename _Graph, typename _Item>
125 125
  struct DefaultMapSelector<_Graph, _Item, double> {
126 126
    typedef VectorMap<_Graph, _Item,  double> Map;
127 127
  };
128 128

	
129 129

	
130 130
  // long double
131 131
  template <typename _Graph, typename _Item>
132 132
  struct DefaultMapSelector<_Graph, _Item, long double> {
133 133
    typedef VectorMap<_Graph, _Item, long double> Map;
134 134
  };
135 135

	
136 136

	
137 137
  // pointer
138 138
  template <typename _Graph, typename _Item, typename _Ptr>
139 139
  struct DefaultMapSelector<_Graph, _Item, _Ptr*> {
140 140
    typedef VectorMap<_Graph, _Item, _Ptr*> Map;
141 141
  };
142 142

	
143 143
// #else
144 144

	
145 145
//   template <typename _Graph, typename _Item, typename _Value>
146 146
//   struct DefaultMapSelector {
147 147
//     typedef DebugMap<_Graph, _Item, _Value> Map;
148 148
//   };
149 149

	
150 150
// #endif
151 151

	
152 152
  // DefaultMap class
153 153
  template <typename _Graph, typename _Item, typename _Value>
154 154
  class DefaultMap
155 155
    : public DefaultMapSelector<_Graph, _Item, _Value>::Map {
156 156
    typedef typename DefaultMapSelector<_Graph, _Item, _Value>::Map Parent;
157 157

	
158 158
  public:
159 159
    typedef DefaultMap<_Graph, _Item, _Value> Map;
160
    
160

	
161 161
    typedef typename Parent::GraphType GraphType;
162 162
    typedef typename Parent::Value Value;
163 163

	
164 164
    explicit DefaultMap(const GraphType& graph) : Parent(graph) {}
165 165
    DefaultMap(const GraphType& graph, const Value& value)
166 166
      : Parent(graph, value) {}
167 167

	
168 168
    DefaultMap& operator=(const DefaultMap& cmap) {
169 169
      return operator=<DefaultMap>(cmap);
170 170
    }
171 171

	
172 172
    template <typename CMap>
173 173
    DefaultMap& operator=(const CMap& cmap) {
174 174
      Parent::operator=(cmap);
175 175
      return *this;
176 176
    }
177 177

	
178 178
  };
179 179

	
180 180
}
181 181

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

	
19 19
#ifndef LEMON_BITS_EDGE_SET_EXTENDER_H
20 20
#define LEMON_BITS_EDGE_SET_EXTENDER_H
21 21

	
22 22
#include <lemon/core.h>
23 23
#include <lemon/error.h>
24 24
#include <lemon/bits/default_map.h>
25 25
#include <lemon/bits/map_extender.h>
26 26

	
27 27
//\ingroup digraphbits
28 28
//\file
29 29
//\brief Extenders for the arc set types
30 30
namespace lemon {
31 31

	
32 32
  // \ingroup digraphbits
33 33
  //
34 34
  // \brief Extender for the ArcSets
35 35
  template <typename Base>
36 36
  class ArcSetExtender : public Base {
37 37
    typedef Base Parent;
38 38

	
39 39
  public:
40 40

	
41 41
    typedef ArcSetExtender Digraph;
42 42

	
43 43
    // Base extensions
44 44

	
45 45
    typedef typename Parent::Node Node;
46 46
    typedef typename Parent::Arc Arc;
47 47

	
48 48
    int maxId(Node) const {
49 49
      return Parent::maxNodeId();
50 50
    }
51 51

	
52 52
    int maxId(Arc) const {
53 53
      return Parent::maxArcId();
54 54
    }
55 55

	
56 56
    Node fromId(int id, Node) const {
57 57
      return Parent::nodeFromId(id);
58 58
    }
59 59

	
60 60
    Arc fromId(int id, Arc) const {
61 61
      return Parent::arcFromId(id);
62 62
    }
63 63

	
64 64
    Node oppositeNode(const Node &n, const Arc &e) const {
65 65
      if (n == Parent::source(e))
66
	return Parent::target(e);
66
        return Parent::target(e);
67 67
      else if(n==Parent::target(e))
68
	return Parent::source(e);
68
        return Parent::source(e);
69 69
      else
70
	return INVALID;
70
        return INVALID;
71 71
    }
72 72

	
73 73

	
74 74
    // Alteration notifier extensions
75 75

	
76 76
    // The arc observer registry.
77 77
    typedef AlterationNotifier<ArcSetExtender, Arc> ArcNotifier;
78 78

	
79 79
  protected:
80 80

	
81 81
    mutable ArcNotifier arc_notifier;
82 82

	
83 83
  public:
84 84

	
85 85
    using Parent::notifier;
86 86

	
87 87
    // Gives back the arc alteration notifier.
88 88
    ArcNotifier& notifier(Arc) const {
89 89
      return arc_notifier;
90 90
    }
91 91

	
92 92
    // Iterable extensions
93 93

	
94
    class NodeIt : public Node { 
94
    class NodeIt : public Node {
95 95
      const Digraph* digraph;
96 96
    public:
97 97

	
98 98
      NodeIt() {}
99 99

	
100 100
      NodeIt(Invalid i) : Node(i) { }
101 101

	
102 102
      explicit NodeIt(const Digraph& _graph) : digraph(&_graph) {
103
	_graph.first(static_cast<Node&>(*this));
103
        _graph.first(static_cast<Node&>(*this));
104 104
      }
105 105

	
106
      NodeIt(const Digraph& _graph, const Node& node) 
107
	: Node(node), digraph(&_graph) {}
106
      NodeIt(const Digraph& _graph, const Node& node)
107
        : Node(node), digraph(&_graph) {}
108 108

	
109
      NodeIt& operator++() { 
110
	digraph->next(*this);
111
	return *this; 
109
      NodeIt& operator++() {
110
        digraph->next(*this);
111
        return *this;
112 112
      }
113 113

	
114 114
    };
115 115

	
116 116

	
117
    class ArcIt : public Arc { 
117
    class ArcIt : public Arc {
118 118
      const Digraph* digraph;
119 119
    public:
120 120

	
121 121
      ArcIt() { }
122 122

	
123 123
      ArcIt(Invalid i) : Arc(i) { }
124 124

	
125 125
      explicit ArcIt(const Digraph& _graph) : digraph(&_graph) {
126
	_graph.first(static_cast<Arc&>(*this));
126
        _graph.first(static_cast<Arc&>(*this));
127 127
      }
128 128

	
129
      ArcIt(const Digraph& _graph, const Arc& e) : 
130
	Arc(e), digraph(&_graph) { }
129
      ArcIt(const Digraph& _graph, const Arc& e) :
130
        Arc(e), digraph(&_graph) { }
131 131

	
132
      ArcIt& operator++() { 
133
	digraph->next(*this);
134
	return *this; 
132
      ArcIt& operator++() {
133
        digraph->next(*this);
134
        return *this;
135 135
      }
136 136

	
137 137
    };
138 138

	
139 139

	
140
    class OutArcIt : public Arc { 
140
    class OutArcIt : public Arc {
141 141
      const Digraph* digraph;
142 142
    public:
143 143

	
144 144
      OutArcIt() { }
145 145

	
146 146
      OutArcIt(Invalid i) : Arc(i) { }
147 147

	
148
      OutArcIt(const Digraph& _graph, const Node& node) 
149
	: digraph(&_graph) {
150
	_graph.firstOut(*this, node);
148
      OutArcIt(const Digraph& _graph, const Node& node)
149
        : digraph(&_graph) {
150
        _graph.firstOut(*this, node);
151 151
      }
152 152

	
153
      OutArcIt(const Digraph& _graph, const Arc& arc) 
154
	: Arc(arc), digraph(&_graph) {}
153
      OutArcIt(const Digraph& _graph, const Arc& arc)
154
        : Arc(arc), digraph(&_graph) {}
155 155

	
156
      OutArcIt& operator++() { 
157
	digraph->nextOut(*this);
158
	return *this; 
156
      OutArcIt& operator++() {
157
        digraph->nextOut(*this);
158
        return *this;
159 159
      }
160 160

	
161 161
    };
162 162

	
163 163

	
164
    class InArcIt : public Arc { 
164
    class InArcIt : public Arc {
165 165
      const Digraph* digraph;
166 166
    public:
167 167

	
168 168
      InArcIt() { }
169 169

	
170 170
      InArcIt(Invalid i) : Arc(i) { }
171 171

	
172
      InArcIt(const Digraph& _graph, const Node& node) 
173
	: digraph(&_graph) {
174
	_graph.firstIn(*this, node);
172
      InArcIt(const Digraph& _graph, const Node& node)
173
        : digraph(&_graph) {
174
        _graph.firstIn(*this, node);
175 175
      }
176 176

	
177
      InArcIt(const Digraph& _graph, const Arc& arc) : 
178
	Arc(arc), digraph(&_graph) {}
177
      InArcIt(const Digraph& _graph, const Arc& arc) :
178
        Arc(arc), digraph(&_graph) {}
179 179

	
180
      InArcIt& operator++() { 
181
	digraph->nextIn(*this);
182
	return *this; 
180
      InArcIt& operator++() {
181
        digraph->nextIn(*this);
182
        return *this;
183 183
      }
184 184

	
185 185
    };
186 186

	
187 187
    // \brief Base node of the iterator
188 188
    //
189 189
    // Returns the base node (ie. the source in this case) of the iterator
190 190
    Node baseNode(const OutArcIt &e) const {
191 191
      return Parent::source(static_cast<const Arc&>(e));
192 192
    }
193 193
    // \brief Running node of the iterator
194 194
    //
195 195
    // Returns the running node (ie. the target in this case) of the
196 196
    // iterator
197 197
    Node runningNode(const OutArcIt &e) const {
198 198
      return Parent::target(static_cast<const Arc&>(e));
199 199
    }
200 200

	
201 201
    // \brief Base node of the iterator
202 202
    //
203 203
    // Returns the base node (ie. the target in this case) of the iterator
204 204
    Node baseNode(const InArcIt &e) const {
205 205
      return Parent::target(static_cast<const Arc&>(e));
206 206
    }
207 207
    // \brief Running node of the iterator
208 208
    //
209 209
    // Returns the running node (ie. the source in this case) of the
210 210
    // iterator
211 211
    Node runningNode(const InArcIt &e) const {
212 212
      return Parent::source(static_cast<const Arc&>(e));
213 213
    }
214 214

	
215 215
    using Parent::first;
216 216

	
217 217
    // Mappable extension
218
    
218

	
219 219
    template <typename _Value>
220
    class ArcMap 
220
    class ArcMap
221 221
      : public MapExtender<DefaultMap<Digraph, Arc, _Value> > {
222 222
      typedef MapExtender<DefaultMap<Digraph, Arc, _Value> > Parent;
223 223

	
224 224
    public:
225
      explicit ArcMap(const Digraph& _g) 
226
	: Parent(_g) {}
227
      ArcMap(const Digraph& _g, const _Value& _v) 
228
	: Parent(_g, _v) {}
225
      explicit ArcMap(const Digraph& _g)
226
        : Parent(_g) {}
227
      ArcMap(const Digraph& _g, const _Value& _v)
228
        : Parent(_g, _v) {}
229 229

	
230 230
      ArcMap& operator=(const ArcMap& cmap) {
231
	return operator=<ArcMap>(cmap);
231
        return operator=<ArcMap>(cmap);
232 232
      }
233 233

	
234 234
      template <typename CMap>
235 235
      ArcMap& operator=(const CMap& cmap) {
236 236
        Parent::operator=(cmap);
237
	return *this;
237
        return *this;
238 238
      }
239 239

	
240 240
    };
241 241

	
242 242

	
243 243
    // Alteration extension
244 244

	
245 245
    Arc addArc(const Node& from, const Node& to) {
246 246
      Arc arc = Parent::addArc(from, to);
247 247
      notifier(Arc()).add(arc);
248 248
      return arc;
249 249
    }
250
    
250

	
251 251
    void clear() {
252 252
      notifier(Arc()).clear();
253 253
      Parent::clear();
254 254
    }
255 255

	
256 256
    void erase(const Arc& arc) {
257 257
      notifier(Arc()).erase(arc);
258 258
      Parent::erase(arc);
259 259
    }
260 260

	
261 261
    ArcSetExtender() {
262 262
      arc_notifier.setContainer(*this);
263 263
    }
264 264

	
265 265
    ~ArcSetExtender() {
266 266
      arc_notifier.clear();
267 267
    }
268 268

	
269 269
  };
270 270

	
271 271

	
272 272
  // \ingroup digraphbits
273 273
  //
274 274
  // \brief Extender for the EdgeSets
275 275
  template <typename Base>
276 276
  class EdgeSetExtender : public Base {
277 277
    typedef Base Parent;
278 278

	
279 279
  public:
280 280

	
281 281
    typedef EdgeSetExtender Graph;
282 282

	
283 283
    typedef typename Parent::Node Node;
284 284
    typedef typename Parent::Arc Arc;
285 285
    typedef typename Parent::Edge Edge;
286 286

	
287 287
    int maxId(Node) const {
288 288
      return Parent::maxNodeId();
289 289
    }
290 290

	
291 291
    int maxId(Arc) const {
292 292
      return Parent::maxArcId();
293 293
    }
294 294

	
295 295
    int maxId(Edge) const {
296 296
      return Parent::maxEdgeId();
297 297
    }
298 298

	
299 299
    Node fromId(int id, Node) const {
300 300
      return Parent::nodeFromId(id);
301 301
    }
302 302

	
303 303
    Arc fromId(int id, Arc) const {
304 304
      return Parent::arcFromId(id);
305 305
    }
306 306

	
307 307
    Edge fromId(int id, Edge) const {
308 308
      return Parent::edgeFromId(id);
309 309
    }
310 310

	
311 311
    Node oppositeNode(const Node &n, const Edge &e) const {
312 312
      if( n == Parent::u(e))
313
	return Parent::v(e);
313
        return Parent::v(e);
314 314
      else if( n == Parent::v(e))
315
	return Parent::u(e);
315
        return Parent::u(e);
316 316
      else
317
	return INVALID;
317
        return INVALID;
318 318
    }
319 319

	
320 320
    Arc oppositeArc(const Arc &e) const {
321 321
      return Parent::direct(e, !Parent::direction(e));
322 322
    }
323 323

	
324 324
    using Parent::direct;
325 325
    Arc direct(const Edge &e, const Node &s) const {
326 326
      return Parent::direct(e, Parent::u(e) == s);
327 327
    }
328 328

	
329 329
    typedef AlterationNotifier<EdgeSetExtender, Arc> ArcNotifier;
330 330
    typedef AlterationNotifier<EdgeSetExtender, Edge> EdgeNotifier;
331 331

	
332 332

	
333 333
  protected:
334 334

	
335 335
    mutable ArcNotifier arc_notifier;
336 336
    mutable EdgeNotifier edge_notifier;
337 337

	
338 338
  public:
339 339

	
340 340
    using Parent::notifier;
341
    
341

	
342 342
    ArcNotifier& notifier(Arc) const {
343 343
      return arc_notifier;
344 344
    }
345 345

	
346 346
    EdgeNotifier& notifier(Edge) const {
347 347
      return edge_notifier;
348 348
    }
349 349

	
350 350

	
351
    class NodeIt : public Node { 
351
    class NodeIt : public Node {
352 352
      const Graph* graph;
353 353
    public:
354 354

	
355 355
      NodeIt() {}
356 356

	
357 357
      NodeIt(Invalid i) : Node(i) { }
358 358

	
359 359
      explicit NodeIt(const Graph& _graph) : graph(&_graph) {
360
	_graph.first(static_cast<Node&>(*this));
360
        _graph.first(static_cast<Node&>(*this));
361 361
      }
362 362

	
363
      NodeIt(const Graph& _graph, const Node& node) 
364
	: Node(node), graph(&_graph) {}
363
      NodeIt(const Graph& _graph, const Node& node)
364
        : Node(node), graph(&_graph) {}
365 365

	
366
      NodeIt& operator++() { 
367
	graph->next(*this);
368
	return *this; 
366
      NodeIt& operator++() {
367
        graph->next(*this);
368
        return *this;
369 369
      }
370 370

	
371 371
    };
372 372

	
373 373

	
374
    class ArcIt : public Arc { 
374
    class ArcIt : public Arc {
375 375
      const Graph* graph;
376 376
    public:
377 377

	
378 378
      ArcIt() { }
379 379

	
380 380
      ArcIt(Invalid i) : Arc(i) { }
381 381

	
382 382
      explicit ArcIt(const Graph& _graph) : graph(&_graph) {
383
	_graph.first(static_cast<Arc&>(*this));
383
        _graph.first(static_cast<Arc&>(*this));
384 384
      }
385 385

	
386
      ArcIt(const Graph& _graph, const Arc& e) : 
387
	Arc(e), graph(&_graph) { }
386
      ArcIt(const Graph& _graph, const Arc& e) :
387
        Arc(e), graph(&_graph) { }
388 388

	
389
      ArcIt& operator++() { 
390
	graph->next(*this);
391
	return *this; 
389
      ArcIt& operator++() {
390
        graph->next(*this);
391
        return *this;
392 392
      }
393 393

	
394 394
    };
395 395

	
396 396

	
397
    class OutArcIt : public Arc { 
397
    class OutArcIt : public Arc {
398 398
      const Graph* graph;
399 399
    public:
400 400

	
401 401
      OutArcIt() { }
402 402

	
403 403
      OutArcIt(Invalid i) : Arc(i) { }
404 404

	
405
      OutArcIt(const Graph& _graph, const Node& node) 
406
	: graph(&_graph) {
407
	_graph.firstOut(*this, node);
405
      OutArcIt(const Graph& _graph, const Node& node)
406
        : graph(&_graph) {
407
        _graph.firstOut(*this, node);
408 408
      }
409 409

	
410
      OutArcIt(const Graph& _graph, const Arc& arc) 
411
	: Arc(arc), graph(&_graph) {}
410
      OutArcIt(const Graph& _graph, const Arc& arc)
411
        : Arc(arc), graph(&_graph) {}
412 412

	
413
      OutArcIt& operator++() { 
414
	graph->nextOut(*this);
415
	return *this; 
413
      OutArcIt& operator++() {
414
        graph->nextOut(*this);
415
        return *this;
416 416
      }
417 417

	
418 418
    };
419 419

	
420 420

	
421
    class InArcIt : public Arc { 
421
    class InArcIt : public Arc {
422 422
      const Graph* graph;
423 423
    public:
424 424

	
425 425
      InArcIt() { }
426 426

	
427 427
      InArcIt(Invalid i) : Arc(i) { }
428 428

	
429
      InArcIt(const Graph& _graph, const Node& node) 
430
	: graph(&_graph) {
431
	_graph.firstIn(*this, node);
429
      InArcIt(const Graph& _graph, const Node& node)
430
        : graph(&_graph) {
431
        _graph.firstIn(*this, node);
432 432
      }
433 433

	
434
      InArcIt(const Graph& _graph, const Arc& arc) : 
435
	Arc(arc), graph(&_graph) {}
434
      InArcIt(const Graph& _graph, const Arc& arc) :
435
        Arc(arc), graph(&_graph) {}
436 436

	
437
      InArcIt& operator++() { 
438
	graph->nextIn(*this);
439
	return *this; 
437
      InArcIt& operator++() {
438
        graph->nextIn(*this);
439
        return *this;
440 440
      }
441 441

	
442 442
    };
443 443

	
444 444

	
445
    class EdgeIt : public Parent::Edge { 
445
    class EdgeIt : public Parent::Edge {
446 446
      const Graph* graph;
447 447
    public:
448 448

	
449 449
      EdgeIt() { }
450 450

	
451 451
      EdgeIt(Invalid i) : Edge(i) { }
452 452

	
453 453
      explicit EdgeIt(const Graph& _graph) : graph(&_graph) {
454
	_graph.first(static_cast<Edge&>(*this));
454
        _graph.first(static_cast<Edge&>(*this));
455 455
      }
456 456

	
457
      EdgeIt(const Graph& _graph, const Edge& e) : 
458
	Edge(e), graph(&_graph) { }
457
      EdgeIt(const Graph& _graph, const Edge& e) :
458
        Edge(e), graph(&_graph) { }
459 459

	
460
      EdgeIt& operator++() { 
461
	graph->next(*this);
462
	return *this; 
460
      EdgeIt& operator++() {
461
        graph->next(*this);
462
        return *this;
463 463
      }
464 464

	
465 465
    };
466 466

	
467 467
    class IncEdgeIt : public Parent::Edge {
468 468
      friend class EdgeSetExtender;
469 469
      const Graph* graph;
470 470
      bool direction;
471 471
    public:
472 472

	
473 473
      IncEdgeIt() { }
474 474

	
475 475
      IncEdgeIt(Invalid i) : Edge(i), direction(false) { }
476 476

	
477 477
      IncEdgeIt(const Graph& _graph, const Node &n) : graph(&_graph) {
478
	_graph.firstInc(*this, direction, n);
478
        _graph.firstInc(*this, direction, n);
479 479
      }
480 480

	
481 481
      IncEdgeIt(const Graph& _graph, const Edge &ue, const Node &n)
482
	: graph(&_graph), Edge(ue) {
483
	direction = (_graph.source(ue) == n);
482
        : graph(&_graph), Edge(ue) {
483
        direction = (_graph.source(ue) == n);
484 484
      }
485 485

	
486 486
      IncEdgeIt& operator++() {
487
	graph->nextInc(*this, direction);
488
	return *this; 
487
        graph->nextInc(*this, direction);
488
        return *this;
489 489
      }
490 490
    };
491 491

	
492 492
    // \brief Base node of the iterator
493 493
    //
494 494
    // Returns the base node (ie. the source in this case) of the iterator
495 495
    Node baseNode(const OutArcIt &e) const {
496 496
      return Parent::source(static_cast<const Arc&>(e));
497 497
    }
498 498
    // \brief Running node of the iterator
499 499
    //
500 500
    // Returns the running node (ie. the target in this case) of the
501 501
    // iterator
502 502
    Node runningNode(const OutArcIt &e) const {
503 503
      return Parent::target(static_cast<const Arc&>(e));
504 504
    }
505 505

	
506 506
    // \brief Base node of the iterator
507 507
    //
508 508
    // Returns the base node (ie. the target in this case) of the iterator
509 509
    Node baseNode(const InArcIt &e) const {
510 510
      return Parent::target(static_cast<const Arc&>(e));
511 511
    }
512 512
    // \brief Running node of the iterator
513 513
    //
514 514
    // Returns the running node (ie. the source in this case) of the
515 515
    // iterator
516 516
    Node runningNode(const InArcIt &e) const {
517 517
      return Parent::source(static_cast<const Arc&>(e));
518 518
    }
519 519

	
520 520
    // Base node of the iterator
521 521
    //
522 522
    // Returns the base node of the iterator
523 523
    Node baseNode(const IncEdgeIt &e) const {
524 524
      return e.direction ? u(e) : v(e);
525 525
    }
526 526
    // Running node of the iterator
527 527
    //
528 528
    // Returns the running node of the iterator
529 529
    Node runningNode(const IncEdgeIt &e) const {
530 530
      return e.direction ? v(e) : u(e);
531 531
    }
532 532

	
533 533

	
534 534
    template <typename _Value>
535
    class ArcMap 
535
    class ArcMap
536 536
      : public MapExtender<DefaultMap<Graph, Arc, _Value> > {
537 537
      typedef MapExtender<DefaultMap<Graph, Arc, _Value> > Parent;
538 538

	
539 539
    public:
540
      explicit ArcMap(const Graph& _g) 
541
	: Parent(_g) {}
542
      ArcMap(const Graph& _g, const _Value& _v) 
543
	: Parent(_g, _v) {}
540
      explicit ArcMap(const Graph& _g)
541
        : Parent(_g) {}
542
      ArcMap(const Graph& _g, const _Value& _v)
543
        : Parent(_g, _v) {}
544 544

	
545 545
      ArcMap& operator=(const ArcMap& cmap) {
546
	return operator=<ArcMap>(cmap);
546
        return operator=<ArcMap>(cmap);
547 547
      }
548 548

	
549 549
      template <typename CMap>
550 550
      ArcMap& operator=(const CMap& cmap) {
551 551
        Parent::operator=(cmap);
552
	return *this;
552
        return *this;
553 553
      }
554 554

	
555 555
    };
556 556

	
557 557

	
558 558
    template <typename _Value>
559
    class EdgeMap 
559
    class EdgeMap
560 560
      : public MapExtender<DefaultMap<Graph, Edge, _Value> > {
561 561
      typedef MapExtender<DefaultMap<Graph, Edge, _Value> > Parent;
562 562

	
563 563
    public:
564
      explicit EdgeMap(const Graph& _g) 
565
	: Parent(_g) {}
564
      explicit EdgeMap(const Graph& _g)
565
        : Parent(_g) {}
566 566

	
567
      EdgeMap(const Graph& _g, const _Value& _v) 
568
	: Parent(_g, _v) {}
567
      EdgeMap(const Graph& _g, const _Value& _v)
568
        : Parent(_g, _v) {}
569 569

	
570 570
      EdgeMap& operator=(const EdgeMap& cmap) {
571
	return operator=<EdgeMap>(cmap);
571
        return operator=<EdgeMap>(cmap);
572 572
      }
573 573

	
574 574
      template <typename CMap>
575 575
      EdgeMap& operator=(const CMap& cmap) {
576 576
        Parent::operator=(cmap);
577
	return *this;
577
        return *this;
578 578
      }
579 579

	
580 580
    };
581 581

	
582 582

	
583 583
    // Alteration extension
584 584

	
585 585
    Edge addEdge(const Node& from, const Node& to) {
586 586
      Edge edge = Parent::addEdge(from, to);
587 587
      notifier(Edge()).add(edge);
588 588
      std::vector<Arc> arcs;
589 589
      arcs.push_back(Parent::direct(edge, true));
590 590
      arcs.push_back(Parent::direct(edge, false));
591 591
      notifier(Arc()).add(arcs);
592 592
      return edge;
593 593
    }
594
    
594

	
595 595
    void clear() {
596 596
      notifier(Arc()).clear();
597 597
      notifier(Edge()).clear();
598 598
      Parent::clear();
599 599
    }
600 600

	
601 601
    void erase(const Edge& edge) {
602 602
      std::vector<Arc> arcs;
603 603
      arcs.push_back(Parent::direct(edge, true));
604 604
      arcs.push_back(Parent::direct(edge, false));
605 605
      notifier(Arc()).erase(arcs);
606 606
      notifier(Edge()).erase(edge);
607 607
      Parent::erase(edge);
608 608
    }
609 609

	
610 610

	
611 611
    EdgeSetExtender() {
612 612
      arc_notifier.setContainer(*this);
613 613
      edge_notifier.setContainer(*this);
614 614
    }
615 615

	
616 616
    ~EdgeSetExtender() {
617 617
      edge_notifier.clear();
618 618
      arc_notifier.clear();
619 619
    }
620
    
620

	
621 621
  };
622 622

	
623 623
}
624 624

	
625 625
#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
 * Copyright (C) 2003-2008
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_BITS_SOLVER_BITS_H
20 20
#define LEMON_BITS_SOLVER_BITS_H
21 21

	
22 22
#include <vector>
23 23

	
24 24
namespace lemon {
25 25

	
26 26
  namespace _solver_bits {
27 27

	
28 28
    class VarIndex {
29 29
    private:
30 30
      struct ItemT {
31 31
        int prev, next;
32 32
        int index;
33 33
      };
34 34
      std::vector<ItemT> items;
35 35
      int first_item, last_item, first_free_item;
36 36

	
37 37
      std::vector<int> cross;
38 38

	
39 39
    public:
40 40

	
41 41
      VarIndex()
42 42
        : first_item(-1), last_item(-1), first_free_item(-1) {
43 43
      }
44 44

	
45 45
      void clear() {
46 46
        first_item = -1;
47 47
        first_free_item = -1;
48 48
        items.clear();
49 49
        cross.clear();
50 50
      }
51 51

	
52 52
      int addIndex(int idx) {
53 53
        int n;
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
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
///\file
20 20
///\brief Some basic non-inline functions and static global data.
21 21

	
22 22
#include<lemon/bits/windows.h>
23 23

	
24 24
#ifdef WIN32
25 25
#ifndef WIN32_LEAN_AND_MEAN
26 26
#define WIN32_LEAN_AND_MEAN
27 27
#endif
28 28
#ifndef NOMINMAX
29 29
#define NOMINMAX
30 30
#endif
31 31
#ifdef UNICODE
32 32
#undef UNICODE
33 33
#endif
34 34
#include <windows.h>
35 35
#ifdef LOCALE_INVARIANT
36 36
#define MY_LOCALE LOCALE_INVARIANT
37 37
#else
38 38
#define MY_LOCALE LOCALE_NEUTRAL
39 39
#endif
40 40
#else
41 41
#include <unistd.h>
42 42
#include <ctime>
43 43
#include <sys/times.h>
44 44
#include <sys/time.h>
45 45
#endif
46 46

	
47 47
#include <cmath>
48 48
#include <sstream>
49 49

	
50 50
namespace lemon {
51 51
  namespace bits {
52 52
    void getWinProcTimes(double &rtime,
53 53
                         double &utime, double &stime,
54 54
                         double &cutime, double &cstime)
55 55
    {
56 56
#ifdef WIN32
57 57
      static const double ch = 4294967296.0e-7;
58 58
      static const double cl = 1.0e-7;
59 59

	
60 60
      FILETIME system;
61 61
      GetSystemTimeAsFileTime(&system);
62 62
      rtime = ch * system.dwHighDateTime + cl * system.dwLowDateTime;
63 63

	
64 64
      FILETIME create, exit, kernel, user;
65 65
      if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
66 66
        utime = ch * user.dwHighDateTime + cl * user.dwLowDateTime;
67 67
        stime = ch * kernel.dwHighDateTime + cl * kernel.dwLowDateTime;
68 68
        cutime = 0;
69 69
        cstime = 0;
70 70
      } else {
71 71
        rtime = 0;
72 72
        utime = 0;
73 73
        stime = 0;
74 74
        cutime = 0;
75 75
        cstime = 0;
76 76
      }
77 77
#else
78 78
      timeval tv;
79 79
      gettimeofday(&tv, 0);
80 80
      rtime=tv.tv_sec+double(tv.tv_usec)/1e6;
81 81

	
82 82
      tms ts;
83 83
      double tck=sysconf(_SC_CLK_TCK);
84 84
      times(&ts);
85 85
      utime=ts.tms_utime/tck;
86 86
      stime=ts.tms_stime/tck;
87 87
      cutime=ts.tms_cutime/tck;
88 88
      cstime=ts.tms_cstime/tck;
89 89
#endif
90 90
    }
91 91

	
92 92
    std::string getWinFormattedDate()
93 93
    {
94 94
      std::ostringstream os;
95 95
#ifdef WIN32
96 96
      SYSTEMTIME time;
97 97
      GetSystemTime(&time);
98 98
      char buf1[11], buf2[9], buf3[5];
99
	  if (GetDateFormat(MY_LOCALE, 0, &time,
99
          if (GetDateFormat(MY_LOCALE, 0, &time,
100 100
                        ("ddd MMM dd"), buf1, 11) &&
101 101
          GetTimeFormat(MY_LOCALE, 0, &time,
102 102
                        ("HH':'mm':'ss"), buf2, 9) &&
103 103
          GetDateFormat(MY_LOCALE, 0, &time,
104 104
                        ("yyyy"), buf3, 5)) {
105 105
        os << buf1 << ' ' << buf2 << ' ' << buf3;
106 106
      }
107 107
      else os << "unknown";
108 108
#else
109 109
      timeval tv;
110 110
      gettimeofday(&tv, 0);
111 111

	
112 112
      char cbuf[26];
113 113
      ctime_r(&tv.tv_sec,cbuf);
114 114
      os << cbuf;
115 115
#endif
116 116
      return os.str();
117 117
    }
118 118

	
119 119
    int getWinRndSeed()
120 120
    {
121 121
#ifdef WIN32
122 122
      FILETIME time;
123 123
      GetSystemTimeAsFileTime(&time);
124 124
      return GetCurrentProcessId() + time.dwHighDateTime + time.dwLowDateTime;
125 125
#else
126 126
      timeval tv;
127 127
      gettimeofday(&tv, 0);
128 128
      return getpid() + tv.tv_sec + tv.tv_usec;
129 129
#endif
130 130
    }
131 131
  }
132 132
}
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
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_BUCKET_HEAP_H
20 20
#define LEMON_BUCKET_HEAP_H
21 21

	
22 22
///\ingroup heaps
23 23
///\file
24 24
///\brief Bucket heap implementation.
25 25

	
26 26
#include <vector>
27 27
#include <utility>
28 28
#include <functional>
29 29

	
30 30
namespace lemon {
31 31

	
32 32
  namespace _bucket_heap_bits {
33 33

	
34 34
    template <bool MIN>
35 35
    struct DirectionTraits {
36 36
      static bool less(int left, int right) {
37 37
        return left < right;
38 38
      }
39 39
      static void increase(int& value) {
40 40
        ++value;
41 41
      }
42 42
    };
43 43

	
44 44
    template <>
45 45
    struct DirectionTraits<false> {
46 46
      static bool less(int left, int right) {
47 47
        return left > right;
48 48
      }
49 49
      static void increase(int& value) {
50 50
        --value;
51 51
      }
52 52
    };
53 53

	
... ...
@@ -339,97 +339,97 @@
339 339
    /// \param i The item.
340 340
    /// \param st The state. It should not be \c IN_HEAP.
341 341
    void state(const Item& i, State st) {
342 342
      switch (st) {
343 343
      case POST_HEAP:
344 344
      case PRE_HEAP:
345 345
        if (state(i) == IN_HEAP) {
346 346
          erase(i);
347 347
        }
348 348
        _iim[i] = st;
349 349
        break;
350 350
      case IN_HEAP:
351 351
        break;
352 352
      }
353 353
    }
354 354

	
355 355
  private:
356 356

	
357 357
    struct BucketItem {
358 358
      BucketItem(const Item& _item, int _value)
359 359
        : item(_item), value(_value) {}
360 360

	
361 361
      Item item;
362 362
      int value;
363 363

	
364 364
      int prev, next;
365 365
    };
366 366

	
367 367
    ItemIntMap& _iim;
368 368
    std::vector<int> _first;
369 369
    std::vector<BucketItem> _data;
370 370
    mutable int _minimum;
371 371

	
372 372
  }; // class BucketHeap
373 373

	
374 374
  /// \ingroup heaps
375 375
  ///
376 376
  /// \brief Simplified bucket heap data structure.
377 377
  ///
378 378
  /// This class implements a simplified \e bucket \e heap data
379 379
  /// structure. It does not provide some functionality, but it is
380 380
  /// faster and simpler than BucketHeap. The main difference is
381 381
  /// that BucketHeap stores a doubly-linked list for each key while
382 382
  /// this class stores only simply-linked lists. It supports erasing
383 383
  /// only for the item having minimum priority and it does not support
384 384
  /// key increasing and decreasing.
385 385
  ///
386 386
  /// Note that this implementation does not conform to the
387
  /// \ref concepts::Heap "heap concept" due to the lack of some 
387
  /// \ref concepts::Heap "heap concept" due to the lack of some
388 388
  /// functionality.
389 389
  ///
390 390
  /// \tparam IM A read-writable item map with \c int values, used
391 391
  /// internally to handle the cross references.
392 392
  /// \tparam MIN Indicate if the heap is a \e min-heap or a \e max-heap.
393 393
  /// The default is \e min-heap. If this parameter is set to \c false,
394 394
  /// then the comparison is reversed, so the top(), prio() and pop()
395 395
  /// functions deal with the item having maximum priority instead of the
396 396
  /// minimum.
397 397
  ///
398 398
  /// \sa BucketHeap
399 399
  template <typename IM, bool MIN = true >
400 400
  class SimpleBucketHeap {
401 401

	
402 402
  public:
403 403

	
404 404
    /// Type of the item-int map.
405 405
    typedef IM ItemIntMap;
406 406
    /// Type of the priorities.
407 407
    typedef int Prio;
408 408
    /// Type of the items stored in the heap.
409 409
    typedef typename ItemIntMap::Key Item;
410 410
    /// Type of the item-priority pairs.
411 411
    typedef std::pair<Item,Prio> Pair;
412 412

	
413 413
  private:
414 414

	
415 415
    typedef _bucket_heap_bits::DirectionTraits<MIN> Direction;
416 416

	
417 417
  public:
418 418

	
419 419
    /// \brief Type to represent the states of the items.
420 420
    ///
421 421
    /// Each item has a state associated to it. It can be "in heap",
422 422
    /// "pre-heap" or "post-heap". The latter two are indifferent from the
423 423
    /// heap's point of view, but may be useful to the user.
424 424
    ///
425 425
    /// The item-int map must be initialized in such way that it assigns
426 426
    /// \c PRE_HEAP (<tt>-1</tt>) to any element to be put in the heap.
427 427
    enum State {
428 428
      IN_HEAP = 0,    ///< = 0.
429 429
      PRE_HEAP = -1,  ///< = -1.
430 430
      POST_HEAP = -2  ///< = -2.
431 431
    };
432 432

	
433 433
  public:
434 434

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

	
22 22
/// \ingroup min_cost_flow_algs
23 23
///
24 24
/// \file
25 25
/// \brief Capacity Scaling algorithm for finding a minimum cost flow.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <lemon/core.h>
30 30
#include <lemon/bin_heap.h>
31 31

	
32 32
namespace lemon {
33 33

	
34 34
  /// \brief Default traits class of CapacityScaling algorithm.
35 35
  ///
36 36
  /// Default traits class of CapacityScaling algorithm.
37 37
  /// \tparam GR Digraph type.
38 38
  /// \tparam V The number type used for flow amounts, capacity bounds
39 39
  /// and supply values. By default it is \c int.
40 40
  /// \tparam C The number type used for costs and potentials.
41 41
  /// By default it is the same as \c V.
42 42
  template <typename GR, typename V = int, typename C = V>
43 43
  struct CapacityScalingDefaultTraits
44 44
  {
45 45
    /// The type of the digraph
46 46
    typedef GR Digraph;
47 47
    /// The type of the flow amounts, capacity bounds and supply values
48 48
    typedef V Value;
49 49
    /// The type of the arc costs
50 50
    typedef C Cost;
51 51

	
52 52
    /// \brief The type of the heap used for internal Dijkstra computations.
53 53
    ///
... ...
@@ -88,178 +88,178 @@
88 88
  ///
89 89
  /// \warning Both number types must be signed and all input data must
90 90
  /// be integer.
91 91
  /// \warning This algorithm does not support negative costs for such
92 92
  /// arcs that have infinite upper bound.
93 93
#ifdef DOXYGEN
94 94
  template <typename GR, typename V, typename C, typename TR>
95 95
#else
96 96
  template < typename GR, typename V = int, typename C = V,
97 97
             typename TR = CapacityScalingDefaultTraits<GR, V, C> >
98 98
#endif
99 99
  class CapacityScaling
100 100
  {
101 101
  public:
102 102

	
103 103
    /// The type of the digraph
104 104
    typedef typename TR::Digraph Digraph;
105 105
    /// The type of the flow amounts, capacity bounds and supply values
106 106
    typedef typename TR::Value Value;
107 107
    /// The type of the arc costs
108 108
    typedef typename TR::Cost Cost;
109 109

	
110 110
    /// The type of the heap used for internal Dijkstra computations
111 111
    typedef typename TR::Heap Heap;
112 112

	
113 113
    /// The \ref CapacityScalingDefaultTraits "traits class" of the algorithm
114 114
    typedef TR Traits;
115 115

	
116 116
  public:
117 117

	
118 118
    /// \brief Problem type constants for the \c run() function.
119 119
    ///
120 120
    /// Enum type containing the problem type constants that can be
121 121
    /// returned by the \ref run() function of the algorithm.
122 122
    enum ProblemType {
123 123
      /// The problem has no feasible solution (flow).
124 124
      INFEASIBLE,
125 125
      /// The problem has optimal solution (i.e. it is feasible and
126 126
      /// bounded), and the algorithm has found optimal flow and node
127 127
      /// potentials (primal and dual solutions).
128 128
      OPTIMAL,
129 129
      /// The digraph contains an arc of negative cost and infinite
130 130
      /// upper bound. It means that the objective function is unbounded
131 131
      /// on that arc, however, note that it could actually be bounded
132 132
      /// over the feasible flows, but this algroithm cannot handle
133 133
      /// these cases.
134 134
      UNBOUNDED
135 135
    };
136
  
136

	
137 137
  private:
138 138

	
139 139
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
140 140

	
141 141
    typedef std::vector<int> IntVector;
142 142
    typedef std::vector<Value> ValueVector;
143 143
    typedef std::vector<Cost> CostVector;
144 144
    typedef std::vector<char> BoolVector;
145 145
    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
146 146

	
147 147
  private:
148 148

	
149 149
    // Data related to the underlying digraph
150 150
    const GR &_graph;
151 151
    int _node_num;
152 152
    int _arc_num;
153 153
    int _res_arc_num;
154 154
    int _root;
155 155

	
156 156
    // Parameters of the problem
157 157
    bool _have_lower;
158 158
    Value _sum_supply;
159 159

	
160 160
    // Data structures for storing the digraph
161 161
    IntNodeMap _node_id;
162 162
    IntArcMap _arc_idf;
163 163
    IntArcMap _arc_idb;
164 164
    IntVector _first_out;
165 165
    BoolVector _forward;
166 166
    IntVector _source;
167 167
    IntVector _target;
168 168
    IntVector _reverse;
169 169

	
170 170
    // Node and arc data
171 171
    ValueVector _lower;
172 172
    ValueVector _upper;
173 173
    CostVector _cost;
174 174
    ValueVector _supply;
175 175

	
176 176
    ValueVector _res_cap;
177 177
    CostVector _pi;
178 178
    ValueVector _excess;
179 179
    IntVector _excess_nodes;
180 180
    IntVector _deficit_nodes;
181 181

	
182 182
    Value _delta;
183 183
    int _factor;
184 184
    IntVector _pred;
185 185

	
186 186
  public:
187
  
187

	
188 188
    /// \brief Constant for infinite upper bounds (capacities).
189 189
    ///
190 190
    /// Constant for infinite upper bounds (capacities).
191 191
    /// It is \c std::numeric_limits<Value>::infinity() if available,
192 192
    /// \c std::numeric_limits<Value>::max() otherwise.
193 193
    const Value INF;
194 194

	
195 195
  private:
196 196

	
197 197
    // Special implementation of the Dijkstra algorithm for finding
198 198
    // shortest paths in the residual network of the digraph with
199 199
    // respect to the reduced arc costs and modifying the node
200 200
    // potentials according to the found distance labels.
201 201
    class ResidualDijkstra
202 202
    {
203 203
    private:
204 204

	
205 205
      int _node_num;
206 206
      bool _geq;
207 207
      const IntVector &_first_out;
208 208
      const IntVector &_target;
209 209
      const CostVector &_cost;
210 210
      const ValueVector &_res_cap;
211 211
      const ValueVector &_excess;
212 212
      CostVector &_pi;
213 213
      IntVector &_pred;
214
      
214

	
215 215
      IntVector _proc_nodes;
216 216
      CostVector _dist;
217
      
217

	
218 218
    public:
219 219

	
220 220
      ResidualDijkstra(CapacityScaling& cs) :
221 221
        _node_num(cs._node_num), _geq(cs._sum_supply < 0),
222 222
        _first_out(cs._first_out), _target(cs._target), _cost(cs._cost),
223 223
        _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi),
224 224
        _pred(cs._pred), _dist(cs._node_num)
225 225
      {}
226 226

	
227 227
      int run(int s, Value delta = 1) {
228 228
        RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
229 229
        Heap heap(heap_cross_ref);
230 230
        heap.push(s, 0);
231 231
        _pred[s] = -1;
232 232
        _proc_nodes.clear();
233 233

	
234 234
        // Process nodes
235 235
        while (!heap.empty() && _excess[heap.top()] > -delta) {
236 236
          int u = heap.top(), v;
237 237
          Cost d = heap.prio() + _pi[u], dn;
238 238
          _dist[u] = heap.prio();
239 239
          _proc_nodes.push_back(u);
240 240
          heap.pop();
241 241

	
242 242
          // Traverse outgoing residual arcs
243 243
          int last_out = _geq ? _first_out[u+1] : _first_out[u+1] - 1;
244 244
          for (int a = _first_out[u]; a != last_out; ++a) {
245 245
            if (_res_cap[a] < delta) continue;
246 246
            v = _target[a];
247 247
            switch (heap.state(v)) {
248 248
              case Heap::PRE_HEAP:
249 249
                heap.push(v, d + _cost[a] - _pi[v]);
250 250
                _pred[v] = a;
251 251
                break;
252 252
              case Heap::IN_HEAP:
253 253
                dn = d + _cost[a] - _pi[v];
254 254
                if (dn < heap[v]) {
255 255
                  heap.decrease(v, dn);
256 256
                  _pred[v] = a;
257 257
                }
258 258
                break;
259 259
              case Heap::POST_HEAP:
260 260
                break;
261 261
            }
262 262
          }
263 263
        }
264 264
        if (heap.empty()) return -1;
265 265

	
... ...
@@ -394,97 +394,97 @@
394 394
      }
395 395
      return *this;
396 396
    }
397 397

	
398 398
    /// \brief Set the supply values of the nodes.
399 399
    ///
400 400
    /// This function sets the supply values of the nodes.
401 401
    /// If neither this function nor \ref stSupply() is used before
402 402
    /// calling \ref run(), the supply of each node will be set to zero.
403 403
    ///
404 404
    /// \param map A node map storing the supply values.
405 405
    /// Its \c Value type must be convertible to the \c Value type
406 406
    /// of the algorithm.
407 407
    ///
408 408
    /// \return <tt>(*this)</tt>
409 409
    template<typename SupplyMap>
410 410
    CapacityScaling& supplyMap(const SupplyMap& map) {
411 411
      for (NodeIt n(_graph); n != INVALID; ++n) {
412 412
        _supply[_node_id[n]] = map[n];
413 413
      }
414 414
      return *this;
415 415
    }
416 416

	
417 417
    /// \brief Set single source and target nodes and a supply value.
418 418
    ///
419 419
    /// This function sets a single source node and a single target node
420 420
    /// and the required flow value.
421 421
    /// If neither this function nor \ref supplyMap() is used before
422 422
    /// calling \ref run(), the supply of each node will be set to zero.
423 423
    ///
424 424
    /// Using this function has the same effect as using \ref supplyMap()
425 425
    /// with such a map in which \c k is assigned to \c s, \c -k is
426 426
    /// assigned to \c t and all other nodes have zero supply value.
427 427
    ///
428 428
    /// \param s The source node.
429 429
    /// \param t The target node.
430 430
    /// \param k The required amount of flow from node \c s to node \c t
431 431
    /// (i.e. the supply of \c s and the demand of \c t).
432 432
    ///
433 433
    /// \return <tt>(*this)</tt>
434 434
    CapacityScaling& stSupply(const Node& s, const Node& t, Value k) {
435 435
      for (int i = 0; i != _node_num; ++i) {
436 436
        _supply[i] = 0;
437 437
      }
438 438
      _supply[_node_id[s]] =  k;
439 439
      _supply[_node_id[t]] = -k;
440 440
      return *this;
441 441
    }
442
    
442

	
443 443
    /// @}
444 444

	
445 445
    /// \name Execution control
446 446
    /// The algorithm can be executed using \ref run().
447 447

	
448 448
    /// @{
449 449

	
450 450
    /// \brief Run the algorithm.
451 451
    ///
452 452
    /// This function runs the algorithm.
453 453
    /// The paramters can be specified using functions \ref lowerMap(),
454 454
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
455 455
    /// For example,
456 456
    /// \code
457 457
    ///   CapacityScaling<ListDigraph> cs(graph);
458 458
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
459 459
    ///     .supplyMap(sup).run();
460 460
    /// \endcode
461 461
    ///
462 462
    /// This function can be called more than once. All the given parameters
463 463
    /// are kept for the next call, unless \ref resetParams() or \ref reset()
464 464
    /// is used, thus only the modified parameters have to be set again.
465 465
    /// If the underlying digraph was also modified after the construction
466 466
    /// of the class (or the last \ref reset() call), then the \ref reset()
467 467
    /// function must be called.
468 468
    ///
469 469
    /// \param factor The capacity scaling factor. It must be larger than
470 470
    /// one to use scaling. If it is less or equal to one, then scaling
471 471
    /// will be disabled.
472 472
    ///
473 473
    /// \return \c INFEASIBLE if no feasible flow exists,
474 474
    /// \n \c OPTIMAL if the problem has optimal solution
475 475
    /// (i.e. it is feasible and bounded), and the algorithm has found
476 476
    /// optimal flow and node potentials (primal and dual solutions),
477 477
    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
478 478
    /// and infinite upper bound. It means that the objective function
479 479
    /// is unbounded on that arc, however, note that it could actually be
480 480
    /// bounded over the feasible flows, but this algroithm cannot handle
481 481
    /// these cases.
482 482
    ///
483 483
    /// \see ProblemType
484 484
    /// \see resetParams(), reset()
485 485
    ProblemType run(int factor = 4) {
486 486
      _factor = factor;
487 487
      ProblemType pt = init();
488 488
      if (pt != OPTIMAL) return pt;
489 489
      return start();
490 490
    }
... ...
@@ -530,141 +530,141 @@
530 530
        _supply[i] = 0;
531 531
      }
532 532
      for (int j = 0; j != _res_arc_num; ++j) {
533 533
        _lower[j] = 0;
534 534
        _upper[j] = INF;
535 535
        _cost[j] = _forward[j] ? 1 : -1;
536 536
      }
537 537
      _have_lower = false;
538 538
      return *this;
539 539
    }
540 540

	
541 541
    /// \brief Reset the internal data structures and all the parameters
542 542
    /// that have been given before.
543 543
    ///
544 544
    /// This function resets the internal data structures and all the
545 545
    /// paramaters that have been given before using functions \ref lowerMap(),
546 546
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
547 547
    ///
548 548
    /// It is useful for multiple \ref run() calls. Basically, all the given
549 549
    /// parameters are kept for the next \ref run() call, unless
550 550
    /// \ref resetParams() or \ref reset() is used.
551 551
    /// If the underlying digraph was also modified after the construction
552 552
    /// of the class or the last \ref reset() call, then the \ref reset()
553 553
    /// function must be used, otherwise \ref resetParams() is sufficient.
554 554
    ///
555 555
    /// See \ref resetParams() for examples.
556 556
    ///
557 557
    /// \return <tt>(*this)</tt>
558 558
    ///
559 559
    /// \see resetParams(), run()
560 560
    CapacityScaling& reset() {
561 561
      // Resize vectors
562 562
      _node_num = countNodes(_graph);
563 563
      _arc_num = countArcs(_graph);
564 564
      _res_arc_num = 2 * (_arc_num + _node_num);
565 565
      _root = _node_num;
566 566
      ++_node_num;
567 567

	
568 568
      _first_out.resize(_node_num + 1);
569 569
      _forward.resize(_res_arc_num);
570 570
      _source.resize(_res_arc_num);
571 571
      _target.resize(_res_arc_num);
572 572
      _reverse.resize(_res_arc_num);
573 573

	
574 574
      _lower.resize(_res_arc_num);
575 575
      _upper.resize(_res_arc_num);
576 576
      _cost.resize(_res_arc_num);
577 577
      _supply.resize(_node_num);
578
      
578

	
579 579
      _res_cap.resize(_res_arc_num);
580 580
      _pi.resize(_node_num);
581 581
      _excess.resize(_node_num);
582 582
      _pred.resize(_node_num);
583 583

	
584 584
      // Copy the graph
585 585
      int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1;
586 586
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
587 587
        _node_id[n] = i;
588 588
      }
589 589
      i = 0;
590 590
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
591 591
        _first_out[i] = j;
592 592
        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
593 593
          _arc_idf[a] = j;
594 594
          _forward[j] = true;
595 595
          _source[j] = i;
596 596
          _target[j] = _node_id[_graph.runningNode(a)];
597 597
        }
598 598
        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
599 599
          _arc_idb[a] = j;
600 600
          _forward[j] = false;
601 601
          _source[j] = i;
602 602
          _target[j] = _node_id[_graph.runningNode(a)];
603 603
        }
604 604
        _forward[j] = false;
605 605
        _source[j] = i;
606 606
        _target[j] = _root;
607 607
        _reverse[j] = k;
608 608
        _forward[k] = true;
609 609
        _source[k] = _root;
610 610
        _target[k] = i;
611 611
        _reverse[k] = j;
612 612
        ++j; ++k;
613 613
      }
614 614
      _first_out[i] = j;
615 615
      _first_out[_node_num] = k;
616 616
      for (ArcIt a(_graph); a != INVALID; ++a) {
617 617
        int fi = _arc_idf[a];
618 618
        int bi = _arc_idb[a];
619 619
        _reverse[fi] = bi;
620 620
        _reverse[bi] = fi;
621 621
      }
622
      
622

	
623 623
      // Reset parameters
624 624
      resetParams();
625 625
      return *this;
626 626
    }
627 627

	
628 628
    /// @}
629 629

	
630 630
    /// \name Query Functions
631 631
    /// The results of the algorithm can be obtained using these
632 632
    /// functions.\n
633 633
    /// The \ref run() function must be called before using them.
634 634

	
635 635
    /// @{
636 636

	
637 637
    /// \brief Return the total cost of the found flow.
638 638
    ///
639 639
    /// This function returns the total cost of the found flow.
640 640
    /// Its complexity is O(e).
641 641
    ///
642 642
    /// \note The return type of the function can be specified as a
643 643
    /// template parameter. For example,
644 644
    /// \code
645 645
    ///   cs.totalCost<double>();
646 646
    /// \endcode
647 647
    /// It is useful if the total cost cannot be stored in the \c Cost
648 648
    /// type of the algorithm, which is the default return type of the
649 649
    /// function.
650 650
    ///
651 651
    /// \pre \ref run() must be called before using this function.
652 652
    template <typename Number>
653 653
    Number totalCost() const {
654 654
      Number c = 0;
655 655
      for (ArcIt a(_graph); a != INVALID; ++a) {
656 656
        int i = _arc_idb[a];
657 657
        c += static_cast<Number>(_res_cap[i]) *
658 658
             (-static_cast<Number>(_cost[i]));
659 659
      }
660 660
      return c;
661 661
    }
662 662

	
663 663
#ifndef DOXYGEN
664 664
    Cost totalCost() const {
665 665
      return totalCost<Cost>();
666 666
    }
667 667
#endif
668 668

	
669 669
    /// \brief Return the flow on the given arc.
670 670
    ///
... ...
@@ -683,215 +683,215 @@
683 683
    ///
684 684
    /// \pre \ref run() must be called before using this function.
685 685
    template <typename FlowMap>
686 686
    void flowMap(FlowMap &map) const {
687 687
      for (ArcIt a(_graph); a != INVALID; ++a) {
688 688
        map.set(a, _res_cap[_arc_idb[a]]);
689 689
      }
690 690
    }
691 691

	
692 692
    /// \brief Return the potential (dual value) of the given node.
693 693
    ///
694 694
    /// This function returns the potential (dual value) of the
695 695
    /// given node.
696 696
    ///
697 697
    /// \pre \ref run() must be called before using this function.
698 698
    Cost potential(const Node& n) const {
699 699
      return _pi[_node_id[n]];
700 700
    }
701 701

	
702 702
    /// \brief Return the potential map (the dual solution).
703 703
    ///
704 704
    /// This function copies the potential (dual value) of each node
705 705
    /// into the given map.
706 706
    /// The \c Cost type of the algorithm must be convertible to the
707 707
    /// \c Value type of the map.
708 708
    ///
709 709
    /// \pre \ref run() must be called before using this function.
710 710
    template <typename PotentialMap>
711 711
    void potentialMap(PotentialMap &map) const {
712 712
      for (NodeIt n(_graph); n != INVALID; ++n) {
713 713
        map.set(n, _pi[_node_id[n]]);
714 714
      }
715 715
    }
716 716

	
717 717
    /// @}
718 718

	
719 719
  private:
720 720

	
721 721
    // Initialize the algorithm
722 722
    ProblemType init() {
723 723
      if (_node_num <= 1) return INFEASIBLE;
724 724

	
725 725
      // Check the sum of supply values
726 726
      _sum_supply = 0;
727 727
      for (int i = 0; i != _root; ++i) {
728 728
        _sum_supply += _supply[i];
729 729
      }
730 730
      if (_sum_supply > 0) return INFEASIBLE;
731
      
731

	
732 732
      // Initialize vectors
733 733
      for (int i = 0; i != _root; ++i) {
734 734
        _pi[i] = 0;
735 735
        _excess[i] = _supply[i];
736 736
      }
737 737

	
738 738
      // Remove non-zero lower bounds
739 739
      const Value MAX = std::numeric_limits<Value>::max();
740 740
      int last_out;
741 741
      if (_have_lower) {
742 742
        for (int i = 0; i != _root; ++i) {
743 743
          last_out = _first_out[i+1];
744 744
          for (int j = _first_out[i]; j != last_out; ++j) {
745 745
            if (_forward[j]) {
746 746
              Value c = _lower[j];
747 747
              if (c >= 0) {
748 748
                _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF;
749 749
              } else {
750 750
                _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF;
751 751
              }
752 752
              _excess[i] -= c;
753 753
              _excess[_target[j]] += c;
754 754
            } else {
755 755
              _res_cap[j] = 0;
756 756
            }
757 757
          }
758 758
        }
759 759
      } else {
760 760
        for (int j = 0; j != _res_arc_num; ++j) {
761 761
          _res_cap[j] = _forward[j] ? _upper[j] : 0;
762 762
        }
763 763
      }
764 764

	
765 765
      // Handle negative costs
766 766
      for (int i = 0; i != _root; ++i) {
767 767
        last_out = _first_out[i+1] - 1;
768 768
        for (int j = _first_out[i]; j != last_out; ++j) {
769 769
          Value rc = _res_cap[j];
770 770
          if (_cost[j] < 0 && rc > 0) {
771 771
            if (rc >= MAX) return UNBOUNDED;
772 772
            _excess[i] -= rc;
773 773
            _excess[_target[j]] += rc;
774 774
            _res_cap[j] = 0;
775 775
            _res_cap[_reverse[j]] += rc;
776 776
          }
777 777
        }
778 778
      }
779
      
779

	
780 780
      // Handle GEQ supply type
781 781
      if (_sum_supply < 0) {
782 782
        _pi[_root] = 0;
783 783
        _excess[_root] = -_sum_supply;
784 784
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
785 785
          int ra = _reverse[a];
786 786
          _res_cap[a] = -_sum_supply + 1;
787 787
          _res_cap[ra] = 0;
788 788
          _cost[a] = 0;
789 789
          _cost[ra] = 0;
790 790
        }
791 791
      } else {
792 792
        _pi[_root] = 0;
793 793
        _excess[_root] = 0;
794 794
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
795 795
          int ra = _reverse[a];
796 796
          _res_cap[a] = 1;
797 797
          _res_cap[ra] = 0;
798 798
          _cost[a] = 0;
799 799
          _cost[ra] = 0;
800 800
        }
801 801
      }
802 802

	
803 803
      // Initialize delta value
804 804
      if (_factor > 1) {
805 805
        // With scaling
806 806
        Value max_sup = 0, max_dem = 0, max_cap = 0;
807 807
        for (int i = 0; i != _root; ++i) {
808 808
          Value ex = _excess[i];
809 809
          if ( ex > max_sup) max_sup =  ex;
810 810
          if (-ex > max_dem) max_dem = -ex;
811 811
          int last_out = _first_out[i+1] - 1;
812 812
          for (int j = _first_out[i]; j != last_out; ++j) {
813 813
            if (_res_cap[j] > max_cap) max_cap = _res_cap[j];
814 814
          }
815 815
        }
816 816
        max_sup = std::min(std::min(max_sup, max_dem), max_cap);
817 817
        for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ;
818 818
      } else {
819 819
        // Without scaling
820 820
        _delta = 1;
821 821
      }
822 822

	
823 823
      return OPTIMAL;
824 824
    }
825 825

	
826 826
    ProblemType start() {
827 827
      // Execute the algorithm
828 828
      ProblemType pt;
829 829
      if (_delta > 1)
830 830
        pt = startWithScaling();
831 831
      else
832 832
        pt = startWithoutScaling();
833 833

	
834 834
      // Handle non-zero lower bounds
835 835
      if (_have_lower) {
836 836
        int limit = _first_out[_root];
837 837
        for (int j = 0; j != limit; ++j) {
838 838
          if (!_forward[j]) _res_cap[j] += _lower[j];
839 839
        }
840 840
      }
841 841

	
842 842
      // Shift potentials if necessary
843 843
      Cost pr = _pi[_root];
844 844
      if (_sum_supply < 0 || pr > 0) {
845 845
        for (int i = 0; i != _node_num; ++i) {
846 846
          _pi[i] -= pr;
847
        }        
847
        }
848 848
      }
849
      
849

	
850 850
      return pt;
851 851
    }
852 852

	
853 853
    // Execute the capacity scaling algorithm
854 854
    ProblemType startWithScaling() {
855 855
      // Perform capacity scaling phases
856 856
      int s, t;
857 857
      ResidualDijkstra _dijkstra(*this);
858 858
      while (true) {
859 859
        // Saturate all arcs not satisfying the optimality condition
860 860
        int last_out;
861 861
        for (int u = 0; u != _node_num; ++u) {
862 862
          last_out = _sum_supply < 0 ?
863 863
            _first_out[u+1] : _first_out[u+1] - 1;
864 864
          for (int a = _first_out[u]; a != last_out; ++a) {
865 865
            int v = _target[a];
866 866
            Cost c = _cost[a] + _pi[u] - _pi[v];
867 867
            Value rc = _res_cap[a];
868 868
            if (c < 0 && rc >= _delta) {
869 869
              _excess[u] -= rc;
870 870
              _excess[v] += rc;
871 871
              _res_cap[a] = 0;
872 872
              _res_cap[_reverse[a]] += rc;
873 873
            }
874 874
          }
875 875
        }
876 876

	
877 877
        // Find excess nodes and deficit nodes
878 878
        _excess_nodes.clear();
879 879
        _deficit_nodes.clear();
880 880
        for (int u = 0; u != _node_num; ++u) {
881 881
          Value ex = _excess[u];
882 882
          if (ex >=  _delta) _excess_nodes.push_back(u);
883 883
          if (ex <= -_delta) _deficit_nodes.push_back(u);
884 884
        }
885 885
        int next_node = 0, next_def_node = 0;
886 886

	
887 887
        // Find augmenting shortest paths
888 888
        while (next_node < int(_excess_nodes.size())) {
889 889
          // Check deficit nodes
890 890
          if (_delta > 1) {
891 891
            bool delta_deficit = false;
892 892
            for ( ; next_def_node < int(_deficit_nodes.size());
893 893
                    ++next_def_node ) {
894 894
              if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
895 895
                delta_deficit = true;
896 896
                break;
897 897
              }
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
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
// -*- C++ -*-
20 20
#ifndef LEMON_CBC_H
21 21
#define LEMON_CBC_H
22 22

	
23 23
///\file
24 24
///\brief Header of the LEMON-CBC mip solver interface.
25 25
///\ingroup lp_group
26 26

	
27 27
#include <lemon/lp_base.h>
28 28

	
29 29
class CoinModel;
30 30
class OsiSolverInterface;
31 31
class CbcModel;
32 32

	
33 33
namespace lemon {
34 34

	
35 35
  /// \brief Interface for the CBC MIP solver
36 36
  ///
37 37
  /// This class implements an interface for the CBC MIP solver.
38 38
  ///\ingroup lp_group
39 39
  class CbcMip : public MipSolver {
40 40
  protected:
41 41

	
42 42
    CoinModel *_prob;
43 43
    OsiSolverInterface *_osi_solver;
44 44
    CbcModel *_cbc_model;
45 45

	
46 46
  public:
47 47

	
48 48
    /// \e
49 49
    CbcMip();
50 50
    /// \e
51 51
    CbcMip(const CbcMip&);
52 52
    /// \e
53 53
    ~CbcMip();
... ...
@@ -76,55 +76,55 @@
76 76

	
77 77
    virtual void _getRowName(int row, std::string& name) const;
78 78
    virtual void _setRowName(int row, const std::string& name);
79 79
    virtual int _rowByName(const std::string& name) const;
80 80

	
81 81
    virtual void _setRowCoeffs(int i, ExprIterator b, ExprIterator e);
82 82
    virtual void _getRowCoeffs(int i, InsertIterator b) const;
83 83

	
84 84
    virtual void _setColCoeffs(int i, ExprIterator b, ExprIterator e);
85 85
    virtual void _getColCoeffs(int i, InsertIterator b) const;
86 86

	
87 87
    virtual void _setCoeff(int row, int col, Value value);
88 88
    virtual Value _getCoeff(int row, int col) const;
89 89

	
90 90
    virtual void _setColLowerBound(int i, Value value);
91 91
    virtual Value _getColLowerBound(int i) const;
92 92
    virtual void _setColUpperBound(int i, Value value);
93 93
    virtual Value _getColUpperBound(int i) const;
94 94

	
95 95
    virtual void _setRowLowerBound(int i, Value value);
96 96
    virtual Value _getRowLowerBound(int i) const;
97 97
    virtual void _setRowUpperBound(int i, Value value);
98 98
    virtual Value _getRowUpperBound(int i) const;
99 99

	
100 100
    virtual void _setObjCoeffs(ExprIterator b, ExprIterator e);
101 101
    virtual void _getObjCoeffs(InsertIterator b) const;
102 102

	
103 103
    virtual void _setObjCoeff(int i, Value obj_coef);
104 104
    virtual Value _getObjCoeff(int i) const;
105 105

	
106 106
    virtual void _setSense(Sense sense);
107 107
    virtual Sense _getSense() const;
108 108

	
109 109
    virtual ColTypes _getColType(int col) const;
110 110
    virtual void _setColType(int col, ColTypes col_type);
111 111

	
112 112
    virtual SolveExitStatus _solve();
113 113
    virtual ProblemType _getType() const;
114 114
    virtual Value _getSol(int i) const;
115 115
    virtual Value _getSolValue() const;
116 116

	
117 117
    virtual void _clear();
118 118

	
119 119
    virtual void _messageLevel(MessageLevel level);
120 120
    void _applyMessageLevel();
121 121

	
122 122
    int _message_level;
123 123

	
124
    
124

	
125 125

	
126 126
  };
127 127

	
128 128
}
129 129

	
130 130
#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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_CIRCULATION_H
20 20
#define LEMON_CIRCULATION_H
21 21

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

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

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

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

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

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

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

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

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

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

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

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

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

	
116 116
  };
117 117

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

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

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

	
141 141
     \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu)
142 142
     \geq sup(u) \quad \forall u\in V, \f]
143 143
     \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A. \f]
144
     
144

	
145 145
     The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
146 146
     zero or negative in order to have a feasible solution (since the sum
147 147
     of the expressions on the left-hand side of the inequalities is zero).
148 148
     It means that the total demand must be greater or equal to the total
149 149
     supply and all the supplies have to be carried out from the supply nodes,
150 150
     but there could be demands that are not satisfied.
151 151
     If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
152 152
     constraints have to be satisfied with equality, i.e. all demands
153 153
     have to be satisfied and all supplies have to be used.
154
     
154

	
155 155
     If you need the opposite inequalities in the supply/demand constraints
156 156
     (i.e. the total demand is less than the total supply and all the demands
157 157
     have to be satisfied while there could be supplies that are not used),
158 158
     then you could easily transform the problem to the above form by reversing
159 159
     the direction of the arcs and taking the negative of the supply values
160 160
     (e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
161 161

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

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

	
169 169
     \tparam GR The type of the digraph the algorithm runs on.
170 170
     \tparam LM The type of the lower bound map. The default
171 171
     map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
172 172
     \tparam UM The type of the upper bound (capacity) map.
173 173
     The default map type is \c LM.
174 174
     \tparam SM The type of the supply map. The default map type is
175 175
     \ref concepts::Digraph::NodeMap "GR::NodeMap<UM::Value>".
176 176
     \tparam TR The traits class that defines various types used by the
177 177
     algorithm. By default, it is \ref CirculationDefaultTraits
178 178
     "CirculationDefaultTraits<GR, LM, UM, SM>".
179 179
     In most cases, this parameter should not be set directly,
180 180
     consider to use the named template parameters instead.
181 181
  */
182 182
#ifdef DOXYGEN
183 183
template< typename GR,
184 184
          typename LM,
185 185
          typename UM,
186 186
          typename SM,
187 187
          typename TR >
188 188
#else
189 189
template< typename GR,
190 190
          typename LM = typename GR::template ArcMap<int>,
191 191
          typename UM = LM,
192 192
          typename SM = typename GR::template NodeMap<typename UM::Value>,
193 193
          typename TR = CirculationDefaultTraits<GR, LM, UM, SM> >
194 194
#endif
195 195
  class Circulation {
196 196
  public:
197 197

	
198 198
    ///The \ref CirculationDefaultTraits "traits class" of the algorithm.
199 199
    typedef TR Traits;
200 200
    ///The type of the digraph the algorithm runs on.
201 201
    typedef typename Traits::Digraph Digraph;
202 202
    ///The type of the flow and supply values.
... ...
@@ -292,97 +292,97 @@
292 292
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
293 293
                           SetElevatorTraits<T> > {
294 294
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
295 295
                          SetElevatorTraits<T> > Create;
296 296
    };
297 297

	
298 298
    template <typename T>
299 299
    struct SetStandardElevatorTraits : public Traits {
300 300
      typedef T Elevator;
301 301
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
302 302
        return new Elevator(digraph, max_level);
303 303
      }
304 304
    };
305 305

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

	
326 326
    /// @}
327 327

	
328 328
  protected:
329 329

	
330 330
    Circulation() {}
331 331

	
332 332
  public:
333 333

	
334 334
    /// Constructor.
335 335

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

	
349 349
    /// Destructor.
350 350
    ~Circulation() {
351 351
      destroyStructures();
352 352
    }
353 353

	
354 354

	
355 355
  private:
356 356

	
357 357
    bool checkBoundMaps() {
358 358
      for (ArcIt e(_g);e!=INVALID;++e) {
359 359
        if (_tol.less((*_up)[e], (*_lo)[e])) return false;
360 360
      }
361 361
      return true;
362 362
    }
363 363

	
364 364
    void createStructures() {
365 365
      _node_num = _el = countNodes(_g);
366 366

	
367 367
      if (!_flow) {
368 368
        _flow = Traits::createFlowMap(_g);
369 369
        _local_flow = true;
370 370
      }
371 371
      if (!_level) {
372 372
        _level = Traits::createElevator(_g, _node_num);
373 373
        _local_level = true;
374 374
      }
375 375
      if (!_excess) {
376 376
        _excess = new ExcessMap(_g);
377 377
      }
378 378
    }
379 379

	
380 380
    void destroyStructures() {
381 381
      if (_local_flow) {
382 382
        delete _flow;
383 383
      }
384 384
      if (_local_level) {
385 385
        delete _level;
386 386
      }
387 387
      if (_excess) {
388 388
        delete _excess;
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
 * Copyright (C) 2003-2008
5
 * Copyright (C) 2003-2010
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/clp.h>
20 20
#include <coin/ClpSimplex.hpp>
21 21

	
22 22
namespace lemon {
23 23

	
24 24
  ClpLp::ClpLp() {
25 25
    _prob = new ClpSimplex();
26 26
    _init_temporals();
27 27
    messageLevel(MESSAGE_NOTHING);
28 28
  }
29 29

	
30 30
  ClpLp::ClpLp(const ClpLp& other) {
31 31
    _prob = new ClpSimplex(*other._prob);
32 32
    rows = other.rows;
33 33
    cols = other.cols;
34 34
    _init_temporals();
35 35
    messageLevel(MESSAGE_NOTHING);
36 36
  }
37 37

	
38 38
  ClpLp::~ClpLp() {
39 39
    delete _prob;
40 40
    _clear_temporals();
41 41
  }
42 42

	
43 43
  void ClpLp::_init_temporals() {
44 44
    _primal_ray = 0;
45 45
    _dual_ray = 0;
46 46
  }
47 47

	
48 48
  void ClpLp::_clear_temporals() {
49 49
    if (_primal_ray) {
50 50
      delete[] _primal_ray;
51 51
      _primal_ray = 0;
52 52
    }
53 53
    if (_dual_ray) {
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
 * Copyright (C) 2003-2008
5
 * Copyright (C) 2003-2010
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_CLP_H
20 20
#define LEMON_CLP_H
21 21

	
22 22
///\file
23 23
///\brief Header of the LEMON-CLP lp solver interface.
24 24

	
25 25
#include <vector>
26 26
#include <string>
27 27

	
28 28
#include <lemon/lp_base.h>
29 29

	
30 30
class ClpSimplex;
31 31

	
32 32
namespace lemon {
33 33

	
34 34
  /// \ingroup lp_group
35 35
  ///
36 36
  /// \brief Interface for the CLP solver
37 37
  ///
38 38
  /// This class implements an interface for the Clp LP solver.  The
39 39
  /// Clp library is an object oriented lp solver library developed at
40 40
  /// the IBM. The CLP is part of the COIN-OR package and it can be
41 41
  /// used with Common Public License.
42 42
  class ClpLp : public LpSolver {
43 43
  protected:
44 44

	
45 45
    ClpSimplex* _prob;
46 46

	
47 47
    std::map<std::string, int> _col_names_ref;
48 48
    std::map<std::string, int> _row_names_ref;
49 49

	
50 50
  public:
51 51

	
52 52
    /// \e
53 53
    ClpLp();
... ...
@@ -93,72 +93,72 @@
93 93

	
94 94
    virtual void _setRowCoeffs(int i, ExprIterator b, ExprIterator e);
95 95
    virtual void _getRowCoeffs(int i, InsertIterator b) const;
96 96

	
97 97
    virtual void _setColCoeffs(int i, ExprIterator b, ExprIterator e);
98 98
    virtual void _getColCoeffs(int i, InsertIterator b) const;
99 99

	
100 100
    virtual void _setCoeff(int row, int col, Value value);
101 101
    virtual Value _getCoeff(int row, int col) const;
102 102

	
103 103
    virtual void _setColLowerBound(int i, Value value);
104 104
    virtual Value _getColLowerBound(int i) const;
105 105
    virtual void _setColUpperBound(int i, Value value);
106 106
    virtual Value _getColUpperBound(int i) const;
107 107

	
108 108
    virtual void _setRowLowerBound(int i, Value value);
109 109
    virtual Value _getRowLowerBound(int i) const;
110 110
    virtual void _setRowUpperBound(int i, Value value);
111 111
    virtual Value _getRowUpperBound(int i) const;
112 112

	
113 113
    virtual void _setObjCoeffs(ExprIterator, ExprIterator);
114 114
    virtual void _getObjCoeffs(InsertIterator) const;
115 115

	
116 116
    virtual void _setObjCoeff(int i, Value obj_coef);
117 117
    virtual Value _getObjCoeff(int i) const;
118 118

	
119 119
    virtual void _setSense(Sense sense);
120 120
    virtual Sense _getSense() const;
121 121

	
122 122
    virtual SolveExitStatus _solve();
123 123

	
124 124
    virtual Value _getPrimal(int i) const;
125 125
    virtual Value _getDual(int i) const;
126 126

	
127 127
    virtual Value _getPrimalValue() const;
128 128

	
129 129
    virtual Value _getPrimalRay(int i) const;
130 130
    virtual Value _getDualRay(int i) const;
131 131

	
132 132
    virtual VarStatus _getColStatus(int i) const;
133 133
    virtual VarStatus _getRowStatus(int i) const;
134 134

	
135 135
    virtual ProblemType _getPrimalType() const;
136 136
    virtual ProblemType _getDualType() const;
137 137

	
138 138
    virtual void _clear();
139 139

	
140 140
    virtual void _messageLevel(MessageLevel);
141
    
141

	
142 142
  public:
143 143

	
144 144
    ///Solves LP with primal simplex method.
145 145
    SolveExitStatus solvePrimal();
146 146

	
147 147
    ///Solves LP with dual simplex method.
148 148
    SolveExitStatus solveDual();
149 149

	
150 150
    ///Solves LP with barrier method.
151 151
    SolveExitStatus solveBarrier();
152 152

	
153 153
    ///Returns the constraint identifier understood by CLP.
154 154
    int clpRow(Row r) const { return rows(id(r)); }
155 155

	
156 156
    ///Returns the variable identifier understood by CLP.
157 157
    int clpCol(Col c) const { return cols(id(c)); }
158 158

	
159 159
  };
160 160

	
161 161
} //END OF NAMESPACE LEMON
162 162

	
163 163
#endif //LEMON_CLP_H
164 164

	
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_CONCEPTS_DIGRAPH_H
20 20
#define LEMON_CONCEPTS_DIGRAPH_H
21 21

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
482 482
    };
483 483

	
484 484
  } //namespace concepts
485 485
} //namespace lemon
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
 * Copyright (C) 2003-2009
5
 * Copyright (C) 2003-2010
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
///\ingroup graph_concepts
20 20
///\file
21 21
///\brief The concept of undirected graphs.
22 22

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

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

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

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

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

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

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

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

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

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

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

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

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

	
124 124
        /// Inequality operator
125 125

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

	
129 129
        /// Artificial ordering operator.
130 130

	
131 131
        /// Artificial ordering operator.
132 132
        ///
133 133
        /// \note This operator only has to define some strict ordering of
134 134
        /// the items; this order has nothing to do with the iteration
135 135
        /// ordering of the items.
136 136
        bool operator<(Node) const { return false; }
... ...
@@ -315,97 +315,97 @@
315 315
        /// of the corresponding node.
316 316
        IncEdgeIt& operator++() { return *this; }
317 317
      };
318 318

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

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

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

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

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

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

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

	
353 353
        /// Artificial ordering operator.
354 354

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

	
362 362
        /// Converison to \c Edge
363
        
363

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

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

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

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

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

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

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

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

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

	

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

0 comments (0 inline)