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

	
19
namespace lemon {
20

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

	
24
\section mcf_def Definition (GEQ form)
25

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

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

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

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

	
59

	
60
\section mcf_algs Algorithms
61

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

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

	
67

	
68
\section mcf_dual Dual Solution
69

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

	
76
 - For all \f$uv\in A\f$ arcs:
77
   - if \f$cost^\pi(uv)>0\f$, then \f$f(uv)=lower(uv)\f$;
78
   - if \f$lower(uv)<f(uv)<upper(uv)\f$, then \f$cost^\pi(uv)=0\f$;
79
   - if \f$cost^\pi(uv)<0\f$, then \f$f(uv)=upper(uv)\f$.
80
 - For all \f$u\in V\f$ nodes:
81
   - \f$\pi(u)<=0\f$;
82
   - if \f$\sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \neq sup(u)\f$,
83
     then \f$\pi(u)=0\f$.
84
 
85
Here \f$cost^\pi(uv)\f$ denotes the \e reduced \e cost of the arc
86
\f$uv\in A\f$ with respect to the potential function \f$\pi\f$, i.e.
87
\f[ cost^\pi(uv) = cost(uv) + \pi(u) - \pi(v).\f]
88

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

	
92

	
93
\section mcf_eq Equality Form
94

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

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

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

	
110

	
111
\section mcf_leq Opposite Inequalites (LEQ Form)
112

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

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

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

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

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

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

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

	
19
#include <lemon/connectivity.h>
20
#include <lemon/list_graph.h>
21
#include <lemon/adaptors.h>
22

	
23
#include "test_tools.h"
24

	
25
using namespace lemon;
26

	
27

	
28
int main()
29
{
30
  typedef ListDigraph Digraph;
31
  typedef Undirector<Digraph> Graph;
32
  
33
  {
34
    Digraph d;
35
    Digraph::NodeMap<int> order(d);
36
    Graph g(d);
37
    
38
    check(stronglyConnected(d), "The empty digraph is strongly connected");
39
    check(countStronglyConnectedComponents(d) == 0,
40
          "The empty digraph has 0 strongly connected component");
41
    check(connected(g), "The empty graph is connected");
42
    check(countConnectedComponents(g) == 0,
43
          "The empty graph has 0 connected component");
44

	
45
    check(biNodeConnected(g), "The empty graph is bi-node-connected");
46
    check(countBiNodeConnectedComponents(g) == 0,
47
          "The empty graph has 0 bi-node-connected component");
48
    check(biEdgeConnected(g), "The empty graph is bi-edge-connected");
49
    check(countBiEdgeConnectedComponents(g) == 0,
50
          "The empty graph has 0 bi-edge-connected component");
51
          
52
    check(dag(d), "The empty digraph is DAG.");
53
    check(checkedTopologicalSort(d, order), "The empty digraph is DAG.");
54
    check(loopFree(d), "The empty digraph is loop-free.");
55
    check(parallelFree(d), "The empty digraph is parallel-free.");
56
    check(simpleGraph(d), "The empty digraph is simple.");
57

	
58
    check(acyclic(g), "The empty graph is acyclic.");
59
    check(tree(g), "The empty graph is tree.");
60
    check(bipartite(g), "The empty graph is bipartite.");
61
    check(loopFree(g), "The empty graph is loop-free.");
62
    check(parallelFree(g), "The empty graph is parallel-free.");
63
    check(simpleGraph(g), "The empty graph is simple.");
64
  }
65

	
66
  {
67
    Digraph d;
68
    Digraph::NodeMap<int> order(d);
69
    Graph g(d);
70
    Digraph::Node n = d.addNode();
71

	
72
    check(stronglyConnected(d), "This digraph is strongly connected");
73
    check(countStronglyConnectedComponents(d) == 1,
74
          "This digraph has 1 strongly connected component");
75
    check(connected(g), "This graph is connected");
76
    check(countConnectedComponents(g) == 1,
77
          "This graph has 1 connected component");
78

	
79
    check(biNodeConnected(g), "This graph is bi-node-connected");
80
    check(countBiNodeConnectedComponents(g) == 0,
81
          "This graph has 0 bi-node-connected component");
82
    check(biEdgeConnected(g), "This graph is bi-edge-connected");
83
    check(countBiEdgeConnectedComponents(g) == 1,
84
          "This graph has 1 bi-edge-connected component");
85
          
86
    check(dag(d), "This digraph is DAG.");
87
    check(checkedTopologicalSort(d, order), "This digraph is DAG.");
88
    check(loopFree(d), "This digraph is loop-free.");
89
    check(parallelFree(d), "This digraph is parallel-free.");
90
    check(simpleGraph(d), "This digraph is simple.");
91

	
92
    check(acyclic(g), "This graph is acyclic.");
93
    check(tree(g), "This graph is tree.");
94
    check(bipartite(g), "This graph is bipartite.");
95
    check(loopFree(g), "This graph is loop-free.");
96
    check(parallelFree(g), "This graph is parallel-free.");
97
    check(simpleGraph(g), "This graph is simple.");
98
  }
99

	
100
  {
101
    Digraph d;
102
    Digraph::NodeMap<int> order(d);
103
    Graph g(d);
104
    
105
    Digraph::Node n1 = d.addNode();
106
    Digraph::Node n2 = d.addNode();
107
    Digraph::Node n3 = d.addNode();
108
    Digraph::Node n4 = d.addNode();
109
    Digraph::Node n5 = d.addNode();
110
    Digraph::Node n6 = d.addNode();
111
    
112
    d.addArc(n1, n3);
113
    d.addArc(n3, n2);
114
    d.addArc(n2, n1);
115
    d.addArc(n4, n2);
116
    d.addArc(n4, n3);
117
    d.addArc(n5, n6);
118
    d.addArc(n6, n5);
119

	
120
    check(!stronglyConnected(d), "This digraph is not strongly connected");
121
    check(countStronglyConnectedComponents(d) == 3,
122
          "This digraph has 3 strongly connected components");
123
    check(!connected(g), "This graph is not connected");
124
    check(countConnectedComponents(g) == 2,
125
          "This graph has 2 connected components");
126

	
127
    check(!dag(d), "This digraph is not DAG.");
128
    check(!checkedTopologicalSort(d, order), "This digraph is not DAG.");
129
    check(loopFree(d), "This digraph is loop-free.");
130
    check(parallelFree(d), "This digraph is parallel-free.");
131
    check(simpleGraph(d), "This digraph is simple.");
132

	
133
    check(!acyclic(g), "This graph is not acyclic.");
134
    check(!tree(g), "This graph is not tree.");
135
    check(!bipartite(g), "This graph is not bipartite.");
136
    check(loopFree(g), "This graph is loop-free.");
137
    check(!parallelFree(g), "This graph is not parallel-free.");
138
    check(!simpleGraph(g), "This graph is not simple.");
139
    
140
    d.addArc(n3, n3);
141
    
142
    check(!loopFree(d), "This digraph is not loop-free.");
143
    check(!loopFree(g), "This graph is not loop-free.");
144
    check(!simpleGraph(d), "This digraph is not simple.");
145
    
146
    d.addArc(n3, n2);
147
    
148
    check(!parallelFree(d), "This digraph is not parallel-free.");
149
  }
150
  
151
  {
152
    Digraph d;
153
    Digraph::ArcMap<bool> cutarcs(d, false);
154
    Graph g(d);
155
    
156
    Digraph::Node n1 = d.addNode();
157
    Digraph::Node n2 = d.addNode();
158
    Digraph::Node n3 = d.addNode();
159
    Digraph::Node n4 = d.addNode();
160
    Digraph::Node n5 = d.addNode();
161
    Digraph::Node n6 = d.addNode();
162
    Digraph::Node n7 = d.addNode();
163
    Digraph::Node n8 = d.addNode();
164

	
165
    d.addArc(n1, n2);
166
    d.addArc(n5, n1);
167
    d.addArc(n2, n8);
168
    d.addArc(n8, n5);
169
    d.addArc(n6, n4);
170
    d.addArc(n4, n6);
171
    d.addArc(n2, n5);
172
    d.addArc(n1, n8);
173
    d.addArc(n6, n7);
174
    d.addArc(n7, n6);
175
   
176
    check(!stronglyConnected(d), "This digraph is not strongly connected");
177
    check(countStronglyConnectedComponents(d) == 3,
178
          "This digraph has 3 strongly connected components");
179
    Digraph::NodeMap<int> scomp1(d);
180
    check(stronglyConnectedComponents(d, scomp1) == 3,
181
          "This digraph has 3 strongly connected components");
182
    check(scomp1[n1] != scomp1[n3] && scomp1[n1] != scomp1[n4] &&
183
          scomp1[n3] != scomp1[n4], "Wrong stronglyConnectedComponents()");
184
    check(scomp1[n1] == scomp1[n2] && scomp1[n1] == scomp1[n5] &&
185
          scomp1[n1] == scomp1[n8], "Wrong stronglyConnectedComponents()");
186
    check(scomp1[n4] == scomp1[n6] && scomp1[n4] == scomp1[n7],
187
          "Wrong stronglyConnectedComponents()");
188
    Digraph::ArcMap<bool> scut1(d, false);
189
    check(stronglyConnectedCutArcs(d, scut1) == 0,
190
          "This digraph has 0 strongly connected cut arc.");
191
    for (Digraph::ArcIt a(d); a != INVALID; ++a) {
192
      check(!scut1[a], "Wrong stronglyConnectedCutArcs()");
193
    }
194

	
195
    check(!connected(g), "This graph is not connected");
196
    check(countConnectedComponents(g) == 3,
197
          "This graph has 3 connected components");
198
    Graph::NodeMap<int> comp(g);
199
    check(connectedComponents(g, comp) == 3,
200
          "This graph has 3 connected components");
201
    check(comp[n1] != comp[n3] && comp[n1] != comp[n4] &&
202
          comp[n3] != comp[n4], "Wrong connectedComponents()");
203
    check(comp[n1] == comp[n2] && comp[n1] == comp[n5] &&
204
          comp[n1] == comp[n8], "Wrong connectedComponents()");
205
    check(comp[n4] == comp[n6] && comp[n4] == comp[n7],
206
          "Wrong connectedComponents()");
207

	
208
    cutarcs[d.addArc(n3, n1)] = true;
209
    cutarcs[d.addArc(n3, n5)] = true;
210
    cutarcs[d.addArc(n3, n8)] = true;
211
    cutarcs[d.addArc(n8, n6)] = true;
212
    cutarcs[d.addArc(n8, n7)] = true;
213

	
214
    check(!stronglyConnected(d), "This digraph is not strongly connected");
215
    check(countStronglyConnectedComponents(d) == 3,
216
          "This digraph has 3 strongly connected components");
217
    Digraph::NodeMap<int> scomp2(d);
218
    check(stronglyConnectedComponents(d, scomp2) == 3,
219
          "This digraph has 3 strongly connected components");
220
    check(scomp2[n3] == 0, "Wrong stronglyConnectedComponents()");
221
    check(scomp2[n1] == 1 && scomp2[n2] == 1 && scomp2[n5] == 1 &&
222
          scomp2[n8] == 1, "Wrong stronglyConnectedComponents()");
223
    check(scomp2[n4] == 2 && scomp2[n6] == 2 && scomp2[n7] == 2,
224
          "Wrong stronglyConnectedComponents()");
225
    Digraph::ArcMap<bool> scut2(d, false);
226
    check(stronglyConnectedCutArcs(d, scut2) == 5,
227
          "This digraph has 5 strongly connected cut arcs.");
228
    for (Digraph::ArcIt a(d); a != INVALID; ++a) {
229
      check(scut2[a] == cutarcs[a], "Wrong stronglyConnectedCutArcs()");
230
    }
231
  }
232

	
233
  {
234
    // DAG example for topological sort from the book New Algorithms
235
    // (T. H. Cormen, C. E. Leiserson, R. L. Rivest, C. Stein)
236
    Digraph d;
237
    Digraph::NodeMap<int> order(d);
238
    
239
    Digraph::Node belt = d.addNode();
240
    Digraph::Node trousers = d.addNode();
241
    Digraph::Node necktie = d.addNode();
242
    Digraph::Node coat = d.addNode();
243
    Digraph::Node socks = d.addNode();
244
    Digraph::Node shirt = d.addNode();
245
    Digraph::Node shoe = d.addNode();
246
    Digraph::Node watch = d.addNode();
247
    Digraph::Node pants = d.addNode();
248

	
249
    d.addArc(socks, shoe);
250
    d.addArc(pants, shoe);
251
    d.addArc(pants, trousers);
252
    d.addArc(trousers, shoe);
253
    d.addArc(trousers, belt);
254
    d.addArc(belt, coat);
255
    d.addArc(shirt, belt);
256
    d.addArc(shirt, necktie);
257
    d.addArc(necktie, coat);
258
    
259
    check(dag(d), "This digraph is DAG.");
260
    topologicalSort(d, order);
261
    for (Digraph::ArcIt a(d); a != INVALID; ++a) {
262
      check(order[d.source(a)] < order[d.target(a)],
263
            "Wrong topologicalSort()");
264
    }
265
  }
266

	
267
  {
268
    ListGraph g;
269
    ListGraph::NodeMap<bool> map(g);
270
    
271
    ListGraph::Node n1 = g.addNode();
272
    ListGraph::Node n2 = g.addNode();
273
    ListGraph::Node n3 = g.addNode();
274
    ListGraph::Node n4 = g.addNode();
275
    ListGraph::Node n5 = g.addNode();
276
    ListGraph::Node n6 = g.addNode();
277
    ListGraph::Node n7 = g.addNode();
278

	
279
    g.addEdge(n1, n3);
280
    g.addEdge(n1, n4);
281
    g.addEdge(n2, n5);
282
    g.addEdge(n3, n6);
283
    g.addEdge(n4, n6);
284
    g.addEdge(n4, n7);
285
    g.addEdge(n5, n7);
286
   
287
    check(bipartite(g), "This graph is bipartite");
288
    check(bipartitePartitions(g, map), "This graph is bipartite");
289
    
290
    check(map[n1] == map[n2] && map[n1] == map[n6] && map[n1] == map[n7],
291
          "Wrong bipartitePartitions()");
292
    check(map[n3] == map[n4] && map[n3] == map[n5],
293
          "Wrong bipartitePartitions()");
294
  }
295

	
296
  return 0;
297
}
Ignore white space 6 line context
1 1
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
2 2

	
3 3
IF(EXISTS ${CMAKE_SOURCE_DIR}/cmake/version.cmake)
4 4
  INCLUDE(${CMAKE_SOURCE_DIR}/cmake/version.cmake)
5 5
ELSE(EXISTS ${CMAKE_SOURCE_DIR}/cmake/version.cmake)
6 6
  SET(PROJECT_NAME "LEMON")
7 7
  SET(PROJECT_VERSION "hg-tip" CACHE STRING "LEMON version string.")
8 8
ENDIF(EXISTS ${CMAKE_SOURCE_DIR}/cmake/version.cmake)
9 9

	
10 10
PROJECT(${PROJECT_NAME})
11 11

	
12 12
SET(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
13 13

	
14 14
INCLUDE(FindDoxygen)
15 15
INCLUDE(FindGhostscript)
16 16
FIND_PACKAGE(GLPK 4.33)
17 17
FIND_PACKAGE(CPLEX)
18 18
FIND_PACKAGE(COIN)
19 19

	
20 20
IF(MSVC)
21 21
  SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /wd4250 /wd4355 /wd4800 /wd4996")
22 22
# Suppressed warnings:
23 23
# C4250: 'class1' : inherits 'class2::member' via dominance
24 24
# C4355: 'this' : used in base member initializer list
25 25
# C4800: 'type' : forcing value to bool 'true' or 'false' (performance warning)
26 26
# C4996: 'function': was declared deprecated
27 27
ENDIF(MSVC)
28 28

	
29 29
INCLUDE(CheckTypeSize)
30 30
CHECK_TYPE_SIZE("long long" LEMON_LONG_LONG)
31 31

	
32 32
ENABLE_TESTING()
33 33

	
34 34
ADD_SUBDIRECTORY(lemon)
35 35
IF(${CMAKE_SOURCE_DIR} STREQUAL ${PROJECT_SOURCE_DIR})
36 36
  ADD_SUBDIRECTORY(demo)
37 37
  ADD_SUBDIRECTORY(tools)
38 38
  ADD_SUBDIRECTORY(doc)
39 39
  ADD_SUBDIRECTORY(test)
40 40
ENDIF(${CMAKE_SOURCE_DIR} STREQUAL ${PROJECT_SOURCE_DIR})
41 41

	
42 42
IF(${CMAKE_SOURCE_DIR} STREQUAL ${PROJECT_SOURCE_DIR})
43 43
  IF(WIN32)
44 44
    SET(CPACK_PACKAGE_NAME ${PROJECT_NAME})
45 45
    SET(CPACK_PACKAGE_VENDOR "EGRES")
46 46
    SET(CPACK_PACKAGE_DESCRIPTION_SUMMARY
47
      "LEMON - Library of Efficient Models and Optimization in Networks")
47
      "LEMON - Library for Efficient Modeling and Optimization in Networks")
48 48
    SET(CPACK_RESOURCE_FILE_LICENSE "${PROJECT_SOURCE_DIR}/LICENSE")
49 49

	
50 50
    SET(CPACK_PACKAGE_VERSION ${PROJECT_VERSION})
51 51

	
52 52
    SET(CPACK_PACKAGE_INSTALL_DIRECTORY
53 53
      "${PROJECT_NAME} ${PROJECT_VERSION}")
54 54
    SET(CPACK_PACKAGE_INSTALL_REGISTRY_KEY
55 55
      "${PROJECT_NAME} ${PROJECT_VERSION}")
56 56

	
57 57
    SET(CPACK_COMPONENTS_ALL headers library html_documentation bin)
58 58

	
59 59
    SET(CPACK_COMPONENT_HEADERS_DISPLAY_NAME "C++ headers")
60 60
    SET(CPACK_COMPONENT_LIBRARY_DISPLAY_NAME "Dynamic-link library")
61 61
    SET(CPACK_COMPONENT_BIN_DISPLAY_NAME "Command line utilities")
62 62
    SET(CPACK_COMPONENT_HTML_DOCUMENTATION_DISPLAY_NAME "HTML documentation")
63 63

	
64 64
    SET(CPACK_COMPONENT_HEADERS_DESCRIPTION
65 65
      "C++ header files")
66 66
    SET(CPACK_COMPONENT_LIBRARY_DESCRIPTION
67 67
      "DLL and import library")
68 68
    SET(CPACK_COMPONENT_BIN_DESCRIPTION
69 69
      "Command line utilities")
70 70
    SET(CPACK_COMPONENT_HTML_DOCUMENTATION_DESCRIPTION
71 71
      "Doxygen generated documentation")
72 72

	
73 73
    SET(CPACK_COMPONENT_HEADERS_DEPENDS library)
74 74

	
75 75
    SET(CPACK_COMPONENT_HEADERS_GROUP "Development")
76 76
    SET(CPACK_COMPONENT_LIBRARY_GROUP "Development")
77 77
    SET(CPACK_COMPONENT_HTML_DOCUMENTATION_GROUP "Documentation")
78 78

	
79 79
    SET(CPACK_COMPONENT_GROUP_DEVELOPMENT_DESCRIPTION
80 80
      "Components needed to develop software using LEMON")
81 81
    SET(CPACK_COMPONENT_GROUP_DOCUMENTATION_DESCRIPTION
82 82
      "Documentation of LEMON")
83 83

	
84 84
    SET(CPACK_ALL_INSTALL_TYPES Full Developer)
85 85

	
86 86
    SET(CPACK_COMPONENT_HEADERS_INSTALL_TYPES Developer Full)
87 87
    SET(CPACK_COMPONENT_LIBRARY_INSTALL_TYPES Developer Full)
88 88
    SET(CPACK_COMPONENT_HTML_DOCUMENTATION_INSTALL_TYPES Full)
89 89

	
90 90
    SET(CPACK_GENERATOR "NSIS")
91 91
    SET(CPACK_NSIS_MUI_ICON "${PROJECT_SOURCE_DIR}/cmake/nsis/lemon.ico")
92 92
    SET(CPACK_NSIS_MUI_UNIICON "${PROJECT_SOURCE_DIR}/cmake/nsis/uninstall.ico")
93 93
    #SET(CPACK_PACKAGE_ICON "${PROJECT_SOURCE_DIR}/cmake/nsis\\\\installer.bmp")
94 94
    SET(CPACK_NSIS_INSTALLED_ICON_NAME "bin\\\\lemon.ico")
95 95
    SET(CPACK_NSIS_DISPLAY_NAME "${CPACK_PACKAGE_INSTALL_DIRECTORY} ${PROJECT_NAME}")
96 96
    SET(CPACK_NSIS_HELP_LINK "http:\\\\\\\\lemon.cs.elte.hu")
97 97
    SET(CPACK_NSIS_URL_INFO_ABOUT "http:\\\\\\\\lemon.cs.elte.hu")
98 98
    SET(CPACK_NSIS_CONTACT "lemon-user@lemon.cs.elte.hu")
99 99
    SET(CPACK_NSIS_CREATE_ICONS_EXTRA "
100 100
      CreateShortCut \\\"$SMPROGRAMS\\\\$STARTMENU_FOLDER\\\\Documentation.lnk\\\" \\\"$INSTDIR\\\\share\\\\doc\\\\index.html\\\"
101 101
      ")
102 102
    SET(CPACK_NSIS_DELETE_ICONS_EXTRA "
103 103
      !insertmacro MUI_STARTMENU_GETFOLDER Application $MUI_TEMP
104 104
      Delete \\\"$SMPROGRAMS\\\\$MUI_TEMP\\\\Documentation.lnk\\\"
105 105
      ")
106 106

	
107 107
    INCLUDE(CPack)
108 108
  ENDIF(WIN32)
109 109
ENDIF(${CMAKE_SOURCE_DIR} STREQUAL ${PROJECT_SOURCE_DIR})
Ignore white space 6 line context
1
2009-05-13 Version 1.1 released
2

	
3
        This is the second stable release of the 1.x series. It
4
        features a better coverage of the tools available in the 0.x
5
        series, a thoroughly reworked LP/MIP interface plus various
6
        improvements in the existing tools.
7

	
8
        * Much improved M$ Windows support
9
          * Various improvements in the CMAKE build system
10
          * Compilation warnings are fixed/suppressed
11
        * Support IBM xlC compiler
12
        * New algorithms
13
          * Connectivity related algorithms (#61)
14
          * Euler walks (#65)
15
          * Preflow push-relabel max. flow algorithm (#176)
16
          * Circulation algorithm (push-relabel based) (#175)
17
          * Suurballe algorithm (#47)
18
          * Gomory-Hu algorithm (#66)
19
          * Hao-Orlin algorithm (#58)
20
          * Edmond's maximum cardinality and weighted matching algorithms
21
            in general graphs (#48,#265)
22
          * Minimum cost arborescence/branching (#60)
23
          * Network Simplex min. cost flow algorithm (#234)
24
        * New data structures
25
          * Full graph structure (#57)
26
          * Grid graph structure (#57)
27
          * Hypercube graph structure (#57)
28
          * Graph adaptors (#67)
29
          * ArcSet and EdgeSet classes (#67)
30
          * Elevator class (#174)
31
        * Other new tools
32
          * LP/MIP interface (#44)
33
            * Support for GLPK, CPLEX, Soplex, COIN-OR CLP and CBC
34
          * Reader for the Nauty file format (#55)
35
          * DIMACS readers (#167)
36
          * Radix sort algorithms (#72)
37
          * RangeIdMap and CrossRefMap (#160)
38
        * New command line tools
39
          * DIMACS to LGF converter (#182)
40
          * lgf-gen - a graph generator (#45)
41
          * DIMACS solver utility (#226)
42
        * Other code improvements
43
          * Lognormal distribution added to Random (#102)
44
          * Better (i.e. O(1) time) item counting in SmartGraph (#3)
45
          * The standard maps of graphs are guaranteed to be
46
            reference maps (#190)
47
        * Miscellaneous
48
          * Various doc improvements
49
          * Improved 0.x -> 1.x converter script
50

	
51
        * Several bugfixes (compared to release 1.0):
52
          #170: Bugfix SmartDigraph::split()
53
          #171: Bugfix in SmartGraph::restoreSnapshot()
54
          #172: Extended test cases for graphs and digraphs
55
          #173: Bugfix in Random
56
                * operator()s always return a double now
57
                * the faulty real<Num>(Num) and real<Num>(Num,Num)
58
                  have been removed
59
          #187: Remove DijkstraWidestPathOperationTraits
60
          #61:  Bugfix in DfsVisit
61
          #193: Bugfix in GraphReader::skipSection()
62
          #195: Bugfix in ConEdgeIt()
63
          #197: Bugfix in heap unionfind
64
                * This bug affects Edmond's general matching algorithms
65
          #207: Fix 'make install' without 'make html' using CMAKE
66
          #208: Suppress or fix VS2008 compilation warnings
67
          ----: Update the LEMON icon
68
          ----: Enable the component-based installer
69
                (in installers made by CPACK)
70
          ----: Set the proper version for CMAKE in the tarballs
71
                (made by autotools)
72
          ----: Minor clarification in the LICENSE file
73
          ----: Add missing unistd.h include to time_measure.h
74
          #204: Compilation bug fixed in graph_to_eps.h with VS2005
75
          #214,#215: windows.h should never be included by lemon headers
76
          #230: Build systems check the availability of 'long long' type
77
          #229: Default implementation of Tolerance<> is used for integer types
78
          #211,#212: Various fixes for compiling on AIX
79
          ----: Improvements in CMAKE config
80
                - docs is installed in share/doc/
81
                - detects newer versions of Ghostscript
82
          #239: Fix missing 'inline' specifier in time_measure.h
83
          #274,#280: Install lemon/config.h
84
          #275: Prefix macro names with LEMON_ in lemon/config.h
85
          ----: Small script for making the release tarballs added
86
          ----: Minor improvement in unify-sources.sh (a76f55d7d397)
87

	
1 88
2009-03-27 LEMON joins to the COIN-OR initiative
2 89

	
3 90
        COIN-OR (Computational Infrastructure for Operations Research,
4 91
        http://www.coin-or.org) project is an initiative to spur the
5 92
        development of open-source software for the operations research
6 93
        community.
7 94

	
8 95
2008-10-13 Version 1.0 released
9 96

	
10 97
	This is the first stable release of LEMON. Compared to the 0.x
11 98
	release series, it features a considerably smaller but more
12 99
	matured set of tools. The API has also completely revised and
13 100
	changed in several places.
14 101

	
15 102
	* The major name changes compared to the 0.x series (see the
16 103
          Migration Guide in the doc for more details)
17 104
          * Graph -> Digraph, UGraph -> Graph
18 105
          * Edge -> Arc, UEdge -> Edge
19 106
	  * source(UEdge)/target(UEdge) -> u(Edge)/v(Edge)
20 107
	* Other improvements
21 108
	  * Better documentation
22 109
	  * Reviewed and cleaned up codebase
23 110
	  * CMake based build system (along with the autotools based one)
24 111
	* Contents of the library (ported from 0.x)
25 112
	  * Algorithms
26 113
       	    * breadth-first search (bfs.h)
27 114
       	    * depth-first search (dfs.h)
28 115
       	    * Dijkstra's algorithm (dijkstra.h)
29 116
       	    * Kruskal's algorithm (kruskal.h)
30 117
    	  * Data structures
31 118
       	    * graph data structures (list_graph.h, smart_graph.h)
32 119
       	    * path data structures (path.h)
33 120
       	    * binary heap data structure (bin_heap.h)
34 121
       	    * union-find data structures (unionfind.h)
35 122
       	    * miscellaneous property maps (maps.h)
36 123
       	    * two dimensional vector and bounding box (dim2.h)
37 124
          * Concepts
38 125
       	    * graph structure concepts (concepts/digraph.h, concepts/graph.h,
39 126
              concepts/graph_components.h)
40 127
       	    * concepts for other structures (concepts/heap.h, concepts/maps.h,
41 128
	      concepts/path.h)
42 129
    	  * Tools
43 130
       	    * Mersenne twister random number generator (random.h)
44 131
       	    * tools for measuring cpu and wall clock time (time_measure.h)
45 132
       	    * tools for counting steps and events (counter.h)
46 133
       	    * tool for parsing command line arguments (arg_parser.h)
47 134
       	    * tool for visualizing graphs (graph_to_eps.h)
48 135
       	    * tools for reading and writing data in LEMON Graph Format
49 136
              (lgf_reader.h, lgf_writer.h)
50 137
            * tools to handle the anomalies of calculations with
51 138
	      floating point numbers (tolerance.h)
52 139
            * tools to manage RGB colors (color.h)
53 140
    	  * Infrastructure
54 141
       	    * extended assertion handling (assert.h)
55 142
       	    * exception classes and error handling (error.h)
56 143
      	    * concept checking (concept_check.h)
57 144
       	    * commonly used mathematical constants (math.h)
Ignore white space 6 line context
1
==================================================================
2
LEMON - a Library of Efficient Models and Optimization in Networks
3
==================================================================
1
=====================================================================
2
LEMON - a Library for Efficient Modeling and Optimization in Networks
3
=====================================================================
4 4

	
5 5
LEMON is an open source library written in C++. It provides
6 6
easy-to-use implementations of common data structures and algorithms
7 7
in the area of optimization and helps implementing new ones. The main
8 8
focus is on graphs and graph algorithms, thus it is especially
9 9
suitable for solving design and optimization problems of
10 10
telecommunication networks. To achieve wide usability its data
11 11
structures and algorithms provide generic interfaces.
12 12

	
13 13
Contents
14 14
========
15 15

	
16 16
LICENSE
17 17

	
18 18
   Copying, distribution and modification conditions and terms.
19 19

	
20 20
INSTALL
21 21

	
22 22
   General building and installation instructions.
23 23

	
24 24
lemon/
25 25

	
26 26
   Source code of LEMON library.
27 27

	
28 28
doc/
29 29

	
30 30
   Documentation of LEMON. The starting page is doc/html/index.html.
31 31

	
32 32
demo/
33 33

	
34 34
   Some example programs to make you easier to get familiar with LEMON.
35 35

	
36 36
test/
37 37

	
38 38
   Programs to check the integrity and correctness of LEMON.
39 39

	
40 40
tools/
41 41

	
42 42
   Various utilities related to LEMON.
Ignore white space 24576 line context
1 1
EXTRA_DIST += \
2 2
	doc/Doxyfile.in \
3 3
	doc/DoxygenLayout.xml \
4 4
	doc/coding_style.dox \
5 5
	doc/dirs.dox \
6 6
	doc/groups.dox \
7 7
	doc/lgf.dox \
8 8
	doc/license.dox \
9 9
	doc/mainpage.dox \
10 10
	doc/migration.dox \
11
	doc/min_cost_flow.dox \
11 12
	doc/named-param.dox \
12 13
	doc/namespaces.dox \
13 14
	doc/html \
14 15
	doc/CMakeLists.txt
15 16

	
16 17
DOC_EPS_IMAGES18 = \
17 18
	grid_graph.eps \
18 19
	nodeshape_0.eps \
19 20
	nodeshape_1.eps \
20 21
	nodeshape_2.eps \
21 22
	nodeshape_3.eps \
22 23
	nodeshape_4.eps
23 24

	
24 25
DOC_EPS_IMAGES27 = \
25 26
	bipartite_matching.eps \
26 27
	bipartite_partitions.eps \
27 28
	connected_components.eps \
28 29
	edge_biconnected_components.eps \
29 30
	node_biconnected_components.eps \
30 31
	strongly_connected_components.eps
31 32

	
32 33
DOC_EPS_IMAGES = \
33 34
	$(DOC_EPS_IMAGES18) \
34 35
	$(DOC_EPS_IMAGES27)
35 36

	
36 37
DOC_PNG_IMAGES = \
37 38
	$(DOC_EPS_IMAGES:%.eps=doc/gen-images/%.png)
38 39

	
39 40
EXTRA_DIST += $(DOC_EPS_IMAGES:%=doc/images/%)
40 41

	
41 42
doc/html:
42 43
	$(MAKE) $(AM_MAKEFLAGS) html
43 44

	
44 45
GS_COMMAND=gs -dNOPAUSE -dBATCH -q -dEPSCrop -dTextAlphaBits=4 -dGraphicsAlphaBits=4
45 46

	
46 47
$(DOC_EPS_IMAGES18:%.eps=doc/gen-images/%.png): doc/gen-images/%.png: doc/images/%.eps
47 48
	-mkdir doc/gen-images
48 49
	if test ${gs_found} = yes; then \
49 50
	  $(GS_COMMAND) -sDEVICE=pngalpha -r18 -sOutputFile=$@ $<; \
50 51
	else \
51 52
	  echo; \
52 53
	  echo "Ghostscript not found."; \
53 54
	  echo; \
54 55
	  exit 1; \
55 56
	fi
56 57

	
57 58
$(DOC_EPS_IMAGES27:%.eps=doc/gen-images/%.png): doc/gen-images/%.png: doc/images/%.eps
58 59
	-mkdir doc/gen-images
59 60
	if test ${gs_found} = yes; then \
60 61
	  $(GS_COMMAND) -sDEVICE=pngalpha -r27 -sOutputFile=$@ $<; \
61 62
	else \
62 63
	  echo; \
63 64
	  echo "Ghostscript not found."; \
64 65
	  echo; \
65 66
	  exit 1; \
66 67
	fi
67 68

	
68 69
html-local: $(DOC_PNG_IMAGES)
69 70
	if test ${doxygen_found} = yes; then \
70 71
	  cd doc; \
71 72
	  doxygen Doxyfile; \
72 73
	  cd ..; \
73 74
	else \
74 75
	  echo; \
75 76
	  echo "Doxygen not found."; \
76 77
	  echo; \
77 78
	  exit 1; \
78 79
	fi
79 80

	
80 81
clean-local:
81 82
	-rm -rf doc/html
82 83
	-rm -f doc/doxygen.log
83 84
	-rm -f $(DOC_PNG_IMAGES)
84 85
	-rm -rf doc/gen-images
85 86

	
86 87
update-external-tags:
87 88
	wget -O doc/libstdc++.tag.tmp http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/libstdc++.tag && \
88 89
	mv doc/libstdc++.tag.tmp doc/libstdc++.tag || \
89 90
	rm doc/libstdc++.tag.tmp
90 91

	
91 92
install-html-local: doc/html
92 93
	@$(NORMAL_INSTALL)
93 94
	$(mkinstalldirs) $(DESTDIR)$(htmldir)/docs
94 95
	for p in doc/html/*.{html,css,png,map,gif,tag} ; do \
95 96
	  f="`echo $$p | sed -e 's|^.*/||'`"; \
96 97
	  echo " $(INSTALL_DATA) $$p $(DESTDIR)$(htmldir)/docs/$$f"; \
97 98
	  $(INSTALL_DATA) $$p $(DESTDIR)$(htmldir)/docs/$$f; \
98 99
	done
99 100

	
100 101
uninstall-local:
101 102
	@$(NORMAL_UNINSTALL)
102 103
	for p in doc/html/*.{html,css,png,map,gif,tag} ; do \
103 104
	  f="`echo $$p | sed -e 's|^.*/||'`"; \
104 105
	  echo " rm -f $(DESTDIR)$(htmldir)/docs/$$f"; \
105 106
	  rm -f $(DESTDIR)$(htmldir)/docs/$$f; \
106 107
	done
107 108

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

	
19 19
namespace lemon {
20 20

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
140 140
/**
141
@defgroup semi_adaptors Semi-Adaptor Classes for Graphs
142
@ingroup graphs
143
\brief Graph types between real graphs and graph adaptors.
144

	
145
This group contains some graph types between real graphs and graph adaptors.
146
These classes wrap graphs to give new functionality as the adaptors do it.
147
On the other hand they are not light-weight structures as the adaptors.
148
*/
149

	
150
/**
151 141
@defgroup maps Maps
152 142
@ingroup datas
153 143
\brief Map structures implemented in LEMON.
154 144

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
251 241
\sa lemon::concepts::Path
252 242
*/
253 243

	
254 244
/**
255 245
@defgroup auxdat Auxiliary Data Structures
256 246
@ingroup datas
257 247
\brief Auxiliary data structures implemented in LEMON.
258 248

	
259 249
This group contains some data structures implemented in LEMON in
260 250
order to make it easier to implement combinatorial algorithms.
261 251
*/
262 252

	
263 253
/**
264 254
@defgroup algs Algorithms
265 255
\brief This group contains the several algorithms
266 256
implemented in LEMON.
267 257

	
268 258
This group contains the several algorithms
269 259
implemented in LEMON.
270 260
*/
271 261

	
272 262
/**
273 263
@defgroup search Graph Search
274 264
@ingroup algs
275 265
\brief Common graph search algorithms.
276 266

	
277 267
This group contains the common graph search algorithms, namely
278 268
\e breadth-first \e search (BFS) and \e depth-first \e search (DFS).
279 269
*/
280 270

	
281 271
/**
282 272
@defgroup shortest_path Shortest Path Algorithms
283 273
@ingroup algs
284 274
\brief Algorithms for finding shortest paths.
285 275

	
286 276
This group contains the algorithms for finding shortest paths in digraphs.
287 277

	
288 278
 - \ref Dijkstra Dijkstra's algorithm for finding shortest paths from a 
289 279
   source node when all arc lengths are non-negative.
290 280
 - \ref Suurballe A successive shortest path algorithm for finding
291 281
   arc-disjoint paths between two nodes having minimum total length.
292 282
*/
293 283

	
294 284
/**
295 285
@defgroup max_flow Maximum Flow Algorithms
296 286
@ingroup algs
297 287
\brief Algorithms for finding maximum flows.
298 288

	
299 289
This group contains the algorithms for finding maximum flows and
300 290
feasible circulations.
301 291

	
302 292
The \e maximum \e flow \e problem is to find a flow of maximum value between
303 293
a single source and a single target. Formally, there is a \f$G=(V,A)\f$
304 294
digraph, a \f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function and
305 295
\f$s, t \in V\f$ source and target nodes.
306 296
A maximum flow is an \f$f: A\rightarrow\mathbf{R}^+_0\f$ solution of the
307 297
following optimization problem.
308 298

	
309 299
\f[ \max\sum_{sv\in A} f(sv) - \sum_{vs\in A} f(vs) \f]
310 300
\f[ \sum_{uv\in A} f(uv) = \sum_{vu\in A} f(vu)
311 301
    \quad \forall u\in V\setminus\{s,t\} \f]
312 302
\f[ 0 \leq f(uv) \leq cap(uv) \quad \forall uv\in A \f]
313 303

	
314 304
\ref Preflow implements the preflow push-relabel algorithm of Goldberg and
315 305
Tarjan for solving this problem. It also provides functions to query the
316 306
minimum cut, which is the dual problem of maximum flow.
317 307

	
308

	
318 309
\ref Circulation is a preflow push-relabel algorithm implemented directly 
319 310
for finding feasible circulations, which is a somewhat different problem,
320 311
but it is strongly related to maximum flow.
321 312
For more information, see \ref Circulation.
322 313
*/
323 314

	
324 315
/**
325
@defgroup min_cost_flow Minimum Cost Flow Algorithms
316
@defgroup min_cost_flow_algs Minimum Cost Flow Algorithms
326 317
@ingroup algs
327 318

	
328 319
\brief Algorithms for finding minimum cost flows and circulations.
329 320

	
330 321
This group contains the algorithms for finding minimum cost flows and
331
circulations.
332

	
333
The \e minimum \e cost \e flow \e problem is to find a feasible flow of
334
minimum total cost from a set of supply nodes to a set of demand nodes
335
in a network with capacity constraints (lower and upper bounds)
336
and arc costs.
337
Formally, let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{Z}\f$,
338
\f$upper: A\rightarrow\mathbf{Z}\cup\{+\infty\}\f$ denote the lower and
339
upper bounds for the flow values on the arcs, for which
340
\f$lower(uv) \leq upper(uv)\f$ must hold for all \f$uv\in A\f$,
341
\f$cost: A\rightarrow\mathbf{Z}\f$ denotes the cost per unit flow
342
on the arcs and \f$sup: V\rightarrow\mathbf{Z}\f$ denotes the
343
signed supply values of the nodes.
344
If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
345
supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
346
\f$-sup(u)\f$ demand.
347
A minimum cost flow is an \f$f: A\rightarrow\mathbf{Z}\f$ solution
348
of the following optimization problem.
349

	
350
\f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
351
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
352
    sup(u) \quad \forall u\in V \f]
353
\f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
354

	
355
The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
356
zero or negative in order to have a feasible solution (since the sum
357
of the expressions on the left-hand side of the inequalities is zero).
358
It means that the total demand must be greater or equal to the total
359
supply and all the supplies have to be carried out from the supply nodes,
360
but there could be demands that are not satisfied.
361
If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
362
constraints have to be satisfied with equality, i.e. all demands
363
have to be satisfied and all supplies have to be used.
364

	
365
If you need the opposite inequalities in the supply/demand constraints
366
(i.e. the total demand is less than the total supply and all the demands
367
have to be satisfied while there could be supplies that are not used),
368
then you could easily transform the problem to the above form by reversing
369
the direction of the arcs and taking the negative of the supply values
370
(e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
371
However \ref NetworkSimplex algorithm also supports this form directly
372
for the sake of convenience.
373

	
374
A feasible solution for this problem can be found using \ref Circulation.
375

	
376
Note that the above formulation is actually more general than the usual
377
definition of the minimum cost flow problem, in which strict equalities
378
are required in the supply/demand contraints, i.e.
379

	
380
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) =
381
    sup(u) \quad \forall u\in V. \f]
382

	
383
However if the sum of the supply values is zero, then these two problems
384
are equivalent. So if you need the equality form, you have to ensure this
385
additional contraint for the algorithms.
386

	
387
The dual solution of the minimum cost flow problem is represented by node 
388
potentials \f$\pi: V\rightarrow\mathbf{Z}\f$.
389
An \f$f: A\rightarrow\mathbf{Z}\f$ feasible solution of the problem
390
is optimal if and only if for some \f$\pi: V\rightarrow\mathbf{Z}\f$
391
node potentials the following \e complementary \e slackness optimality
392
conditions hold.
393

	
394
 - For all \f$uv\in A\f$ arcs:
395
   - if \f$cost^\pi(uv)>0\f$, then \f$f(uv)=lower(uv)\f$;
396
   - if \f$lower(uv)<f(uv)<upper(uv)\f$, then \f$cost^\pi(uv)=0\f$;
397
   - if \f$cost^\pi(uv)<0\f$, then \f$f(uv)=upper(uv)\f$.
398
 - For all \f$u\in V\f$ nodes:
399
   - if \f$\sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \neq sup(u)\f$,
400
     then \f$\pi(u)=0\f$.
401
 
402
Here \f$cost^\pi(uv)\f$ denotes the \e reduced \e cost of the arc
403
\f$uv\in A\f$ with respect to the potential function \f$\pi\f$, i.e.
404
\f[ cost^\pi(uv) = cost(uv) + \pi(u) - \pi(v).\f]
322
circulations. For more information about this problem and its dual
323
solution see \ref min_cost_flow "Minimum Cost Flow Problem".
405 324

	
406 325
\ref NetworkSimplex is an efficient implementation of the primal Network
407 326
Simplex algorithm for finding minimum cost flows. It also provides dual
408 327
solution (node potentials), if an optimal flow is found.
409 328
*/
410 329

	
411 330
/**
412 331
@defgroup min_cut Minimum Cut Algorithms
413 332
@ingroup algs
414 333

	
415 334
\brief Algorithms for finding minimum cut in graphs.
416 335

	
417 336
This group contains the algorithms for finding minimum cut in graphs.
418 337

	
419 338
The \e minimum \e cut \e problem is to find a non-empty and non-complete
420 339
\f$X\f$ subset of the nodes with minimum overall capacity on
421 340
outgoing arcs. Formally, there is a \f$G=(V,A)\f$ digraph, a
422 341
\f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function. The minimum
423 342
cut is the \f$X\f$ solution of the next optimization problem:
424 343

	
425 344
\f[ \min_{X \subset V, X\not\in \{\emptyset, V\}}
426 345
    \sum_{uv\in A, u\in X, v\not\in X}cap(uv) \f]
427 346

	
428 347
LEMON contains several algorithms related to minimum cut problems:
429 348

	
430 349
- \ref HaoOrlin "Hao-Orlin algorithm" for calculating minimum cut
431 350
  in directed graphs.
432 351
- \ref GomoryHu "Gomory-Hu tree computation" for calculating
433 352
  all-pairs minimum cut in undirected graphs.
434 353

	
435 354
If you want to find minimum cut just between two distinict nodes,
436 355
see the \ref max_flow "maximum flow problem".
437 356
*/
438 357

	
439 358
/**
440 359
@defgroup graph_properties Connectivity and Other Graph Properties
441 360
@ingroup algs
442 361
\brief Algorithms for discovering the graph properties
443 362

	
444 363
This group contains the algorithms for discovering the graph properties
445 364
like connectivity, bipartiteness, euler property, simplicity etc.
446 365

	
447 366
\image html edge_biconnected_components.png
448 367
\image latex edge_biconnected_components.eps "bi-edge-connected components" width=\textwidth
449 368
*/
450 369

	
451 370
/**
452 371
@defgroup matching Matching Algorithms
453 372
@ingroup algs
454 373
\brief Algorithms for finding matchings in graphs and bipartite graphs.
455 374

	
456 375
This group contains the algorithms for calculating matchings in graphs.
457 376
The general matching problem is finding a subset of the edges for which
458 377
each node has at most one incident edge.
459 378

	
460 379
There are several different algorithms for calculate matchings in
461 380
graphs. The goal of the matching optimization
462 381
can be finding maximum cardinality, maximum weight or minimum cost
463 382
matching. The search can be constrained to find perfect or
464 383
maximum cardinality matching.
465 384

	
466 385
The matching algorithms implemented in LEMON:
467 386
- \ref MaxMatching Edmond's blossom shrinking algorithm for calculating
468 387
  maximum cardinality matching in general graphs.
469 388
- \ref MaxWeightedMatching Edmond's blossom shrinking algorithm for calculating
470 389
  maximum weighted matching in general graphs.
471 390
- \ref MaxWeightedPerfectMatching
472 391
  Edmond's blossom shrinking algorithm for calculating maximum weighted
473 392
  perfect matching in general graphs.
474 393

	
475 394
\image html bipartite_matching.png
476 395
\image latex bipartite_matching.eps "Bipartite Matching" width=\textwidth
477 396
*/
478 397

	
479 398
/**
480 399
@defgroup spantree Minimum Spanning Tree Algorithms
481 400
@ingroup algs
482
\brief Algorithms for finding a minimum cost spanning tree in a graph.
401
\brief Algorithms for finding minimum cost spanning trees and arborescences.
483 402

	
484
This group contains the algorithms for finding a minimum cost spanning
485
tree in a graph.
403
This group contains the algorithms for finding minimum cost spanning
404
trees and arborescences.
486 405
*/
487 406

	
488 407
/**
489 408
@defgroup auxalg Auxiliary Algorithms
490 409
@ingroup algs
491 410
\brief Auxiliary algorithms implemented in LEMON.
492 411

	
493 412
This group contains some algorithms implemented in LEMON
494 413
in order to make it easier to implement complex algorithms.
495 414
*/
496 415

	
497 416
/**
498 417
@defgroup gen_opt_group General Optimization Tools
499 418
\brief This group contains some general optimization frameworks
500 419
implemented in LEMON.
501 420

	
502 421
This group contains some general optimization frameworks
503 422
implemented in LEMON.
504 423
*/
505 424

	
506 425
/**
507 426
@defgroup lp_group Lp and Mip Solvers
508 427
@ingroup gen_opt_group
509 428
\brief Lp and Mip solver interfaces for LEMON.
510 429

	
511 430
This group contains Lp and Mip solver interfaces for LEMON. The
512 431
various LP solvers could be used in the same manner with this
513 432
interface.
514 433
*/
515 434

	
516 435
/**
517 436
@defgroup utils Tools and Utilities
518 437
\brief Tools and utilities for programming in LEMON
519 438

	
520 439
Tools and utilities for programming in LEMON.
521 440
*/
522 441

	
523 442
/**
524 443
@defgroup gutils Basic Graph Utilities
525 444
@ingroup utils
526 445
\brief Simple basic graph utilities.
527 446

	
528 447
This group contains some simple basic graph utilities.
529 448
*/
530 449

	
531 450
/**
532 451
@defgroup misc Miscellaneous Tools
533 452
@ingroup utils
534 453
\brief Tools for development, debugging and testing.
535 454

	
536 455
This group contains several useful tools for development,
537 456
debugging and testing.
538 457
*/
539 458

	
540 459
/**
541 460
@defgroup timecount Time Measuring and Counting
542 461
@ingroup misc
543 462
\brief Simple tools for measuring the performance of algorithms.
544 463

	
545 464
This group contains simple tools for measuring the performance
546 465
of algorithms.
547 466
*/
548 467

	
549 468
/**
550 469
@defgroup exceptions Exceptions
551 470
@ingroup utils
552 471
\brief Exceptions defined in LEMON.
553 472

	
554 473
This group contains the exceptions defined in LEMON.
555 474
*/
556 475

	
557 476
/**
558 477
@defgroup io_group Input-Output
559 478
\brief Graph Input-Output methods
560 479

	
561 480
This group contains the tools for importing and exporting graphs
562 481
and graph related data. Now it supports the \ref lgf-format
563 482
"LEMON Graph Format", the \c DIMACS format and the encapsulated
564 483
postscript (EPS) format.
565 484
*/
566 485

	
567 486
/**
568 487
@defgroup lemon_io LEMON Graph Format
569 488
@ingroup io_group
570 489
\brief Reading and writing LEMON Graph Format.
571 490

	
572 491
This group contains methods for reading and writing
573 492
\ref lgf-format "LEMON Graph Format".
574 493
*/
575 494

	
576 495
/**
577 496
@defgroup eps_io Postscript Exporting
578 497
@ingroup io_group
579 498
\brief General \c EPS drawer and graph exporter
580 499

	
581 500
This group contains general \c EPS drawing methods and special
582 501
graph exporting tools.
583 502
*/
584 503

	
585 504
/**
586 505
@defgroup dimacs_group DIMACS format
587 506
@ingroup io_group
588 507
\brief Read and write files in DIMACS format
589 508

	
590 509
Tools to read a digraph from or write it to a file in DIMACS format data.
591 510
*/
592 511

	
593 512
/**
594 513
@defgroup nauty_group NAUTY Format
595 514
@ingroup io_group
596 515
\brief Read \e Nauty format
597 516

	
598 517
Tool to read graphs from \e Nauty format data.
599 518
*/
600 519

	
601 520
/**
602 521
@defgroup concept Concepts
603 522
\brief Skeleton classes and concept checking classes
604 523

	
605 524
This group contains the data/algorithm skeletons and concept checking
606 525
classes implemented in LEMON.
607 526

	
608 527
The purpose of the classes in this group is fourfold.
609 528

	
610 529
- These classes contain the documentations of the %concepts. In order
611 530
  to avoid document multiplications, an implementation of a concept
612 531
  simply refers to the corresponding concept class.
613 532

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

	
623 542
- The concept descriptor classes also provide a <em>checker class</em>
624 543
  that makes it possible to check whether a certain implementation of a
625 544
  concept indeed provides all the required features.
626 545

	
627 546
- Finally, They can serve as a skeleton of a new implementation of a concept.
628 547
*/
629 548

	
630 549
/**
631 550
@defgroup graph_concepts Graph Structure Concepts
632 551
@ingroup concept
633 552
\brief Skeleton and concept checking classes for graph structures
634 553

	
635 554
This group contains the skeletons and concept checking classes of LEMON's
636 555
graph structures and helper classes used to implement these.
637 556
*/
638 557

	
639 558
/**
640 559
@defgroup map_concepts Map Concepts
641 560
@ingroup concept
642 561
\brief Skeleton and concept checking classes for maps
643 562

	
644 563
This group contains the skeletons and concept checking classes of maps.
645 564
*/
646 565

	
647 566
/**
648 567
\anchor demoprograms
649 568

	
650 569
@defgroup demos Demo Programs
651 570

	
652 571
Some demo programs are listed here. Their full source codes can be found in
653 572
the \c demo subdirectory of the source tree.
654 573

	
655 574
In order to compile them, use the <tt>make demo</tt> or the
656 575
<tt>make check</tt> commands.
657 576
*/
658 577

	
659 578
/**
660 579
@defgroup tools Standalone Utility Applications
661 580

	
662 581
Some utility applications are listed here.
663 582

	
664 583
The standard compilation procedure (<tt>./configure;make</tt>) will compile
665 584
them, as well.
666 585
*/
667 586

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

	
19 19
/**
20 20
\mainpage LEMON Documentation
21 21

	
22 22
\section intro Introduction
23 23

	
24 24
\subsection whatis What is LEMON
25 25

	
26
LEMON stands for
27
<b>L</b>ibrary of <b>E</b>fficient <b>M</b>odels
26
LEMON stands for <b>L</b>ibrary for <b>E</b>fficient <b>M</b>odeling
28 27
and <b>O</b>ptimization in <b>N</b>etworks.
29 28
It is a C++ template
30 29
library aimed at combinatorial optimization tasks which
31 30
often involve in working
32 31
with graphs.
33 32

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

	
42 41
\subsection howtoread How to read the documentation
43 42

	
44
If you want to get a quick start and see the most important features then
45
take a look at our \ref quicktour
46
"Quick Tour to LEMON" which will guide you along.
47

	
48
If you already feel like using our library, see the
43
If you would like to get to know the library, see
49 44
<a class="el" href="http://lemon.cs.elte.hu/pub/tutorial/">LEMON Tutorial</a>.
50 45

	
51
If you know what you are looking for then try to find it under the
46
If you know what you are looking for, then try to find it under the
52 47
<a class="el" href="modules.html">Modules</a> section.
53 48

	
54 49
If you are a user of the old (0.x) series of LEMON, please check out the
55 50
\ref migration "Migration Guide" for the backward incompatibilities.
56 51
*/
Ignore white space 6 line context
1 1
EXTRA_DIST += \
2 2
	lemon/lemon.pc.in \
3 3
	lemon/CMakeLists.txt
4 4

	
5 5
pkgconfig_DATA += lemon/lemon.pc
6 6

	
7 7
lib_LTLIBRARIES += lemon/libemon.la
8 8

	
9 9
lemon_libemon_la_SOURCES = \
10 10
	lemon/arg_parser.cc \
11 11
	lemon/base.cc \
12 12
	lemon/color.cc \
13 13
	lemon/lp_base.cc \
14 14
	lemon/lp_skeleton.cc \
15 15
	lemon/random.cc \
16 16
	lemon/bits/windows.cc
17 17

	
18 18
nodist_lemon_HEADERS = lemon/config.h	
19 19
	
20 20
lemon_libemon_la_CXXFLAGS = \
21 21
	$(AM_CXXFLAGS) \
22 22
	$(GLPK_CFLAGS) \
23 23
	$(CPLEX_CFLAGS) \
24 24
	$(SOPLEX_CXXFLAGS) \
25 25
	$(CLP_CXXFLAGS) \
26 26
	$(CBC_CXXFLAGS)
27 27

	
28 28
lemon_libemon_la_LDFLAGS = \
29 29
	$(GLPK_LIBS) \
30 30
	$(CPLEX_LIBS) \
31 31
	$(SOPLEX_LIBS) \
32 32
	$(CLP_LIBS) \
33 33
	$(CBC_LIBS)
34 34

	
35 35
if HAVE_GLPK
36 36
lemon_libemon_la_SOURCES += lemon/glpk.cc
37 37
endif
38 38

	
39 39
if HAVE_CPLEX
40 40
lemon_libemon_la_SOURCES += lemon/cplex.cc
41 41
endif
42 42

	
43 43
if HAVE_SOPLEX
44 44
lemon_libemon_la_SOURCES += lemon/soplex.cc
45 45
endif
46 46

	
47 47
if HAVE_CLP
48 48
lemon_libemon_la_SOURCES += lemon/clp.cc
49 49
endif
50 50

	
51 51
if HAVE_CBC
52 52
lemon_libemon_la_SOURCES += lemon/cbc.cc
53 53
endif
54 54

	
55 55
lemon_HEADERS += \
56 56
	lemon/adaptors.h \
57 57
	lemon/arg_parser.h \
58 58
	lemon/assert.h \
59 59
	lemon/bfs.h \
60 60
	lemon/bin_heap.h \
61 61
	lemon/cbc.h \
62 62
	lemon/circulation.h \
63 63
	lemon/clp.h \
64 64
	lemon/color.h \
65 65
	lemon/concept_check.h \
66 66
	lemon/connectivity.h \
67 67
	lemon/counter.h \
68 68
	lemon/core.h \
69 69
	lemon/cplex.h \
70 70
	lemon/dfs.h \
71 71
	lemon/dijkstra.h \
72 72
	lemon/dim2.h \
73 73
	lemon/dimacs.h \
74 74
	lemon/edge_set.h \
75 75
	lemon/elevator.h \
76 76
	lemon/error.h \
77 77
	lemon/euler.h \
78 78
	lemon/full_graph.h \
79 79
	lemon/glpk.h \
80 80
	lemon/gomory_hu.h \
81 81
	lemon/graph_to_eps.h \
82 82
	lemon/grid_graph.h \
83 83
	lemon/hypercube_graph.h \
84 84
	lemon/kruskal.h \
85 85
	lemon/hao_orlin.h \
86 86
	lemon/lgf_reader.h \
87 87
	lemon/lgf_writer.h \
88 88
	lemon/list_graph.h \
89 89
	lemon/lp.h \
90 90
	lemon/lp_base.h \
91 91
	lemon/lp_skeleton.h \
92 92
	lemon/list_graph.h \
93 93
	lemon/maps.h \
94 94
	lemon/matching.h \
95 95
	lemon/math.h \
96 96
	lemon/min_cost_arborescence.h \
97 97
	lemon/nauty_reader.h \
98 98
	lemon/network_simplex.h \
99 99
	lemon/path.h \
100 100
	lemon/preflow.h \
101 101
	lemon/radix_sort.h \
102 102
	lemon/random.h \
103 103
	lemon/smart_graph.h \
104 104
	lemon/soplex.h \
105 105
	lemon/suurballe.h \
106 106
	lemon/time_measure.h \
107 107
	lemon/tolerance.h \
108 108
	lemon/unionfind.h \
109 109
	lemon/bits/windows.h
110 110

	
111 111
bits_HEADERS += \
112 112
	lemon/bits/alteration_notifier.h \
113 113
	lemon/bits/array_map.h \
114
	lemon/bits/base_extender.h \
115 114
	lemon/bits/bezier.h \
116 115
	lemon/bits/default_map.h \
117 116
	lemon/bits/edge_set_extender.h \
118 117
	lemon/bits/enable_if.h \
119 118
	lemon/bits/graph_adaptor_extender.h \
120 119
	lemon/bits/graph_extender.h \
121 120
	lemon/bits/map_extender.h \
122 121
	lemon/bits/path_dump.h \
123 122
	lemon/bits/solver_bits.h \
124 123
	lemon/bits/traits.h \
125 124
	lemon/bits/variant.h \
126 125
	lemon/bits/vector_map.h
127 126

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

	
19 19
#ifndef LEMON_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;
54 54
    DigraphAdaptorBase() : _digraph(0) { }
55 55
    void initialize(DGR& digraph) { _digraph = &digraph; }
56 56

	
57 57
  public:
58 58
    DigraphAdaptorBase(DGR& digraph) : _digraph(&digraph) { }
59 59

	
60 60
    typedef typename DGR::Node Node;
61 61
    typedef typename DGR::Arc Arc;
62 62

	
63 63
    void first(Node& i) const { _digraph->first(i); }
64 64
    void first(Arc& i) const { _digraph->first(i); }
65 65
    void firstIn(Arc& i, const Node& n) const { _digraph->firstIn(i, n); }
66 66
    void firstOut(Arc& i, const Node& n ) const { _digraph->firstOut(i, n); }
67 67

	
68 68
    void next(Node& i) const { _digraph->next(i); }
69 69
    void next(Arc& i) const { _digraph->next(i); }
70 70
    void nextIn(Arc& i) const { _digraph->nextIn(i); }
71 71
    void nextOut(Arc& i) const { _digraph->nextOut(i); }
72 72

	
73 73
    Node source(const Arc& a) const { return _digraph->source(a); }
74 74
    Node target(const Arc& a) const { return _digraph->target(a); }
75 75

	
76 76
    typedef NodeNumTagIndicator<DGR> NodeNumTag;
77 77
    int nodeNum() const { return _digraph->nodeNum(); }
78 78

	
79 79
    typedef ArcNumTagIndicator<DGR> ArcNumTag;
80 80
    int arcNum() const { return _digraph->arcNum(); }
81 81

	
82 82
    typedef FindArcTagIndicator<DGR> FindArcTag;
83 83
    Arc findArc(const Node& u, const Node& v, const Arc& prev = INVALID) const {
84 84
      return _digraph->findArc(u, v, prev);
85 85
    }
86 86

	
87 87
    Node addNode() { return _digraph->addNode(); }
88 88
    Arc addArc(const Node& u, const Node& v) { return _digraph->addArc(u, v); }
89 89

	
90 90
    void erase(const Node& n) { _digraph->erase(n); }
91 91
    void erase(const Arc& a) { _digraph->erase(a); }
92 92

	
93 93
    void clear() { _digraph->clear(); }
94 94

	
95 95
    int id(const Node& n) const { return _digraph->id(n); }
96 96
    int id(const Arc& a) const { return _digraph->id(a); }
97 97

	
98 98
    Node nodeFromId(int ix) const { return _digraph->nodeFromId(ix); }
99 99
    Arc arcFromId(int ix) const { return _digraph->arcFromId(ix); }
100 100

	
101 101
    int maxNodeId() const { return _digraph->maxNodeId(); }
102 102
    int maxArcId() const { return _digraph->maxArcId(); }
103 103

	
104 104
    typedef typename ItemSetTraits<DGR, Node>::ItemNotifier NodeNotifier;
105 105
    NodeNotifier& notifier(Node) const { return _digraph->notifier(Node()); }
106 106

	
107 107
    typedef typename ItemSetTraits<DGR, Arc>::ItemNotifier ArcNotifier;
108 108
    ArcNotifier& notifier(Arc) const { return _digraph->notifier(Arc()); }
109 109

	
110 110
    template <typename V>
111 111
    class NodeMap : public DGR::template NodeMap<V> {
112 112
      typedef typename DGR::template NodeMap<V> Parent;
113 113

	
114 114
    public:
115 115
      explicit NodeMap(const Adaptor& adaptor)
116 116
        : Parent(*adaptor._digraph) {}
117 117
      NodeMap(const Adaptor& adaptor, const V& value)
118 118
        : Parent(*adaptor._digraph, value) { }
119 119

	
120 120
    private:
121 121
      NodeMap& operator=(const NodeMap& cmap) {
122 122
        return operator=<NodeMap>(cmap);
123 123
      }
124 124

	
125 125
      template <typename CMap>
126 126
      NodeMap& operator=(const CMap& cmap) {
127 127
        Parent::operator=(cmap);
128 128
        return *this;
129 129
      }
130 130

	
131 131
    };
132 132

	
133 133
    template <typename V>
134 134
    class ArcMap : public DGR::template ArcMap<V> {
135 135
      typedef typename DGR::template ArcMap<V> Parent;
136 136

	
137 137
    public:
138 138
      explicit ArcMap(const DigraphAdaptorBase<DGR>& adaptor)
139 139
        : Parent(*adaptor._digraph) {}
140 140
      ArcMap(const DigraphAdaptorBase<DGR>& adaptor, const V& value)
141 141
        : Parent(*adaptor._digraph, value) {}
142 142

	
143 143
    private:
144 144
      ArcMap& operator=(const ArcMap& cmap) {
145 145
        return operator=<ArcMap>(cmap);
146 146
      }
147 147

	
148 148
      template <typename CMap>
149 149
      ArcMap& operator=(const CMap& cmap) {
150 150
        Parent::operator=(cmap);
151 151
        return *this;
152 152
      }
153 153

	
154 154
    };
155 155

	
156 156
  };
157 157

	
158 158
  template<typename GR>
159 159
  class GraphAdaptorBase {
160 160
  public:
161 161
    typedef GR Graph;
162 162

	
163 163
  protected:
164 164
    GR* _graph;
165 165

	
166 166
    GraphAdaptorBase() : _graph(0) {}
167 167

	
168 168
    void initialize(GR& graph) { _graph = &graph; }
169 169

	
170 170
  public:
171 171
    GraphAdaptorBase(GR& graph) : _graph(&graph) {}
172 172

	
173 173
    typedef typename GR::Node Node;
174 174
    typedef typename GR::Arc Arc;
175 175
    typedef typename GR::Edge Edge;
176 176

	
177 177
    void first(Node& i) const { _graph->first(i); }
178 178
    void first(Arc& i) const { _graph->first(i); }
179 179
    void first(Edge& i) const { _graph->first(i); }
180 180
    void firstIn(Arc& i, const Node& n) const { _graph->firstIn(i, n); }
181 181
    void firstOut(Arc& i, const Node& n ) const { _graph->firstOut(i, n); }
182 182
    void firstInc(Edge &i, bool &d, const Node &n) const {
183 183
      _graph->firstInc(i, d, n);
184 184
    }
185 185

	
186 186
    void next(Node& i) const { _graph->next(i); }
187 187
    void next(Arc& i) const { _graph->next(i); }
188 188
    void next(Edge& i) const { _graph->next(i); }
189 189
    void nextIn(Arc& i) const { _graph->nextIn(i); }
190 190
    void nextOut(Arc& i) const { _graph->nextOut(i); }
191 191
    void nextInc(Edge &i, bool &d) const { _graph->nextInc(i, d); }
192 192

	
193 193
    Node u(const Edge& e) const { return _graph->u(e); }
194 194
    Node v(const Edge& e) const { return _graph->v(e); }
195 195

	
196 196
    Node source(const Arc& a) const { return _graph->source(a); }
197 197
    Node target(const Arc& a) const { return _graph->target(a); }
198 198

	
199 199
    typedef NodeNumTagIndicator<Graph> NodeNumTag;
200 200
    int nodeNum() const { return _graph->nodeNum(); }
201 201

	
202 202
    typedef ArcNumTagIndicator<Graph> ArcNumTag;
203 203
    int arcNum() const { return _graph->arcNum(); }
204 204

	
205 205
    typedef EdgeNumTagIndicator<Graph> EdgeNumTag;
206 206
    int edgeNum() const { return _graph->edgeNum(); }
207 207

	
208 208
    typedef FindArcTagIndicator<Graph> FindArcTag;
209 209
    Arc findArc(const Node& u, const Node& v,
210 210
                const Arc& prev = INVALID) const {
211 211
      return _graph->findArc(u, v, prev);
212 212
    }
213 213

	
214 214
    typedef FindEdgeTagIndicator<Graph> FindEdgeTag;
215 215
    Edge findEdge(const Node& u, const Node& v,
216 216
                  const Edge& prev = INVALID) const {
217 217
      return _graph->findEdge(u, v, prev);
218 218
    }
219 219

	
220 220
    Node addNode() { return _graph->addNode(); }
221 221
    Edge addEdge(const Node& u, const Node& v) { return _graph->addEdge(u, v); }
222 222

	
223 223
    void erase(const Node& i) { _graph->erase(i); }
224 224
    void erase(const Edge& i) { _graph->erase(i); }
225 225

	
226 226
    void clear() { _graph->clear(); }
227 227

	
228 228
    bool direction(const Arc& a) const { return _graph->direction(a); }
229 229
    Arc direct(const Edge& e, bool d) const { return _graph->direct(e, d); }
230 230

	
231 231
    int id(const Node& v) const { return _graph->id(v); }
232 232
    int id(const Arc& a) const { return _graph->id(a); }
233 233
    int id(const Edge& e) const { return _graph->id(e); }
234 234

	
235 235
    Node nodeFromId(int ix) const { return _graph->nodeFromId(ix); }
236 236
    Arc arcFromId(int ix) const { return _graph->arcFromId(ix); }
237 237
    Edge edgeFromId(int ix) const { return _graph->edgeFromId(ix); }
238 238

	
239 239
    int maxNodeId() const { return _graph->maxNodeId(); }
240 240
    int maxArcId() const { return _graph->maxArcId(); }
241 241
    int maxEdgeId() const { return _graph->maxEdgeId(); }
242 242

	
243 243
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
244 244
    NodeNotifier& notifier(Node) const { return _graph->notifier(Node()); }
245 245

	
246 246
    typedef typename ItemSetTraits<GR, Arc>::ItemNotifier ArcNotifier;
247 247
    ArcNotifier& notifier(Arc) const { return _graph->notifier(Arc()); }
248 248

	
249 249
    typedef typename ItemSetTraits<GR, Edge>::ItemNotifier EdgeNotifier;
250 250
    EdgeNotifier& notifier(Edge) const { return _graph->notifier(Edge()); }
251 251

	
252 252
    template <typename V>
253 253
    class NodeMap : public GR::template NodeMap<V> {
254 254
      typedef typename GR::template NodeMap<V> Parent;
255 255

	
256 256
    public:
257 257
      explicit NodeMap(const GraphAdaptorBase<GR>& adapter)
258 258
        : Parent(*adapter._graph) {}
259 259
      NodeMap(const GraphAdaptorBase<GR>& adapter, const V& value)
260 260
        : Parent(*adapter._graph, value) {}
261 261

	
262 262
    private:
263 263
      NodeMap& operator=(const NodeMap& cmap) {
264 264
        return operator=<NodeMap>(cmap);
265 265
      }
266 266

	
267 267
      template <typename CMap>
268 268
      NodeMap& operator=(const CMap& cmap) {
269 269
        Parent::operator=(cmap);
270 270
        return *this;
271 271
      }
272 272

	
273 273
    };
274 274

	
275 275
    template <typename V>
276 276
    class ArcMap : public GR::template ArcMap<V> {
277 277
      typedef typename GR::template ArcMap<V> Parent;
278 278

	
279 279
    public:
280 280
      explicit ArcMap(const GraphAdaptorBase<GR>& adapter)
281 281
        : Parent(*adapter._graph) {}
282 282
      ArcMap(const GraphAdaptorBase<GR>& adapter, const V& value)
283 283
        : Parent(*adapter._graph, value) {}
284 284

	
285 285
    private:
286 286
      ArcMap& operator=(const ArcMap& cmap) {
287 287
        return operator=<ArcMap>(cmap);
288 288
      }
289 289

	
290 290
      template <typename CMap>
291 291
      ArcMap& operator=(const CMap& cmap) {
292 292
        Parent::operator=(cmap);
293 293
        return *this;
294 294
      }
295 295
    };
296 296

	
297 297
    template <typename V>
298 298
    class EdgeMap : public GR::template EdgeMap<V> {
299 299
      typedef typename GR::template EdgeMap<V> Parent;
300 300

	
301 301
    public:
302 302
      explicit EdgeMap(const GraphAdaptorBase<GR>& adapter)
303 303
        : Parent(*adapter._graph) {}
304 304
      EdgeMap(const GraphAdaptorBase<GR>& adapter, const V& value)
305 305
        : Parent(*adapter._graph, value) {}
306 306

	
307 307
    private:
308 308
      EdgeMap& operator=(const EdgeMap& cmap) {
309 309
        return operator=<EdgeMap>(cmap);
310 310
      }
311 311

	
312 312
      template <typename CMap>
313 313
      EdgeMap& operator=(const CMap& cmap) {
314 314
        Parent::operator=(cmap);
315 315
        return *this;
316 316
      }
317 317
    };
318 318

	
319 319
  };
320 320

	
321 321
  template <typename DGR>
322 322
  class ReverseDigraphBase : public DigraphAdaptorBase<DGR> {
323 323
    typedef DigraphAdaptorBase<DGR> Parent;
324 324
  public:
325 325
    typedef DGR Digraph;
326 326
  protected:
327 327
    ReverseDigraphBase() : Parent() { }
328 328
  public:
329 329
    typedef typename Parent::Node Node;
330 330
    typedef typename Parent::Arc Arc;
331 331

	
332 332
    void firstIn(Arc& a, const Node& n) const { Parent::firstOut(a, n); }
333 333
    void firstOut(Arc& a, const Node& n ) const { Parent::firstIn(a, n); }
334 334

	
335 335
    void nextIn(Arc& a) const { Parent::nextOut(a); }
336 336
    void nextOut(Arc& a) const { Parent::nextIn(a); }
337 337

	
338 338
    Node source(const Arc& a) const { return Parent::target(a); }
339 339
    Node target(const Arc& a) const { return Parent::source(a); }
340 340

	
341 341
    Arc addArc(const Node& u, const Node& v) { return Parent::addArc(v, u); }
342 342

	
343 343
    typedef FindArcTagIndicator<DGR> FindArcTag;
344 344
    Arc findArc(const Node& u, const Node& v,
345 345
                const Arc& prev = INVALID) const {
346 346
      return Parent::findArc(v, u, prev);
347 347
    }
348 348

	
349 349
  };
350 350

	
351 351
  /// \ingroup graph_adaptors
352 352
  ///
353 353
  /// \brief Adaptor class for reversing the orientation of the arcs in
354 354
  /// a digraph.
355 355
  ///
356 356
  /// ReverseDigraph can be used for reversing the arcs in a digraph.
357 357
  /// It conforms to the \ref concepts::Digraph "Digraph" concept.
358 358
  ///
359 359
  /// The adapted digraph can also be modified through this adaptor
360 360
  /// by adding or removing nodes or arcs, unless the \c GR template
361 361
  /// parameter is set to be \c const.
362 362
  ///
363 363
  /// \tparam DGR The type of the adapted digraph.
364 364
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
365 365
  /// It can also be specified to be \c const.
366 366
  ///
367 367
  /// \note The \c Node and \c Arc types of this adaptor and the adapted
368 368
  /// digraph are convertible to each other.
369 369
  template<typename DGR>
370 370
#ifdef DOXYGEN
371 371
  class ReverseDigraph {
372 372
#else
373 373
  class ReverseDigraph :
374 374
    public DigraphAdaptorExtender<ReverseDigraphBase<DGR> > {
375 375
#endif
376 376
    typedef DigraphAdaptorExtender<ReverseDigraphBase<DGR> > Parent;
377 377
  public:
378 378
    /// The type of the adapted digraph.
379 379
    typedef DGR Digraph;
380 380
  protected:
381 381
    ReverseDigraph() { }
382 382
  public:
383 383

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

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

	
402 402

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

	
411 411
    typedef SubDigraphBase Adaptor;
412 412
  protected:
413 413
    NF* _node_filter;
414 414
    AF* _arc_filter;
415 415
    SubDigraphBase()
416 416
      : Parent(), _node_filter(0), _arc_filter(0) { }
417 417

	
418 418
    void initialize(DGR& digraph, NF& node_filter, AF& arc_filter) {
419 419
      Parent::initialize(digraph);
420 420
      _node_filter = &node_filter;
421 421
      _arc_filter = &arc_filter;      
422 422
    }
423 423

	
424 424
  public:
425 425

	
426 426
    typedef typename Parent::Node Node;
427 427
    typedef typename Parent::Arc Arc;
428 428

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

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

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

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

	
456 456
    void next(Node& i) const {
457 457
      Parent::next(i);
458 458
      while (i != INVALID && !(*_node_filter)[i]) Parent::next(i);
459 459
    }
460 460

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

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

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

	
483 483
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
484 484
    void status(const Arc& a, bool v) const { _arc_filter->set(a, v); }
485 485

	
486 486
    bool status(const Node& n) const { return (*_node_filter)[n]; }
487 487
    bool status(const Arc& a) const { return (*_arc_filter)[a]; }
488 488

	
489 489
    typedef False NodeNumTag;
490 490
    typedef False ArcNumTag;
491 491

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

	
505 505
  public:
506 506

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

	
514 514
    public:
515 515
      typedef V Value;
516 516

	
517 517
      NodeMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor)
518 518
        : Parent(adaptor) {}
519 519
      NodeMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor, const V& value)
520 520
        : Parent(adaptor, value) {}
521 521

	
522 522
    private:
523 523
      NodeMap& operator=(const NodeMap& cmap) {
524 524
        return operator=<NodeMap>(cmap);
525 525
      }
526 526

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

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

	
541 541
    public:
542 542
      typedef V Value;
543 543

	
544 544
      ArcMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor)
545 545
        : Parent(adaptor) {}
546 546
      ArcMap(const SubDigraphBase<DGR, NF, AF, ch>& adaptor, const V& value)
547 547
        : Parent(adaptor, value) {}
548 548

	
549 549
    private:
550 550
      ArcMap& operator=(const ArcMap& cmap) {
551 551
        return operator=<ArcMap>(cmap);
552 552
      }
553 553

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

	
561 561
  };
562 562

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

	
572 572
    typedef SubDigraphBase Adaptor;
573 573
  protected:
574 574
    NF* _node_filter;
575 575
    AF* _arc_filter;
576 576
    SubDigraphBase()
577 577
      : Parent(), _node_filter(0), _arc_filter(0) { }
578 578

	
579 579
    void initialize(DGR& digraph, NF& node_filter, AF& arc_filter) {
580 580
      Parent::initialize(digraph);
581 581
      _node_filter = &node_filter;
582 582
      _arc_filter = &arc_filter;      
583 583
    }
584 584

	
585 585
  public:
586 586

	
587 587
    typedef typename Parent::Node Node;
588 588
    typedef typename Parent::Arc Arc;
589 589

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

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

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

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

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

	
623 623
    void nextOut(Arc& i) const {
624 624
      Parent::nextOut(i);
625 625
      while (i!=INVALID && !(*_arc_filter)[i]) Parent::nextOut(i);
626 626
    }
627 627

	
628 628
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
629 629
    void status(const Arc& a, bool v) const { _arc_filter->set(a, v); }
630 630

	
631 631
    bool status(const Node& n) const { return (*_node_filter)[n]; }
632 632
    bool status(const Arc& a) const { return (*_arc_filter)[a]; }
633 633

	
634 634
    typedef False NodeNumTag;
635 635
    typedef False ArcNumTag;
636 636

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

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

	
657 657
    public:
658 658
      typedef V Value;
659 659

	
660 660
      NodeMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor)
661 661
        : Parent(adaptor) {}
662 662
      NodeMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor, const V& value)
663 663
        : Parent(adaptor, value) {}
664 664

	
665 665
    private:
666 666
      NodeMap& operator=(const NodeMap& cmap) {
667 667
        return operator=<NodeMap>(cmap);
668 668
      }
669 669

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

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

	
684 684
    public:
685 685
      typedef V Value;
686 686

	
687 687
      ArcMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor)
688 688
        : Parent(adaptor) {}
689 689
      ArcMap(const SubDigraphBase<DGR, NF, AF, false>& adaptor, const V& value)
690 690
        : Parent(adaptor, value) {}
691 691

	
692 692
    private:
693 693
      ArcMap& operator=(const ArcMap& cmap) {
694 694
        return operator=<ArcMap>(cmap);
695 695
      }
696 696

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

	
704 704
  };
705 705

	
706 706
  /// \ingroup graph_adaptors
707 707
  ///
708 708
  /// \brief Adaptor class for hiding nodes and arcs in a digraph
709 709
  ///
710 710
  /// SubDigraph can be used for hiding nodes and arcs in a digraph.
711 711
  /// A \c bool node map and a \c bool arc map must be specified, which
712 712
  /// define the filters for nodes and arcs.
713 713
  /// Only the nodes and arcs with \c true filter value are
714 714
  /// shown in the subdigraph. The arcs that are incident to hidden
715 715
  /// nodes are also filtered out.
716 716
  /// This adaptor conforms to the \ref concepts::Digraph "Digraph" concept.
717 717
  ///
718 718
  /// The adapted digraph can also be modified through this adaptor
719 719
  /// by adding or removing nodes or arcs, unless the \c GR template
720 720
  /// parameter is set to be \c const.
721 721
  ///
722 722
  /// \tparam DGR The type of the adapted digraph.
723 723
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
724 724
  /// It can also be specified to be \c const.
725 725
  /// \tparam NF The type of the node filter map.
726 726
  /// It must be a \c bool (or convertible) node map of the
727 727
  /// adapted digraph. The default type is
728 728
  /// \ref concepts::Digraph::NodeMap "DGR::NodeMap<bool>".
729 729
  /// \tparam AF The type of the arc filter map.
730 730
  /// It must be \c bool (or convertible) arc map of the
731 731
  /// adapted digraph. The default type is
732 732
  /// \ref concepts::Digraph::ArcMap "DGR::ArcMap<bool>".
733 733
  ///
734 734
  /// \note The \c Node and \c Arc types of this adaptor and the adapted
735 735
  /// digraph are convertible to each other.
736 736
  ///
737 737
  /// \see FilterNodes
738 738
  /// \see FilterArcs
739 739
#ifdef DOXYGEN
740 740
  template<typename DGR, typename NF, typename AF>
741 741
  class SubDigraph {
742 742
#else
743 743
  template<typename DGR,
744 744
           typename NF = typename DGR::template NodeMap<bool>,
745 745
           typename AF = typename DGR::template ArcMap<bool> >
746 746
  class SubDigraph :
747 747
    public DigraphAdaptorExtender<SubDigraphBase<DGR, NF, AF, true> > {
748 748
#endif
749 749
  public:
750 750
    /// The type of the adapted digraph.
751 751
    typedef DGR Digraph;
752 752
    /// The type of the node filter map.
753 753
    typedef NF NodeFilterMap;
754 754
    /// The type of the arc filter map.
755 755
    typedef AF ArcFilterMap;
756 756

	
757 757
    typedef DigraphAdaptorExtender<SubDigraphBase<DGR, NF, AF, true> >
758 758
      Parent;
759 759

	
760 760
    typedef typename Parent::Node Node;
761 761
    typedef typename Parent::Arc Arc;
762 762

	
763 763
  protected:
764 764
    SubDigraph() { }
765 765
  public:
766 766

	
767 767
    /// \brief Constructor
768 768
    ///
769 769
    /// Creates a subdigraph for the given digraph with the
770 770
    /// given node and arc filter maps.
771 771
    SubDigraph(DGR& digraph, NF& node_filter, AF& arc_filter) {
772 772
      Parent::initialize(digraph, node_filter, arc_filter);
773 773
    }
774 774

	
775 775
    /// \brief Sets the status of the given node
776 776
    ///
777 777
    /// This function sets the status of the given node.
778 778
    /// It is done by simply setting the assigned value of \c n
779 779
    /// to \c v in the node filter map.
780 780
    void status(const Node& n, bool v) const { Parent::status(n, v); }
781 781

	
782 782
    /// \brief Sets the status of the given arc
783 783
    ///
784 784
    /// This function sets the status of the given arc.
785 785
    /// It is done by simply setting the assigned value of \c a
786 786
    /// to \c v in the arc filter map.
787 787
    void status(const Arc& a, bool v) const { Parent::status(a, v); }
788 788

	
789 789
    /// \brief Returns the status of the given node
790 790
    ///
791 791
    /// This function returns the status of the given node.
792 792
    /// It is \c true if the given node is enabled (i.e. not hidden).
793 793
    bool status(const Node& n) const { return Parent::status(n); }
794 794

	
795 795
    /// \brief Returns the status of the given arc
796 796
    ///
797 797
    /// This function returns the status of the given arc.
798 798
    /// It is \c true if the given arc is enabled (i.e. not hidden).
799 799
    bool status(const Arc& a) const { return Parent::status(a); }
800 800

	
801 801
    /// \brief Disables the given node
802 802
    ///
803 803
    /// This function disables the given node in the subdigraph,
804 804
    /// so the iteration jumps over it.
805 805
    /// It is the same as \ref status() "status(n, false)".
806 806
    void disable(const Node& n) const { Parent::status(n, false); }
807 807

	
808 808
    /// \brief Disables the given arc
809 809
    ///
810 810
    /// This function disables the given arc in the subdigraph,
811 811
    /// so the iteration jumps over it.
812 812
    /// It is the same as \ref status() "status(a, false)".
813 813
    void disable(const Arc& a) const { Parent::status(a, false); }
814 814

	
815 815
    /// \brief Enables the given node
816 816
    ///
817 817
    /// This function enables the given node in the subdigraph.
818 818
    /// It is the same as \ref status() "status(n, true)".
819 819
    void enable(const Node& n) const { Parent::status(n, true); }
820 820

	
821 821
    /// \brief Enables the given arc
822 822
    ///
823 823
    /// This function enables the given arc in the subdigraph.
824 824
    /// It is the same as \ref status() "status(a, true)".
825 825
    void enable(const Arc& a) const { Parent::status(a, true); }
826 826

	
827 827
  };
828 828

	
829 829
  /// \brief Returns a read-only SubDigraph adaptor
830 830
  ///
831 831
  /// This function just returns a read-only \ref SubDigraph adaptor.
832 832
  /// \ingroup graph_adaptors
833 833
  /// \relates SubDigraph
834 834
  template<typename DGR, typename NF, typename AF>
835 835
  SubDigraph<const DGR, NF, AF>
836 836
  subDigraph(const DGR& digraph,
837 837
             NF& node_filter, AF& arc_filter) {
838 838
    return SubDigraph<const DGR, NF, AF>
839 839
      (digraph, node_filter, arc_filter);
840 840
  }
841 841

	
842 842
  template<typename DGR, typename NF, typename AF>
843 843
  SubDigraph<const DGR, const NF, AF>
844 844
  subDigraph(const DGR& digraph,
845 845
             const NF& node_filter, AF& arc_filter) {
846 846
    return SubDigraph<const DGR, const NF, AF>
847 847
      (digraph, node_filter, arc_filter);
848 848
  }
849 849

	
850 850
  template<typename DGR, typename NF, typename AF>
851 851
  SubDigraph<const DGR, NF, const AF>
852 852
  subDigraph(const DGR& digraph,
853 853
             NF& node_filter, const AF& arc_filter) {
854 854
    return SubDigraph<const DGR, NF, const AF>
855 855
      (digraph, node_filter, arc_filter);
856 856
  }
857 857

	
858 858
  template<typename DGR, typename NF, typename AF>
859 859
  SubDigraph<const DGR, const NF, const AF>
860 860
  subDigraph(const DGR& digraph,
861 861
             const NF& node_filter, const AF& arc_filter) {
862 862
    return SubDigraph<const DGR, const NF, const AF>
863 863
      (digraph, node_filter, arc_filter);
864 864
  }
865 865

	
866 866

	
867 867
  template <typename GR, typename NF, typename EF, bool ch = true>
868 868
  class SubGraphBase : public GraphAdaptorBase<GR> {
869 869
    typedef GraphAdaptorBase<GR> Parent;
870 870
  public:
871 871
    typedef GR Graph;
872 872
    typedef NF NodeFilterMap;
873 873
    typedef EF EdgeFilterMap;
874 874

	
875 875
    typedef SubGraphBase Adaptor;
876 876
  protected:
877 877

	
878 878
    NF* _node_filter;
879 879
    EF* _edge_filter;
880 880

	
881 881
    SubGraphBase()
882 882
      : Parent(), _node_filter(0), _edge_filter(0) { }
883 883

	
884 884
    void initialize(GR& graph, NF& node_filter, EF& edge_filter) {
885 885
      Parent::initialize(graph);
886 886
      _node_filter = &node_filter;
887 887
      _edge_filter = &edge_filter;
888 888
    }
889 889

	
890 890
  public:
891 891

	
892 892
    typedef typename Parent::Node Node;
893 893
    typedef typename Parent::Arc Arc;
894 894
    typedef typename Parent::Edge Edge;
895 895

	
896 896
    void first(Node& i) const {
897 897
      Parent::first(i);
898 898
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
899 899
    }
900 900

	
901 901
    void first(Arc& i) const {
902 902
      Parent::first(i);
903 903
      while (i!=INVALID && (!(*_edge_filter)[i]
904 904
                            || !(*_node_filter)[Parent::source(i)]
905 905
                            || !(*_node_filter)[Parent::target(i)]))
906 906
        Parent::next(i);
907 907
    }
908 908

	
909 909
    void first(Edge& i) const {
910 910
      Parent::first(i);
911 911
      while (i!=INVALID && (!(*_edge_filter)[i]
912 912
                            || !(*_node_filter)[Parent::u(i)]
913 913
                            || !(*_node_filter)[Parent::v(i)]))
914 914
        Parent::next(i);
915 915
    }
916 916

	
917 917
    void firstIn(Arc& i, const Node& n) const {
918 918
      Parent::firstIn(i, n);
919 919
      while (i!=INVALID && (!(*_edge_filter)[i]
920 920
                            || !(*_node_filter)[Parent::source(i)]))
921 921
        Parent::nextIn(i);
922 922
    }
923 923

	
924 924
    void firstOut(Arc& i, const Node& n) const {
925 925
      Parent::firstOut(i, n);
926 926
      while (i!=INVALID && (!(*_edge_filter)[i]
927 927
                            || !(*_node_filter)[Parent::target(i)]))
928 928
        Parent::nextOut(i);
929 929
    }
930 930

	
931 931
    void firstInc(Edge& i, bool& d, const Node& n) const {
932 932
      Parent::firstInc(i, d, n);
933 933
      while (i!=INVALID && (!(*_edge_filter)[i]
934 934
                            || !(*_node_filter)[Parent::u(i)]
935 935
                            || !(*_node_filter)[Parent::v(i)]))
936 936
        Parent::nextInc(i, d);
937 937
    }
938 938

	
939 939
    void next(Node& i) const {
940 940
      Parent::next(i);
941 941
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
942 942
    }
943 943

	
944 944
    void next(Arc& i) const {
945 945
      Parent::next(i);
946 946
      while (i!=INVALID && (!(*_edge_filter)[i]
947 947
                            || !(*_node_filter)[Parent::source(i)]
948 948
                            || !(*_node_filter)[Parent::target(i)]))
949 949
        Parent::next(i);
950 950
    }
951 951

	
952 952
    void next(Edge& i) const {
953 953
      Parent::next(i);
954 954
      while (i!=INVALID && (!(*_edge_filter)[i]
955 955
                            || !(*_node_filter)[Parent::u(i)]
956 956
                            || !(*_node_filter)[Parent::v(i)]))
957 957
        Parent::next(i);
958 958
    }
959 959

	
960 960
    void nextIn(Arc& i) const {
961 961
      Parent::nextIn(i);
962 962
      while (i!=INVALID && (!(*_edge_filter)[i]
963 963
                            || !(*_node_filter)[Parent::source(i)]))
964 964
        Parent::nextIn(i);
965 965
    }
966 966

	
967 967
    void nextOut(Arc& i) const {
968 968
      Parent::nextOut(i);
969 969
      while (i!=INVALID && (!(*_edge_filter)[i]
970 970
                            || !(*_node_filter)[Parent::target(i)]))
971 971
        Parent::nextOut(i);
972 972
    }
973 973

	
974 974
    void nextInc(Edge& i, bool& d) const {
975 975
      Parent::nextInc(i, d);
976 976
      while (i!=INVALID && (!(*_edge_filter)[i]
977 977
                            || !(*_node_filter)[Parent::u(i)]
978 978
                            || !(*_node_filter)[Parent::v(i)]))
979 979
        Parent::nextInc(i, d);
980 980
    }
981 981

	
982 982
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
983 983
    void status(const Edge& e, bool v) const { _edge_filter->set(e, v); }
984 984

	
985 985
    bool status(const Node& n) const { return (*_node_filter)[n]; }
986 986
    bool status(const Edge& e) const { return (*_edge_filter)[e]; }
987 987

	
988 988
    typedef False NodeNumTag;
989 989
    typedef False ArcNumTag;
990 990
    typedef False EdgeNumTag;
991 991

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

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

	
1018 1018
    template <typename V>
1019 1019
    class NodeMap 
1020 1020
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1021 1021
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> {
1022 1022
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1023 1023
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> Parent;
1024 1024

	
1025 1025
    public:
1026 1026
      typedef V Value;
1027 1027

	
1028 1028
      NodeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1029 1029
        : Parent(adaptor) {}
1030 1030
      NodeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1031 1031
        : Parent(adaptor, value) {}
1032 1032

	
1033 1033
    private:
1034 1034
      NodeMap& operator=(const NodeMap& cmap) {
1035 1035
        return operator=<NodeMap>(cmap);
1036 1036
      }
1037 1037

	
1038 1038
      template <typename CMap>
1039 1039
      NodeMap& operator=(const CMap& cmap) {
1040 1040
        Parent::operator=(cmap);
1041 1041
        return *this;
1042 1042
      }
1043 1043
    };
1044 1044

	
1045 1045
    template <typename V>
1046 1046
    class ArcMap 
1047 1047
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1048 1048
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> {
1049 1049
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1050 1050
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> Parent;
1051 1051

	
1052 1052
    public:
1053 1053
      typedef V Value;
1054 1054

	
1055 1055
      ArcMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1056 1056
        : Parent(adaptor) {}
1057 1057
      ArcMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1058 1058
        : Parent(adaptor, value) {}
1059 1059

	
1060 1060
    private:
1061 1061
      ArcMap& operator=(const ArcMap& cmap) {
1062 1062
        return operator=<ArcMap>(cmap);
1063 1063
      }
1064 1064

	
1065 1065
      template <typename CMap>
1066 1066
      ArcMap& operator=(const CMap& cmap) {
1067 1067
        Parent::operator=(cmap);
1068 1068
        return *this;
1069 1069
      }
1070 1070
    };
1071 1071

	
1072 1072
    template <typename V>
1073 1073
    class EdgeMap 
1074 1074
      : public SubMapExtender<SubGraphBase<GR, NF, EF, ch>,
1075 1075
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> {
1076 1076
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, ch>, 
1077 1077
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> Parent;
1078 1078

	
1079 1079
    public:
1080 1080
      typedef V Value;
1081 1081

	
1082 1082
      EdgeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor)
1083 1083
        : Parent(adaptor) {}
1084 1084

	
1085 1085
      EdgeMap(const SubGraphBase<GR, NF, EF, ch>& adaptor, const V& value)
1086 1086
        : Parent(adaptor, value) {}
1087 1087

	
1088 1088
    private:
1089 1089
      EdgeMap& operator=(const EdgeMap& cmap) {
1090 1090
        return operator=<EdgeMap>(cmap);
1091 1091
      }
1092 1092

	
1093 1093
      template <typename CMap>
1094 1094
      EdgeMap& operator=(const CMap& cmap) {
1095 1095
        Parent::operator=(cmap);
1096 1096
        return *this;
1097 1097
      }
1098 1098
    };
1099 1099

	
1100 1100
  };
1101 1101

	
1102 1102
  template <typename GR, typename NF, typename EF>
1103 1103
  class SubGraphBase<GR, NF, EF, false>
1104 1104
    : public GraphAdaptorBase<GR> {
1105 1105
    typedef GraphAdaptorBase<GR> Parent;
1106 1106
  public:
1107 1107
    typedef GR Graph;
1108 1108
    typedef NF NodeFilterMap;
1109 1109
    typedef EF EdgeFilterMap;
1110 1110

	
1111 1111
    typedef SubGraphBase Adaptor;
1112 1112
  protected:
1113 1113
    NF* _node_filter;
1114 1114
    EF* _edge_filter;
1115 1115
    SubGraphBase() 
1116 1116
	  : Parent(), _node_filter(0), _edge_filter(0) { }
1117 1117

	
1118 1118
    void initialize(GR& graph, NF& node_filter, EF& edge_filter) {
1119 1119
      Parent::initialize(graph);
1120 1120
      _node_filter = &node_filter;
1121 1121
      _edge_filter = &edge_filter;
1122 1122
    }
1123 1123

	
1124 1124
  public:
1125 1125

	
1126 1126
    typedef typename Parent::Node Node;
1127 1127
    typedef typename Parent::Arc Arc;
1128 1128
    typedef typename Parent::Edge Edge;
1129 1129

	
1130 1130
    void first(Node& i) const {
1131 1131
      Parent::first(i);
1132 1132
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
1133 1133
    }
1134 1134

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

	
1140 1140
    void first(Edge& 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 firstIn(Arc& i, const Node& n) const {
1146 1146
      Parent::firstIn(i, n);
1147 1147
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextIn(i);
1148 1148
    }
1149 1149

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

	
1155 1155
    void firstInc(Edge& i, bool& d, const Node& n) const {
1156 1156
      Parent::firstInc(i, d, n);
1157 1157
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextInc(i, d);
1158 1158
    }
1159 1159

	
1160 1160
    void next(Node& i) const {
1161 1161
      Parent::next(i);
1162 1162
      while (i!=INVALID && !(*_node_filter)[i]) Parent::next(i);
1163 1163
    }
1164 1164
    void next(Arc& i) const {
1165 1165
      Parent::next(i);
1166 1166
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1167 1167
    }
1168 1168
    void next(Edge& i) const {
1169 1169
      Parent::next(i);
1170 1170
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::next(i);
1171 1171
    }
1172 1172
    void nextIn(Arc& i) const {
1173 1173
      Parent::nextIn(i);
1174 1174
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextIn(i);
1175 1175
    }
1176 1176

	
1177 1177
    void nextOut(Arc& i) const {
1178 1178
      Parent::nextOut(i);
1179 1179
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextOut(i);
1180 1180
    }
1181 1181
    void nextInc(Edge& i, bool& d) const {
1182 1182
      Parent::nextInc(i, d);
1183 1183
      while (i!=INVALID && !(*_edge_filter)[i]) Parent::nextInc(i, d);
1184 1184
    }
1185 1185

	
1186 1186
    void status(const Node& n, bool v) const { _node_filter->set(n, v); }
1187 1187
    void status(const Edge& e, bool v) const { _edge_filter->set(e, v); }
1188 1188

	
1189 1189
    bool status(const Node& n) const { return (*_node_filter)[n]; }
1190 1190
    bool status(const Edge& e) const { return (*_edge_filter)[e]; }
1191 1191

	
1192 1192
    typedef False NodeNumTag;
1193 1193
    typedef False ArcNumTag;
1194 1194
    typedef False EdgeNumTag;
1195 1195

	
1196 1196
    typedef FindArcTagIndicator<Graph> FindArcTag;
1197 1197
    Arc findArc(const Node& u, const Node& v,
1198 1198
                const Arc& prev = INVALID) const {
1199 1199
      Arc arc = Parent::findArc(u, v, prev);
1200 1200
      while (arc != INVALID && !(*_edge_filter)[arc]) {
1201 1201
        arc = Parent::findArc(u, v, arc);
1202 1202
      }
1203 1203
      return arc;
1204 1204
    }
1205 1205

	
1206 1206
    typedef FindEdgeTagIndicator<Graph> FindEdgeTag;
1207 1207
    Edge findEdge(const Node& u, const Node& v,
1208 1208
                  const Edge& prev = INVALID) const {
1209 1209
      Edge edge = Parent::findEdge(u, v, prev);
1210 1210
      while (edge != INVALID && !(*_edge_filter)[edge]) {
1211 1211
        edge = Parent::findEdge(u, v, edge);
1212 1212
      }
1213 1213
      return edge;
1214 1214
    }
1215 1215

	
1216 1216
    template <typename V>
1217 1217
    class NodeMap 
1218 1218
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1219 1219
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> {
1220 1220
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1221 1221
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, NodeMap<V>)> Parent;
1222 1222

	
1223 1223
    public:
1224 1224
      typedef V Value;
1225 1225

	
1226 1226
      NodeMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1227 1227
        : Parent(adaptor) {}
1228 1228
      NodeMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1229 1229
        : Parent(adaptor, value) {}
1230 1230

	
1231 1231
    private:
1232 1232
      NodeMap& operator=(const NodeMap& cmap) {
1233 1233
        return operator=<NodeMap>(cmap);
1234 1234
      }
1235 1235

	
1236 1236
      template <typename CMap>
1237 1237
      NodeMap& operator=(const CMap& cmap) {
1238 1238
        Parent::operator=(cmap);
1239 1239
        return *this;
1240 1240
      }
1241 1241
    };
1242 1242

	
1243 1243
    template <typename V>
1244 1244
    class ArcMap 
1245 1245
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1246 1246
          LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> {
1247 1247
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1248 1248
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, ArcMap<V>)> Parent;
1249 1249

	
1250 1250
    public:
1251 1251
      typedef V Value;
1252 1252

	
1253 1253
      ArcMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1254 1254
        : Parent(adaptor) {}
1255 1255
      ArcMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1256 1256
        : Parent(adaptor, value) {}
1257 1257

	
1258 1258
    private:
1259 1259
      ArcMap& operator=(const ArcMap& cmap) {
1260 1260
        return operator=<ArcMap>(cmap);
1261 1261
      }
1262 1262

	
1263 1263
      template <typename CMap>
1264 1264
      ArcMap& operator=(const CMap& cmap) {
1265 1265
        Parent::operator=(cmap);
1266 1266
        return *this;
1267 1267
      }
1268 1268
    };
1269 1269

	
1270 1270
    template <typename V>
1271 1271
    class EdgeMap 
1272 1272
      : public SubMapExtender<SubGraphBase<GR, NF, EF, false>,
1273 1273
        LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> {
1274 1274
      typedef SubMapExtender<SubGraphBase<GR, NF, EF, false>, 
1275 1275
	LEMON_SCOPE_FIX(GraphAdaptorBase<GR>, EdgeMap<V>)> Parent;
1276 1276

	
1277 1277
    public:
1278 1278
      typedef V Value;
1279 1279

	
1280 1280
      EdgeMap(const SubGraphBase<GR, NF, EF, false>& adaptor)
1281 1281
        : Parent(adaptor) {}
1282 1282

	
1283 1283
      EdgeMap(const SubGraphBase<GR, NF, EF, false>& adaptor, const V& value)
1284 1284
        : Parent(adaptor, value) {}
1285 1285

	
1286 1286
    private:
1287 1287
      EdgeMap& operator=(const EdgeMap& cmap) {
1288 1288
        return operator=<EdgeMap>(cmap);
1289 1289
      }
1290 1290

	
1291 1291
      template <typename CMap>
1292 1292
      EdgeMap& operator=(const CMap& cmap) {
1293 1293
        Parent::operator=(cmap);
1294 1294
        return *this;
1295 1295
      }
1296 1296
    };
1297 1297

	
1298 1298
  };
1299 1299

	
1300 1300
  /// \ingroup graph_adaptors
1301 1301
  ///
1302 1302
  /// \brief Adaptor class for hiding nodes and edges in an undirected
1303 1303
  /// graph.
1304 1304
  ///
1305 1305
  /// SubGraph can be used for hiding nodes and edges in a graph.
1306 1306
  /// A \c bool node map and a \c bool edge map must be specified, which
1307 1307
  /// define the filters for nodes and edges.
1308 1308
  /// Only the nodes and edges with \c true filter value are
1309 1309
  /// shown in the subgraph. The edges that are incident to hidden
1310 1310
  /// nodes are also filtered out.
1311 1311
  /// This adaptor conforms to the \ref concepts::Graph "Graph" concept.
1312 1312
  ///
1313 1313
  /// The adapted graph can also be modified through this adaptor
1314 1314
  /// by adding or removing nodes or edges, unless the \c GR template
1315 1315
  /// parameter is set to be \c const.
1316 1316
  ///
1317 1317
  /// \tparam GR The type of the adapted graph.
1318 1318
  /// It must conform to the \ref concepts::Graph "Graph" concept.
1319 1319
  /// It can also be specified to be \c const.
1320 1320
  /// \tparam NF The type of the node filter map.
1321 1321
  /// It must be a \c bool (or convertible) node map of the
1322 1322
  /// adapted graph. The default type is
1323 1323
  /// \ref concepts::Graph::NodeMap "GR::NodeMap<bool>".
1324 1324
  /// \tparam EF The type of the edge filter map.
1325 1325
  /// It must be a \c bool (or convertible) edge map of the
1326 1326
  /// adapted graph. The default type is
1327 1327
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<bool>".
1328 1328
  ///
1329 1329
  /// \note The \c Node, \c Edge and \c Arc types of this adaptor and the
1330 1330
  /// adapted graph are convertible to each other.
1331 1331
  ///
1332 1332
  /// \see FilterNodes
1333 1333
  /// \see FilterEdges
1334 1334
#ifdef DOXYGEN
1335 1335
  template<typename GR, typename NF, typename EF>
1336 1336
  class SubGraph {
1337 1337
#else
1338 1338
  template<typename GR,
1339 1339
           typename NF = typename GR::template NodeMap<bool>,
1340 1340
           typename EF = typename GR::template EdgeMap<bool> >
1341 1341
  class SubGraph :
1342 1342
    public GraphAdaptorExtender<SubGraphBase<GR, NF, EF, true> > {
1343 1343
#endif
1344 1344
  public:
1345 1345
    /// The type of the adapted graph.
1346 1346
    typedef GR Graph;
1347 1347
    /// The type of the node filter map.
1348 1348
    typedef NF NodeFilterMap;
1349 1349
    /// The type of the edge filter map.
1350 1350
    typedef EF EdgeFilterMap;
1351 1351

	
1352 1352
    typedef GraphAdaptorExtender<SubGraphBase<GR, NF, EF, true> >
1353 1353
      Parent;
1354 1354

	
1355 1355
    typedef typename Parent::Node Node;
1356 1356
    typedef typename Parent::Edge Edge;
1357 1357

	
1358 1358
  protected:
1359 1359
    SubGraph() { }
1360 1360
  public:
1361 1361

	
1362 1362
    /// \brief Constructor
1363 1363
    ///
1364 1364
    /// Creates a subgraph for the given graph with the given node
1365 1365
    /// and edge filter maps.
1366 1366
    SubGraph(GR& graph, NF& node_filter, EF& edge_filter) {
1367 1367
      initialize(graph, node_filter, edge_filter);
1368 1368
    }
1369 1369

	
1370 1370
    /// \brief Sets the status of the given node
1371 1371
    ///
1372 1372
    /// This function sets the status of the given node.
1373 1373
    /// It is done by simply setting the assigned value of \c n
1374 1374
    /// to \c v in the node filter map.
1375 1375
    void status(const Node& n, bool v) const { Parent::status(n, v); }
1376 1376

	
1377 1377
    /// \brief Sets the status of the given edge
1378 1378
    ///
1379 1379
    /// This function sets the status of the given edge.
1380 1380
    /// It is done by simply setting the assigned value of \c e
1381 1381
    /// to \c v in the edge filter map.
1382 1382
    void status(const Edge& e, bool v) const { Parent::status(e, v); }
1383 1383

	
1384 1384
    /// \brief Returns the status of the given node
1385 1385
    ///
1386 1386
    /// This function returns the status of the given node.
1387 1387
    /// It is \c true if the given node is enabled (i.e. not hidden).
1388 1388
    bool status(const Node& n) const { return Parent::status(n); }
1389 1389

	
1390 1390
    /// \brief Returns the status of the given edge
1391 1391
    ///
1392 1392
    /// This function returns the status of the given edge.
1393 1393
    /// It is \c true if the given edge is enabled (i.e. not hidden).
1394 1394
    bool status(const Edge& e) const { return Parent::status(e); }
1395 1395

	
1396 1396
    /// \brief Disables the given node
1397 1397
    ///
1398 1398
    /// This function disables the given node in the subdigraph,
1399 1399
    /// so the iteration jumps over it.
1400 1400
    /// It is the same as \ref status() "status(n, false)".
1401 1401
    void disable(const Node& n) const { Parent::status(n, false); }
1402 1402

	
1403 1403
    /// \brief Disables the given edge
1404 1404
    ///
1405 1405
    /// This function disables the given edge in the subgraph,
1406 1406
    /// so the iteration jumps over it.
1407 1407
    /// It is the same as \ref status() "status(e, false)".
1408 1408
    void disable(const Edge& e) const { Parent::status(e, false); }
1409 1409

	
1410 1410
    /// \brief Enables the given node
1411 1411
    ///
1412 1412
    /// This function enables the given node in the subdigraph.
1413 1413
    /// It is the same as \ref status() "status(n, true)".
1414 1414
    void enable(const Node& n) const { Parent::status(n, true); }
1415 1415

	
1416 1416
    /// \brief Enables the given edge
1417 1417
    ///
1418 1418
    /// This function enables the given edge in the subgraph.
1419 1419
    /// It is the same as \ref status() "status(e, true)".
1420 1420
    void enable(const Edge& e) const { Parent::status(e, true); }
1421 1421

	
1422 1422
  };
1423 1423

	
1424 1424
  /// \brief Returns a read-only SubGraph adaptor
1425 1425
  ///
1426 1426
  /// This function just returns a read-only \ref SubGraph adaptor.
1427 1427
  /// \ingroup graph_adaptors
1428 1428
  /// \relates SubGraph
1429 1429
  template<typename GR, typename NF, typename EF>
1430 1430
  SubGraph<const GR, NF, EF>
1431 1431
  subGraph(const GR& graph, NF& node_filter, EF& edge_filter) {
1432 1432
    return SubGraph<const GR, NF, EF>
1433 1433
      (graph, node_filter, edge_filter);
1434 1434
  }
1435 1435

	
1436 1436
  template<typename GR, typename NF, typename EF>
1437 1437
  SubGraph<const GR, const NF, EF>
1438 1438
  subGraph(const GR& graph, const NF& node_filter, EF& edge_filter) {
1439 1439
    return SubGraph<const GR, const NF, EF>
1440 1440
      (graph, node_filter, edge_filter);
1441 1441
  }
1442 1442

	
1443 1443
  template<typename GR, typename NF, typename EF>
1444 1444
  SubGraph<const GR, NF, const EF>
1445 1445
  subGraph(const GR& graph, NF& node_filter, const EF& edge_filter) {
1446 1446
    return SubGraph<const GR, NF, const EF>
1447 1447
      (graph, node_filter, edge_filter);
1448 1448
  }
1449 1449

	
1450 1450
  template<typename GR, typename NF, typename EF>
1451 1451
  SubGraph<const GR, const NF, const EF>
1452 1452
  subGraph(const GR& graph, const NF& node_filter, const EF& edge_filter) {
1453 1453
    return SubGraph<const GR, const NF, const EF>
1454 1454
      (graph, node_filter, edge_filter);
1455 1455
  }
1456 1456

	
1457 1457

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

	
1501 1501
  public:
1502 1502

	
1503 1503
    typedef GR Digraph;
1504 1504
    typedef NF NodeFilterMap;
1505 1505

	
1506 1506
    typedef typename Parent::Node Node;
1507 1507

	
1508 1508
  protected:
1509 1509
    ConstMap<typename Digraph::Arc, Const<bool, true> > const_true_map;
1510 1510

	
1511 1511
    FilterNodes() : const_true_map() {}
1512 1512

	
1513 1513
  public:
1514 1514

	
1515 1515
    /// \brief Constructor
1516 1516
    ///
1517 1517
    /// Creates a subgraph for the given digraph or graph with the
1518 1518
    /// given node filter map.
1519 1519
    FilterNodes(GR& graph, NF& node_filter) 
1520 1520
      : Parent(), const_true_map()
1521 1521
    {
1522 1522
      Parent::initialize(graph, node_filter, const_true_map);
1523 1523
    }
1524 1524

	
1525 1525
    /// \brief Sets the status of the given node
1526 1526
    ///
1527 1527
    /// This function sets the status of the given node.
1528 1528
    /// It is done by simply setting the assigned value of \c n
1529 1529
    /// to \c v in the node filter map.
1530 1530
    void status(const Node& n, bool v) const { Parent::status(n, v); }
1531 1531

	
1532 1532
    /// \brief Returns the status of the given node
1533 1533
    ///
1534 1534
    /// This function returns the status of the given node.
1535 1535
    /// It is \c true if the given node is enabled (i.e. not hidden).
1536 1536
    bool status(const Node& n) const { return Parent::status(n); }
1537 1537

	
1538 1538
    /// \brief Disables the given node
1539 1539
    ///
1540 1540
    /// This function disables the given node, so the iteration
1541 1541
    /// jumps over it.
1542 1542
    /// It is the same as \ref status() "status(n, false)".
1543 1543
    void disable(const Node& n) const { Parent::status(n, false); }
1544 1544

	
1545 1545
    /// \brief Enables the given node
1546 1546
    ///
1547 1547
    /// This function enables the given node.
1548 1548
    /// It is the same as \ref status() "status(n, true)".
1549 1549
    void enable(const Node& n) const { Parent::status(n, true); }
1550 1550

	
1551 1551
  };
1552 1552

	
1553 1553
  template<typename GR, typename NF>
1554 1554
  class FilterNodes<GR, NF,
1555 1555
                    typename enable_if<UndirectedTagIndicator<GR> >::type> :
1556 1556
    public GraphAdaptorExtender<
1557 1557
      SubGraphBase<GR, NF, ConstMap<typename GR::Edge, Const<bool, true> >, 
1558 1558
                   true> > {
1559 1559

	
1560 1560
    typedef GraphAdaptorExtender<
1561 1561
      SubGraphBase<GR, NF, ConstMap<typename GR::Edge, Const<bool, true> >, 
1562 1562
                   true> > Parent;
1563 1563

	
1564 1564
  public:
1565 1565

	
1566 1566
    typedef GR Graph;
1567 1567
    typedef NF NodeFilterMap;
1568 1568

	
1569 1569
    typedef typename Parent::Node Node;
1570 1570

	
1571 1571
  protected:
1572 1572
    ConstMap<typename GR::Edge, Const<bool, true> > const_true_map;
1573 1573

	
1574 1574
    FilterNodes() : const_true_map() {}
1575 1575

	
1576 1576
  public:
1577 1577

	
1578 1578
    FilterNodes(GR& graph, NodeFilterMap& node_filter) :
1579 1579
      Parent(), const_true_map() {
1580 1580
      Parent::initialize(graph, node_filter, const_true_map);
1581 1581
    }
1582 1582

	
1583 1583
    void status(const Node& n, bool v) const { Parent::status(n, v); }
1584 1584
    bool status(const Node& n) const { return Parent::status(n); }
1585 1585
    void disable(const Node& n) const { Parent::status(n, false); }
1586 1586
    void enable(const Node& n) const { Parent::status(n, true); }
1587 1587

	
1588 1588
  };
1589 1589

	
1590 1590

	
1591 1591
  /// \brief Returns a read-only FilterNodes adaptor
1592 1592
  ///
1593 1593
  /// This function just returns a read-only \ref FilterNodes adaptor.
1594 1594
  /// \ingroup graph_adaptors
1595 1595
  /// \relates FilterNodes
1596 1596
  template<typename GR, typename NF>
1597 1597
  FilterNodes<const GR, NF>
1598 1598
  filterNodes(const GR& graph, NF& node_filter) {
1599 1599
    return FilterNodes<const GR, NF>(graph, node_filter);
1600 1600
  }
1601 1601

	
1602 1602
  template<typename GR, typename NF>
1603 1603
  FilterNodes<const GR, const NF>
1604 1604
  filterNodes(const GR& graph, const NF& node_filter) {
1605 1605
    return FilterNodes<const GR, const NF>(graph, node_filter);
1606 1606
  }
1607 1607

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

	
1648 1648
  public:
1649 1649

	
1650 1650
    /// The type of the adapted digraph.
1651 1651
    typedef DGR Digraph;
1652 1652
    /// The type of the arc filter map.
1653 1653
    typedef AF ArcFilterMap;
1654 1654

	
1655 1655
    typedef typename Parent::Arc Arc;
1656 1656

	
1657 1657
  protected:
1658 1658
    ConstMap<typename DGR::Node, Const<bool, true> > const_true_map;
1659 1659

	
1660 1660
    FilterArcs() : const_true_map() {}
1661 1661

	
1662 1662
  public:
1663 1663

	
1664 1664
    /// \brief Constructor
1665 1665
    ///
1666 1666
    /// Creates a subdigraph for the given digraph with the given arc
1667 1667
    /// filter map.
1668 1668
    FilterArcs(DGR& digraph, ArcFilterMap& arc_filter)
1669 1669
      : Parent(), const_true_map() {
1670 1670
      Parent::initialize(digraph, const_true_map, arc_filter);
1671 1671
    }
1672 1672

	
1673 1673
    /// \brief Sets the status of the given arc
1674 1674
    ///
1675 1675
    /// This function sets the status of the given arc.
1676 1676
    /// It is done by simply setting the assigned value of \c a
1677 1677
    /// to \c v in the arc filter map.
1678 1678
    void status(const Arc& a, bool v) const { Parent::status(a, v); }
1679 1679

	
1680 1680
    /// \brief Returns the status of the given arc
1681 1681
    ///
1682 1682
    /// This function returns the status of the given arc.
1683 1683
    /// It is \c true if the given arc is enabled (i.e. not hidden).
1684 1684
    bool status(const Arc& a) const { return Parent::status(a); }
1685 1685

	
1686 1686
    /// \brief Disables the given arc
1687 1687
    ///
1688 1688
    /// This function disables the given arc in the subdigraph,
1689 1689
    /// so the iteration jumps over it.
1690 1690
    /// It is the same as \ref status() "status(a, false)".
1691 1691
    void disable(const Arc& a) const { Parent::status(a, false); }
1692 1692

	
1693 1693
    /// \brief Enables the given arc
1694 1694
    ///
1695 1695
    /// This function enables the given arc in the subdigraph.
1696 1696
    /// It is the same as \ref status() "status(a, true)".
1697 1697
    void enable(const Arc& a) const { Parent::status(a, true); }
1698 1698

	
1699 1699
  };
1700 1700

	
1701 1701
  /// \brief Returns a read-only FilterArcs adaptor
1702 1702
  ///
1703 1703
  /// This function just returns a read-only \ref FilterArcs adaptor.
1704 1704
  /// \ingroup graph_adaptors
1705 1705
  /// \relates FilterArcs
1706 1706
  template<typename DGR, typename AF>
1707 1707
  FilterArcs<const DGR, AF>
1708 1708
  filterArcs(const DGR& digraph, AF& arc_filter) {
1709 1709
    return FilterArcs<const DGR, AF>(digraph, arc_filter);
1710 1710
  }
1711 1711

	
1712 1712
  template<typename DGR, typename AF>
1713 1713
  FilterArcs<const DGR, const AF>
1714 1714
  filterArcs(const DGR& digraph, const AF& arc_filter) {
1715 1715
    return FilterArcs<const DGR, const AF>(digraph, arc_filter);
1716 1716
  }
1717 1717

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

	
1758 1758
  public:
1759 1759

	
1760 1760
    /// The type of the adapted graph.
1761 1761
    typedef GR Graph;
1762 1762
    /// The type of the edge filter map.
1763 1763
    typedef EF EdgeFilterMap;
1764 1764

	
1765 1765
    typedef typename Parent::Edge Edge;
1766 1766

	
1767 1767
  protected:
1768 1768
    ConstMap<typename GR::Node, Const<bool, true> > const_true_map;
1769 1769

	
1770 1770
    FilterEdges() : const_true_map(true) {
1771 1771
      Parent::setNodeFilterMap(const_true_map);
1772 1772
    }
1773 1773

	
1774 1774
  public:
1775 1775

	
1776 1776
    /// \brief Constructor
1777 1777
    ///
1778 1778
    /// Creates a subgraph for the given graph with the given edge
1779 1779
    /// filter map.
1780 1780
    FilterEdges(GR& graph, EF& edge_filter) 
1781 1781
      : Parent(), const_true_map() {
1782 1782
      Parent::initialize(graph, const_true_map, edge_filter);
1783 1783
    }
1784 1784

	
1785 1785
    /// \brief Sets the status of the given edge
1786 1786
    ///
1787 1787
    /// This function sets the status of the given edge.
1788 1788
    /// It is done by simply setting the assigned value of \c e
1789 1789
    /// to \c v in the edge filter map.
1790 1790
    void status(const Edge& e, bool v) const { Parent::status(e, v); }
1791 1791

	
1792 1792
    /// \brief Returns the status of the given edge
1793 1793
    ///
1794 1794
    /// This function returns the status of the given edge.
1795 1795
    /// It is \c true if the given edge is enabled (i.e. not hidden).
1796 1796
    bool status(const Edge& e) const { return Parent::status(e); }
1797 1797

	
1798 1798
    /// \brief Disables the given edge
1799 1799
    ///
1800 1800
    /// This function disables the given edge in the subgraph,
1801 1801
    /// so the iteration jumps over it.
1802 1802
    /// It is the same as \ref status() "status(e, false)".
1803 1803
    void disable(const Edge& e) const { Parent::status(e, false); }
1804 1804

	
1805 1805
    /// \brief Enables the given edge
1806 1806
    ///
1807 1807
    /// This function enables the given edge in the subgraph.
1808 1808
    /// It is the same as \ref status() "status(e, true)".
1809 1809
    void enable(const Edge& e) const { Parent::status(e, true); }
1810 1810

	
1811 1811
  };
1812 1812

	
1813 1813
  /// \brief Returns a read-only FilterEdges adaptor
1814 1814
  ///
1815 1815
  /// This function just returns a read-only \ref FilterEdges adaptor.
1816 1816
  /// \ingroup graph_adaptors
1817 1817
  /// \relates FilterEdges
1818 1818
  template<typename GR, typename EF>
1819 1819
  FilterEdges<const GR, EF>
1820 1820
  filterEdges(const GR& graph, EF& edge_filter) {
1821 1821
    return FilterEdges<const GR, EF>(graph, edge_filter);
1822 1822
  }
1823 1823

	
1824 1824
  template<typename GR, typename EF>
1825 1825
  FilterEdges<const GR, const EF>
1826 1826
  filterEdges(const GR& graph, const EF& edge_filter) {
1827 1827
    return FilterEdges<const GR, const EF>(graph, edge_filter);
1828 1828
  }
1829 1829

	
1830 1830

	
1831 1831
  template <typename DGR>
1832 1832
  class UndirectorBase {
1833 1833
  public:
1834 1834
    typedef DGR Digraph;
1835 1835
    typedef UndirectorBase Adaptor;
1836 1836

	
1837 1837
    typedef True UndirectedTag;
1838 1838

	
1839 1839
    typedef typename Digraph::Arc Edge;
1840 1840
    typedef typename Digraph::Node Node;
1841 1841

	
1842
    class Arc : public Edge {
1842
    class Arc {
1843 1843
      friend class UndirectorBase;
1844 1844
    protected:
1845
      Edge _edge;
1845 1846
      bool _forward;
1846 1847

	
1847
      Arc(const Edge& edge, bool forward) :
1848
        Edge(edge), _forward(forward) {}
1848
      Arc(const Edge& edge, bool forward) 
1849
        : _edge(edge), _forward(forward) {}
1849 1850

	
1850 1851
    public:
1851 1852
      Arc() {}
1852 1853

	
1853
      Arc(Invalid) : Edge(INVALID), _forward(true) {}
1854
      Arc(Invalid) : _edge(INVALID), _forward(true) {}
1855

	
1856
      operator const Edge&() const { return _edge; }
1854 1857

	
1855 1858
      bool operator==(const Arc &other) const {
1856
        return _forward == other._forward &&
1857
          static_cast<const Edge&>(*this) == static_cast<const Edge&>(other);
1859
        return _forward == other._forward && _edge == other._edge;
1858 1860
      }
1859 1861
      bool operator!=(const Arc &other) const {
1860
        return _forward != other._forward ||
1861
          static_cast<const Edge&>(*this) != static_cast<const Edge&>(other);
1862
        return _forward != other._forward || _edge != other._edge;
1862 1863
      }
1863 1864
      bool operator<(const Arc &other) const {
1864 1865
        return _forward < other._forward ||
1865
          (_forward == other._forward &&
1866
           static_cast<const Edge&>(*this) < static_cast<const Edge&>(other));
1866
          (_forward == other._forward && _edge < other._edge);
1867 1867
      }
1868 1868
    };
1869 1869

	
1870 1870
    void first(Node& n) const {
1871 1871
      _digraph->first(n);
1872 1872
    }
1873 1873

	
1874 1874
    void next(Node& n) const {
1875 1875
      _digraph->next(n);
1876 1876
    }
1877 1877

	
1878 1878
    void first(Arc& a) const {
1879
      _digraph->first(a);
1879
      _digraph->first(a._edge);
1880 1880
      a._forward = true;
1881 1881
    }
1882 1882

	
1883 1883
    void next(Arc& a) const {
1884 1884
      if (a._forward) {
1885 1885
        a._forward = false;
1886 1886
      } else {
1887
        _digraph->next(a);
1887
        _digraph->next(a._edge);
1888 1888
        a._forward = true;
1889 1889
      }
1890 1890
    }
1891 1891

	
1892 1892
    void first(Edge& e) const {
1893 1893
      _digraph->first(e);
1894 1894
    }
1895 1895

	
1896 1896
    void next(Edge& e) const {
1897 1897
      _digraph->next(e);
1898 1898
    }
1899 1899

	
1900 1900
    void firstOut(Arc& a, const Node& n) const {
1901
      _digraph->firstIn(a, n);
1902
      if( static_cast<const Edge&>(a) != INVALID ) {
1901
      _digraph->firstIn(a._edge, n);
1902
      if (a._edge != INVALID ) {
1903 1903
        a._forward = false;
1904 1904
      } else {
1905
        _digraph->firstOut(a, n);
1905
        _digraph->firstOut(a._edge, n);
1906 1906
        a._forward = true;
1907 1907
      }
1908 1908
    }
1909 1909
    void nextOut(Arc &a) const {
1910 1910
      if (!a._forward) {
1911
        Node n = _digraph->target(a);
1912
        _digraph->nextIn(a);
1913
        if (static_cast<const Edge&>(a) == INVALID ) {
1914
          _digraph->firstOut(a, n);
1911
        Node n = _digraph->target(a._edge);
1912
        _digraph->nextIn(a._edge);
1913
        if (a._edge == INVALID) {
1914
          _digraph->firstOut(a._edge, n);
1915 1915
          a._forward = true;
1916 1916
        }
1917 1917
      }
1918 1918
      else {
1919
        _digraph->nextOut(a);
1919
        _digraph->nextOut(a._edge);
1920 1920
      }
1921 1921
    }
1922 1922

	
1923 1923
    void firstIn(Arc &a, const Node &n) const {
1924
      _digraph->firstOut(a, n);
1925
      if (static_cast<const Edge&>(a) != INVALID ) {
1924
      _digraph->firstOut(a._edge, n);
1925
      if (a._edge != INVALID ) {
1926 1926
        a._forward = false;
1927 1927
      } else {
1928
        _digraph->firstIn(a, n);
1928
        _digraph->firstIn(a._edge, n);
1929 1929
        a._forward = true;
1930 1930
      }
1931 1931
    }
1932 1932
    void nextIn(Arc &a) const {
1933 1933
      if (!a._forward) {
1934
        Node n = _digraph->source(a);
1935
        _digraph->nextOut(a);
1936
        if( static_cast<const Edge&>(a) == INVALID ) {
1937
          _digraph->firstIn(a, n);
1934
        Node n = _digraph->source(a._edge);
1935
        _digraph->nextOut(a._edge);
1936
        if (a._edge == INVALID ) {
1937
          _digraph->firstIn(a._edge, n);
1938 1938
          a._forward = true;
1939 1939
        }
1940 1940
      }
1941 1941
      else {
1942
        _digraph->nextIn(a);
1942
        _digraph->nextIn(a._edge);
1943 1943
      }
1944 1944
    }
1945 1945

	
1946 1946
    void firstInc(Edge &e, bool &d, const Node &n) const {
1947 1947
      d = true;
1948 1948
      _digraph->firstOut(e, n);
1949 1949
      if (e != INVALID) return;
1950 1950
      d = false;
1951 1951
      _digraph->firstIn(e, n);
1952 1952
    }
1953 1953

	
1954 1954
    void nextInc(Edge &e, bool &d) const {
1955 1955
      if (d) {
1956 1956
        Node s = _digraph->source(e);
1957 1957
        _digraph->nextOut(e);
1958 1958
        if (e != INVALID) return;
1959 1959
        d = false;
1960 1960
        _digraph->firstIn(e, s);
1961 1961
      } else {
1962 1962
        _digraph->nextIn(e);
1963 1963
      }
1964 1964
    }
1965 1965

	
1966 1966
    Node u(const Edge& e) const {
1967 1967
      return _digraph->source(e);
1968 1968
    }
1969 1969

	
1970 1970
    Node v(const Edge& e) const {
1971 1971
      return _digraph->target(e);
1972 1972
    }
1973 1973

	
1974 1974
    Node source(const Arc &a) const {
1975
      return a._forward ? _digraph->source(a) : _digraph->target(a);
1975
      return a._forward ? _digraph->source(a._edge) : _digraph->target(a._edge);
1976 1976
    }
1977 1977

	
1978 1978
    Node target(const Arc &a) const {
1979
      return a._forward ? _digraph->target(a) : _digraph->source(a);
1979
      return a._forward ? _digraph->target(a._edge) : _digraph->source(a._edge);
1980 1980
    }
1981 1981

	
1982 1982
    static Arc direct(const Edge &e, bool d) {
1983 1983
      return Arc(e, d);
1984 1984
    }
1985
    Arc direct(const Edge &e, const Node& n) const {
1986
      return Arc(e, _digraph->source(e) == n);
1987
    }
1988 1985

	
1989 1986
    static bool direction(const Arc &a) { return a._forward; }
1990 1987

	
1991 1988
    Node nodeFromId(int ix) const { return _digraph->nodeFromId(ix); }
1992 1989
    Arc arcFromId(int ix) const {
1993 1990
      return direct(_digraph->arcFromId(ix >> 1), bool(ix & 1));
1994 1991
    }
1995 1992
    Edge edgeFromId(int ix) const { return _digraph->arcFromId(ix); }
1996 1993

	
1997 1994
    int id(const Node &n) const { return _digraph->id(n); }
1998 1995
    int id(const Arc &a) const {
1999 1996
      return  (_digraph->id(a) << 1) | (a._forward ? 1 : 0);
2000 1997
    }
2001 1998
    int id(const Edge &e) const { return _digraph->id(e); }
2002 1999

	
2003 2000
    int maxNodeId() const { return _digraph->maxNodeId(); }
2004 2001
    int maxArcId() const { return (_digraph->maxArcId() << 1) | 1; }
2005 2002
    int maxEdgeId() const { return _digraph->maxArcId(); }
2006 2003

	
2007 2004
    Node addNode() { return _digraph->addNode(); }
2008 2005
    Edge addEdge(const Node& u, const Node& v) {
2009 2006
      return _digraph->addArc(u, v);
2010 2007
    }
2011 2008

	
2012 2009
    void erase(const Node& i) { _digraph->erase(i); }
2013 2010
    void erase(const Edge& i) { _digraph->erase(i); }
2014 2011

	
2015 2012
    void clear() { _digraph->clear(); }
2016 2013

	
2017 2014
    typedef NodeNumTagIndicator<Digraph> NodeNumTag;
2018 2015
    int nodeNum() const { return _digraph->nodeNum(); }
2019 2016

	
2020 2017
    typedef ArcNumTagIndicator<Digraph> ArcNumTag;
2021 2018
    int arcNum() const { return 2 * _digraph->arcNum(); }
2022 2019

	
2023 2020
    typedef ArcNumTag EdgeNumTag;
2024 2021
    int edgeNum() const { return _digraph->arcNum(); }
2025 2022

	
2026 2023
    typedef FindArcTagIndicator<Digraph> FindArcTag;
2027 2024
    Arc findArc(Node s, Node t, Arc p = INVALID) const {
2028 2025
      if (p == INVALID) {
2029 2026
        Edge arc = _digraph->findArc(s, t);
2030 2027
        if (arc != INVALID) return direct(arc, true);
2031 2028
        arc = _digraph->findArc(t, s);
2032 2029
        if (arc != INVALID) return direct(arc, false);
2033 2030
      } else if (direction(p)) {
2034 2031
        Edge arc = _digraph->findArc(s, t, p);
2035 2032
        if (arc != INVALID) return direct(arc, true);
2036 2033
        arc = _digraph->findArc(t, s);
2037 2034
        if (arc != INVALID) return direct(arc, false);
2038 2035
      } else {
2039 2036
        Edge arc = _digraph->findArc(t, s, p);
2040 2037
        if (arc != INVALID) return direct(arc, false);
2041 2038
      }
2042 2039
      return INVALID;
2043 2040
    }
2044 2041

	
2045 2042
    typedef FindArcTag FindEdgeTag;
2046 2043
    Edge findEdge(Node s, Node t, Edge p = INVALID) const {
2047 2044
      if (s != t) {
2048 2045
        if (p == INVALID) {
2049 2046
          Edge arc = _digraph->findArc(s, t);
2050 2047
          if (arc != INVALID) return arc;
2051 2048
          arc = _digraph->findArc(t, s);
2052 2049
          if (arc != INVALID) return arc;
2053 2050
        } else if (_digraph->source(p) == s) {
2054 2051
          Edge arc = _digraph->findArc(s, t, p);
2055 2052
          if (arc != INVALID) return arc;
2056 2053
          arc = _digraph->findArc(t, s);
2057 2054
          if (arc != INVALID) return arc;
2058 2055
        } else {
2059 2056
          Edge arc = _digraph->findArc(t, s, p);
2060 2057
          if (arc != INVALID) return arc;
2061 2058
        }
2062 2059
      } else {
2063 2060
        return _digraph->findArc(s, t, p);
2064 2061
      }
2065 2062
      return INVALID;
2066 2063
    }
2067 2064

	
2068 2065
  private:
2069 2066

	
2070 2067
    template <typename V>
2071 2068
    class ArcMapBase {
2072 2069
    private:
2073 2070

	
2074 2071
      typedef typename DGR::template ArcMap<V> MapImpl;
2075 2072

	
2076 2073
    public:
2077 2074

	
2078 2075
      typedef typename MapTraits<MapImpl>::ReferenceMapTag ReferenceMapTag;
2079 2076

	
2080 2077
      typedef V Value;
2081 2078
      typedef Arc Key;
2082 2079
      typedef typename MapTraits<MapImpl>::ConstReturnValue ConstReturnValue;
2083 2080
      typedef typename MapTraits<MapImpl>::ReturnValue ReturnValue;
2084 2081
      typedef typename MapTraits<MapImpl>::ConstReturnValue ConstReference;
2085 2082
      typedef typename MapTraits<MapImpl>::ReturnValue Reference;
2086 2083

	
2087 2084
      ArcMapBase(const UndirectorBase<DGR>& adaptor) :
2088 2085
        _forward(*adaptor._digraph), _backward(*adaptor._digraph) {}
2089 2086

	
2090 2087
      ArcMapBase(const UndirectorBase<DGR>& adaptor, const V& value)
2091 2088
        : _forward(*adaptor._digraph, value), 
2092 2089
          _backward(*adaptor._digraph, value) {}
2093 2090

	
2094 2091
      void set(const Arc& a, const V& value) {
2095 2092
        if (direction(a)) {
2096 2093
          _forward.set(a, value);
2097 2094
        } else {
2098 2095
          _backward.set(a, value);
2099 2096
        }
2100 2097
      }
2101 2098

	
2102 2099
      ConstReturnValue operator[](const Arc& a) const {
2103 2100
        if (direction(a)) {
2104 2101
          return _forward[a];
2105 2102
        } else {
2106 2103
          return _backward[a];
2107 2104
        }
2108 2105
      }
2109 2106

	
2110 2107
      ReturnValue operator[](const Arc& a) {
2111 2108
        if (direction(a)) {
2112 2109
          return _forward[a];
2113 2110
        } else {
2114 2111
          return _backward[a];
2115 2112
        }
2116 2113
      }
2117 2114

	
2118 2115
    protected:
2119 2116

	
2120 2117
      MapImpl _forward, _backward;
2121 2118

	
2122 2119
    };
2123 2120

	
2124 2121
  public:
2125 2122

	
2126 2123
    template <typename V>
2127 2124
    class NodeMap : public DGR::template NodeMap<V> {
2128 2125
      typedef typename DGR::template NodeMap<V> Parent;
2129 2126

	
2130 2127
    public:
2131 2128
      typedef V Value;
2132 2129

	
2133 2130
      explicit NodeMap(const UndirectorBase<DGR>& adaptor)
2134 2131
        : Parent(*adaptor._digraph) {}
2135 2132

	
2136 2133
      NodeMap(const UndirectorBase<DGR>& adaptor, const V& value)
2137 2134
        : Parent(*adaptor._digraph, value) { }
2138 2135

	
2139 2136
    private:
2140 2137
      NodeMap& operator=(const NodeMap& cmap) {
2141 2138
        return operator=<NodeMap>(cmap);
2142 2139
      }
2143 2140

	
2144 2141
      template <typename CMap>
2145 2142
      NodeMap& operator=(const CMap& cmap) {
2146 2143
        Parent::operator=(cmap);
2147 2144
        return *this;
2148 2145
      }
2149 2146

	
2150 2147
    };
2151 2148

	
2152 2149
    template <typename V>
2153 2150
    class ArcMap
2154 2151
      : public SubMapExtender<UndirectorBase<DGR>, ArcMapBase<V> > {
2155 2152
      typedef SubMapExtender<UndirectorBase<DGR>, ArcMapBase<V> > Parent;
2156 2153

	
2157 2154
    public:
2158 2155
      typedef V Value;
2159 2156

	
2160 2157
      explicit ArcMap(const UndirectorBase<DGR>& adaptor)
2161 2158
        : Parent(adaptor) {}
2162 2159

	
2163 2160
      ArcMap(const UndirectorBase<DGR>& adaptor, const V& value)
2164 2161
        : Parent(adaptor, value) {}
2165 2162

	
2166 2163
    private:
2167 2164
      ArcMap& operator=(const ArcMap& cmap) {
2168 2165
        return operator=<ArcMap>(cmap);
2169 2166
      }
2170 2167

	
2171 2168
      template <typename CMap>
2172 2169
      ArcMap& operator=(const CMap& cmap) {
2173 2170
        Parent::operator=(cmap);
2174 2171
        return *this;
2175 2172
      }
2176 2173
    };
2177 2174

	
2178 2175
    template <typename V>
2179 2176
    class EdgeMap : public Digraph::template ArcMap<V> {
2180 2177
      typedef typename Digraph::template ArcMap<V> Parent;
2181 2178

	
2182 2179
    public:
2183 2180
      typedef V Value;
2184 2181

	
2185 2182
      explicit EdgeMap(const UndirectorBase<DGR>& adaptor)
2186 2183
        : Parent(*adaptor._digraph) {}
2187 2184

	
2188 2185
      EdgeMap(const UndirectorBase<DGR>& adaptor, const V& value)
2189 2186
        : Parent(*adaptor._digraph, value) {}
2190 2187

	
2191 2188
    private:
2192 2189
      EdgeMap& operator=(const EdgeMap& cmap) {
2193 2190
        return operator=<EdgeMap>(cmap);
2194 2191
      }
2195 2192

	
2196 2193
      template <typename CMap>
2197 2194
      EdgeMap& operator=(const CMap& cmap) {
2198 2195
        Parent::operator=(cmap);
2199 2196
        return *this;
2200 2197
      }
2201 2198

	
2202 2199
    };
2203 2200

	
2204 2201
    typedef typename ItemSetTraits<DGR, Node>::ItemNotifier NodeNotifier;
2205 2202
    NodeNotifier& notifier(Node) const { return _digraph->notifier(Node()); }
2206 2203

	
2207 2204
    typedef typename ItemSetTraits<DGR, Edge>::ItemNotifier EdgeNotifier;
2208 2205
    EdgeNotifier& notifier(Edge) const { return _digraph->notifier(Edge()); }
2209 2206
    
2210 2207
    typedef EdgeNotifier ArcNotifier;
2211 2208
    ArcNotifier& notifier(Arc) const { return _digraph->notifier(Edge()); }
2212 2209

	
2213 2210
  protected:
2214 2211

	
2215 2212
    UndirectorBase() : _digraph(0) {}
2216 2213

	
2217 2214
    DGR* _digraph;
2218 2215

	
2219 2216
    void initialize(DGR& digraph) {
2220 2217
      _digraph = &digraph;
2221 2218
    }
2222 2219

	
2223 2220
  };
2224 2221

	
2225 2222
  /// \ingroup graph_adaptors
2226 2223
  ///
2227 2224
  /// \brief Adaptor class for viewing a digraph as an undirected graph.
2228 2225
  ///
2229 2226
  /// Undirector adaptor can be used for viewing a digraph as an undirected
2230 2227
  /// graph. All arcs of the underlying digraph are showed in the
2231 2228
  /// adaptor as an edge (and also as a pair of arcs, of course).
2232 2229
  /// This adaptor conforms to the \ref concepts::Graph "Graph" concept.
2233 2230
  ///
2234 2231
  /// The adapted digraph can also be modified through this adaptor
2235 2232
  /// by adding or removing nodes or edges, unless the \c GR template
2236 2233
  /// parameter is set to be \c const.
2237 2234
  ///
2238 2235
  /// \tparam DGR The type of the adapted digraph.
2239 2236
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
2240 2237
  /// It can also be specified to be \c const.
2241 2238
  ///
2242 2239
  /// \note The \c Node type of this adaptor and the adapted digraph are
2243 2240
  /// convertible to each other, moreover the \c Edge type of the adaptor
2244 2241
  /// and the \c Arc type of the adapted digraph are also convertible to
2245 2242
  /// each other.
2246 2243
  /// (Thus the \c Arc type of the adaptor is convertible to the \c Arc type
2247 2244
  /// of the adapted digraph.)
2248 2245
  template<typename DGR>
2249 2246
#ifdef DOXYGEN
2250 2247
  class Undirector {
2251 2248
#else
2252 2249
  class Undirector :
2253 2250
    public GraphAdaptorExtender<UndirectorBase<DGR> > {
2254 2251
#endif
2255 2252
    typedef GraphAdaptorExtender<UndirectorBase<DGR> > Parent;
2256 2253
  public:
2257 2254
    /// The type of the adapted digraph.
2258 2255
    typedef DGR Digraph;
2259 2256
  protected:
2260 2257
    Undirector() { }
2261 2258
  public:
2262 2259

	
2263 2260
    /// \brief Constructor
2264 2261
    ///
2265 2262
    /// Creates an undirected graph from the given digraph.
2266 2263
    Undirector(DGR& digraph) {
2267 2264
      initialize(digraph);
2268 2265
    }
2269 2266

	
2270 2267
    /// \brief Arc map combined from two original arc maps
2271 2268
    ///
2272 2269
    /// This map adaptor class adapts two arc maps of the underlying
2273 2270
    /// digraph to get an arc map of the undirected graph.
2274 2271
    /// Its value type is inherited from the first arc map type (\c FW).
2275 2272
    /// \tparam FW The type of the "foward" arc map.
2276 2273
    /// \tparam BK The type of the "backward" arc map.
2277 2274
    template <typename FW, typename BK>
2278 2275
    class CombinedArcMap {
2279 2276
    public:
2280 2277

	
2281 2278
      /// The key type of the map
2282 2279
      typedef typename Parent::Arc Key;
2283 2280
      /// The value type of the map
2284 2281
      typedef typename FW::Value Value;
2285 2282

	
2286 2283
      typedef typename MapTraits<FW>::ReferenceMapTag ReferenceMapTag;
2287 2284

	
2288 2285
      typedef typename MapTraits<FW>::ReturnValue ReturnValue;
2289 2286
      typedef typename MapTraits<FW>::ConstReturnValue ConstReturnValue;
2290 2287
      typedef typename MapTraits<FW>::ReturnValue Reference;
2291 2288
      typedef typename MapTraits<FW>::ConstReturnValue ConstReference;
2292 2289

	
2293 2290
      /// Constructor
2294 2291
      CombinedArcMap(FW& forward, BK& backward)
2295 2292
        : _forward(&forward), _backward(&backward) {}
2296 2293

	
2297 2294
      /// Sets the value associated with the given key.
2298 2295
      void set(const Key& e, const Value& a) {
2299 2296
        if (Parent::direction(e)) {
2300 2297
          _forward->set(e, a);
2301 2298
        } else {
2302 2299
          _backward->set(e, a);
2303 2300
        }
2304 2301
      }
2305 2302

	
2306 2303
      /// Returns the value associated with the given key.
2307 2304
      ConstReturnValue operator[](const Key& e) const {
2308 2305
        if (Parent::direction(e)) {
2309 2306
          return (*_forward)[e];
2310 2307
        } else {
2311 2308
          return (*_backward)[e];
2312 2309
        }
2313 2310
      }
2314 2311

	
2315 2312
      /// Returns a reference to the value associated with the given key.
2316 2313
      ReturnValue operator[](const Key& e) {
2317 2314
        if (Parent::direction(e)) {
2318 2315
          return (*_forward)[e];
2319 2316
        } else {
2320 2317
          return (*_backward)[e];
2321 2318
        }
2322 2319
      }
2323 2320

	
2324 2321
    protected:
2325 2322

	
2326 2323
      FW* _forward;
2327 2324
      BK* _backward;
2328 2325

	
2329 2326
    };
2330 2327

	
2331 2328
    /// \brief Returns a combined arc map
2332 2329
    ///
2333 2330
    /// This function just returns a combined arc map.
2334 2331
    template <typename FW, typename BK>
2335 2332
    static CombinedArcMap<FW, BK>
2336 2333
    combinedArcMap(FW& forward, BK& backward) {
2337 2334
      return CombinedArcMap<FW, BK>(forward, backward);
2338 2335
    }
2339 2336

	
2340 2337
    template <typename FW, typename BK>
2341 2338
    static CombinedArcMap<const FW, BK>
2342 2339
    combinedArcMap(const FW& forward, BK& backward) {
2343 2340
      return CombinedArcMap<const FW, BK>(forward, backward);
2344 2341
    }
2345 2342

	
2346 2343
    template <typename FW, typename BK>
2347 2344
    static CombinedArcMap<FW, const BK>
2348 2345
    combinedArcMap(FW& forward, const BK& backward) {
2349 2346
      return CombinedArcMap<FW, const BK>(forward, backward);
2350 2347
    }
2351 2348

	
2352 2349
    template <typename FW, typename BK>
2353 2350
    static CombinedArcMap<const FW, const BK>
2354 2351
    combinedArcMap(const FW& forward, const BK& backward) {
2355 2352
      return CombinedArcMap<const FW, const BK>(forward, backward);
2356 2353
    }
2357 2354

	
2358 2355
  };
2359 2356

	
2360 2357
  /// \brief Returns a read-only Undirector adaptor
2361 2358
  ///
2362 2359
  /// This function just returns a read-only \ref Undirector adaptor.
2363 2360
  /// \ingroup graph_adaptors
2364 2361
  /// \relates Undirector
2365 2362
  template<typename DGR>
2366 2363
  Undirector<const DGR> undirector(const DGR& digraph) {
2367 2364
    return Undirector<const DGR>(digraph);
2368 2365
  }
2369 2366

	
2370 2367

	
2371 2368
  template <typename GR, typename DM>
2372 2369
  class OrienterBase {
2373 2370
  public:
2374 2371

	
2375 2372
    typedef GR Graph;
2376 2373
    typedef DM DirectionMap;
2377 2374

	
2378 2375
    typedef typename GR::Node Node;
2379 2376
    typedef typename GR::Edge Arc;
2380 2377

	
2381 2378
    void reverseArc(const Arc& arc) {
2382 2379
      _direction->set(arc, !(*_direction)[arc]);
2383 2380
    }
2384 2381

	
2385 2382
    void first(Node& i) const { _graph->first(i); }
2386 2383
    void first(Arc& i) const { _graph->first(i); }
2387 2384
    void firstIn(Arc& i, const Node& n) const {
2388 2385
      bool d = true;
2389 2386
      _graph->firstInc(i, d, n);
2390 2387
      while (i != INVALID && d == (*_direction)[i]) _graph->nextInc(i, d);
2391 2388
    }
2392 2389
    void firstOut(Arc& i, const Node& n ) const {
2393 2390
      bool d = true;
2394 2391
      _graph->firstInc(i, d, n);
2395 2392
      while (i != INVALID && d != (*_direction)[i]) _graph->nextInc(i, d);
2396 2393
    }
2397 2394

	
2398 2395
    void next(Node& i) const { _graph->next(i); }
2399 2396
    void next(Arc& i) const { _graph->next(i); }
2400 2397
    void nextIn(Arc& i) const {
2401 2398
      bool d = !(*_direction)[i];
2402 2399
      _graph->nextInc(i, d);
2403 2400
      while (i != INVALID && d == (*_direction)[i]) _graph->nextInc(i, d);
2404 2401
    }
2405 2402
    void nextOut(Arc& i) const {
2406 2403
      bool d = (*_direction)[i];
2407 2404
      _graph->nextInc(i, d);
2408 2405
      while (i != INVALID && d != (*_direction)[i]) _graph->nextInc(i, d);
2409 2406
    }
2410 2407

	
2411 2408
    Node source(const Arc& e) const {
2412 2409
      return (*_direction)[e] ? _graph->u(e) : _graph->v(e);
2413 2410
    }
2414 2411
    Node target(const Arc& e) const {
2415 2412
      return (*_direction)[e] ? _graph->v(e) : _graph->u(e);
2416 2413
    }
2417 2414

	
2418 2415
    typedef NodeNumTagIndicator<Graph> NodeNumTag;
2419 2416
    int nodeNum() const { return _graph->nodeNum(); }
2420 2417

	
2421 2418
    typedef EdgeNumTagIndicator<Graph> ArcNumTag;
2422 2419
    int arcNum() const { return _graph->edgeNum(); }
2423 2420

	
2424 2421
    typedef FindEdgeTagIndicator<Graph> FindArcTag;
2425 2422
    Arc findArc(const Node& u, const Node& v,
2426 2423
                const Arc& prev = INVALID) const {
2427 2424
      Arc arc = _graph->findEdge(u, v, prev);
2428 2425
      while (arc != INVALID && source(arc) != u) {
2429 2426
        arc = _graph->findEdge(u, v, arc);
2430 2427
      }
2431 2428
      return arc;
2432 2429
    }
2433 2430

	
2434 2431
    Node addNode() {
2435 2432
      return Node(_graph->addNode());
2436 2433
    }
2437 2434

	
2438 2435
    Arc addArc(const Node& u, const Node& v) {
2439 2436
      Arc arc = _graph->addEdge(u, v);
2440 2437
      _direction->set(arc, _graph->u(arc) == u);
2441 2438
      return arc;
2442 2439
    }
2443 2440

	
2444 2441
    void erase(const Node& i) { _graph->erase(i); }
2445 2442
    void erase(const Arc& i) { _graph->erase(i); }
2446 2443

	
2447 2444
    void clear() { _graph->clear(); }
2448 2445

	
2449 2446
    int id(const Node& v) const { return _graph->id(v); }
2450 2447
    int id(const Arc& e) const { return _graph->id(e); }
2451 2448

	
2452 2449
    Node nodeFromId(int idx) const { return _graph->nodeFromId(idx); }
2453 2450
    Arc arcFromId(int idx) const { return _graph->edgeFromId(idx); }
2454 2451

	
2455 2452
    int maxNodeId() const { return _graph->maxNodeId(); }
2456 2453
    int maxArcId() const { return _graph->maxEdgeId(); }
2457 2454

	
2458 2455
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
2459 2456
    NodeNotifier& notifier(Node) const { return _graph->notifier(Node()); }
2460 2457

	
2461 2458
    typedef typename ItemSetTraits<GR, Arc>::ItemNotifier ArcNotifier;
2462 2459
    ArcNotifier& notifier(Arc) const { return _graph->notifier(Arc()); }
2463 2460

	
2464 2461
    template <typename V>
2465 2462
    class NodeMap : public GR::template NodeMap<V> {
2466 2463
      typedef typename GR::template NodeMap<V> Parent;
2467 2464

	
2468 2465
    public:
2469 2466

	
2470 2467
      explicit NodeMap(const OrienterBase<GR, DM>& adapter)
2471 2468
        : Parent(*adapter._graph) {}
2472 2469

	
2473 2470
      NodeMap(const OrienterBase<GR, DM>& adapter, const V& value)
2474 2471
        : Parent(*adapter._graph, value) {}
2475 2472

	
2476 2473
    private:
2477 2474
      NodeMap& operator=(const NodeMap& cmap) {
2478 2475
        return operator=<NodeMap>(cmap);
2479 2476
      }
2480 2477

	
2481 2478
      template <typename CMap>
2482 2479
      NodeMap& operator=(const CMap& cmap) {
2483 2480
        Parent::operator=(cmap);
2484 2481
        return *this;
2485 2482
      }
2486 2483

	
2487 2484
    };
2488 2485

	
2489 2486
    template <typename V>
2490 2487
    class ArcMap : public GR::template EdgeMap<V> {
2491 2488
      typedef typename Graph::template EdgeMap<V> Parent;
2492 2489

	
2493 2490
    public:
2494 2491

	
2495 2492
      explicit ArcMap(const OrienterBase<GR, DM>& adapter)
2496 2493
        : Parent(*adapter._graph) { }
2497 2494

	
2498 2495
      ArcMap(const OrienterBase<GR, DM>& adapter, const V& value)
2499 2496
        : Parent(*adapter._graph, value) { }
2500 2497

	
2501 2498
    private:
2502 2499
      ArcMap& operator=(const ArcMap& cmap) {
2503 2500
        return operator=<ArcMap>(cmap);
2504 2501
      }
2505 2502

	
2506 2503
      template <typename CMap>
2507 2504
      ArcMap& operator=(const CMap& cmap) {
2508 2505
        Parent::operator=(cmap);
2509 2506
        return *this;
2510 2507
      }
2511 2508
    };
2512 2509

	
2513 2510

	
2514 2511

	
2515 2512
  protected:
2516 2513
    Graph* _graph;
2517 2514
    DM* _direction;
2518 2515

	
2519 2516
    void initialize(GR& graph, DM& direction) {
2520 2517
      _graph = &graph;
2521 2518
      _direction = &direction;
2522 2519
    }
2523 2520

	
2524 2521
  };
2525 2522

	
2526 2523
  /// \ingroup graph_adaptors
2527 2524
  ///
2528 2525
  /// \brief Adaptor class for orienting the edges of a graph to get a digraph
2529 2526
  ///
2530 2527
  /// Orienter adaptor can be used for orienting the edges of a graph to
2531 2528
  /// get a digraph. A \c bool edge map of the underlying graph must be
2532 2529
  /// specified, which define the direction of the arcs in the adaptor.
2533 2530
  /// The arcs can be easily reversed by the \c reverseArc() member function
2534 2531
  /// of the adaptor.
2535 2532
  /// This class conforms to the \ref concepts::Digraph "Digraph" concept.
2536 2533
  ///
2537 2534
  /// The adapted graph can also be modified through this adaptor
2538 2535
  /// by adding or removing nodes or arcs, unless the \c GR template
2539 2536
  /// parameter is set to be \c const.
2540 2537
  ///
2541 2538
  /// \tparam GR The type of the adapted graph.
2542 2539
  /// It must conform to the \ref concepts::Graph "Graph" concept.
2543 2540
  /// It can also be specified to be \c const.
2544 2541
  /// \tparam DM The type of the direction map.
2545 2542
  /// It must be a \c bool (or convertible) edge map of the
2546 2543
  /// adapted graph. The default type is
2547 2544
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<bool>".
2548 2545
  ///
2549 2546
  /// \note The \c Node type of this adaptor and the adapted graph are
2550 2547
  /// convertible to each other, moreover the \c Arc type of the adaptor
2551 2548
  /// and the \c Edge type of the adapted graph are also convertible to
2552 2549
  /// each other.
2553 2550
#ifdef DOXYGEN
2554 2551
  template<typename GR,
2555 2552
           typename DM>
2556 2553
  class Orienter {
2557 2554
#else
2558 2555
  template<typename GR,
2559 2556
           typename DM = typename GR::template EdgeMap<bool> >
2560 2557
  class Orienter :
2561 2558
    public DigraphAdaptorExtender<OrienterBase<GR, DM> > {
2562 2559
#endif
2563 2560
    typedef DigraphAdaptorExtender<OrienterBase<GR, DM> > Parent;
2564 2561
  public:
2565 2562

	
2566 2563
    /// The type of the adapted graph.
2567 2564
    typedef GR Graph;
2568 2565
    /// The type of the direction edge map.
2569 2566
    typedef DM DirectionMap;
2570 2567

	
2571 2568
    typedef typename Parent::Arc Arc;
2572 2569

	
2573 2570
  protected:
2574 2571
    Orienter() { }
2575 2572

	
2576 2573
  public:
2577 2574

	
2578 2575
    /// \brief Constructor
2579 2576
    ///
2580 2577
    /// Constructor of the adaptor.
2581 2578
    Orienter(GR& graph, DM& direction) {
2582 2579
      Parent::initialize(graph, direction);
2583 2580
    }
2584 2581

	
2585 2582
    /// \brief Reverses the given arc
2586 2583
    ///
2587 2584
    /// This function reverses the given arc.
2588 2585
    /// It is done by simply negate the assigned value of \c a
2589 2586
    /// in the direction map.
2590 2587
    void reverseArc(const Arc& a) {
2591 2588
      Parent::reverseArc(a);
2592 2589
    }
2593 2590
  };
2594 2591

	
2595 2592
  /// \brief Returns a read-only Orienter adaptor
2596 2593
  ///
2597 2594
  /// This function just returns a read-only \ref Orienter adaptor.
2598 2595
  /// \ingroup graph_adaptors
2599 2596
  /// \relates Orienter
2600 2597
  template<typename GR, typename DM>
2601 2598
  Orienter<const GR, DM>
2602 2599
  orienter(const GR& graph, DM& direction) {
2603 2600
    return Orienter<const GR, DM>(graph, direction);
2604 2601
  }
2605 2602

	
2606 2603
  template<typename GR, typename DM>
2607 2604
  Orienter<const GR, const DM>
2608 2605
  orienter(const GR& graph, const DM& direction) {
2609 2606
    return Orienter<const GR, const DM>(graph, direction);
2610 2607
  }
2611 2608

	
2612 2609
  namespace _adaptor_bits {
2613 2610

	
2614 2611
    template <typename DGR, typename CM, typename FM, typename TL>
2615 2612
    class ResForwardFilter {
2616 2613
    public:
2617 2614

	
2618 2615
      typedef typename DGR::Arc Key;
2619 2616
      typedef bool Value;
2620 2617

	
2621 2618
    private:
2622 2619

	
2623 2620
      const CM* _capacity;
2624 2621
      const FM* _flow;
2625 2622
      TL _tolerance;
2626 2623

	
2627 2624
    public:
2628 2625

	
2629 2626
      ResForwardFilter(const CM& capacity, const FM& flow,
2630 2627
                       const TL& tolerance = TL())
2631 2628
        : _capacity(&capacity), _flow(&flow), _tolerance(tolerance) { }
2632 2629

	
2633 2630
      bool operator[](const typename DGR::Arc& a) const {
2634 2631
        return _tolerance.positive((*_capacity)[a] - (*_flow)[a]);
2635 2632
      }
2636 2633
    };
2637 2634

	
2638 2635
    template<typename DGR,typename CM, typename FM, typename TL>
2639 2636
    class ResBackwardFilter {
2640 2637
    public:
2641 2638

	
2642 2639
      typedef typename DGR::Arc Key;
2643 2640
      typedef bool Value;
2644 2641

	
2645 2642
    private:
2646 2643

	
2647 2644
      const CM* _capacity;
2648 2645
      const FM* _flow;
2649 2646
      TL _tolerance;
2650 2647

	
2651 2648
    public:
2652 2649

	
2653 2650
      ResBackwardFilter(const CM& capacity, const FM& flow,
2654 2651
                        const TL& tolerance = TL())
2655 2652
        : _capacity(&capacity), _flow(&flow), _tolerance(tolerance) { }
2656 2653

	
2657 2654
      bool operator[](const typename DGR::Arc& a) const {
2658 2655
        return _tolerance.positive((*_flow)[a]);
2659 2656
      }
2660 2657
    };
2661 2658

	
2662 2659
  }
2663 2660

	
2664 2661
  /// \ingroup graph_adaptors
2665 2662
  ///
2666 2663
  /// \brief Adaptor class for composing the residual digraph for directed
2667 2664
  /// flow and circulation problems.
2668 2665
  ///
2669 2666
  /// ResidualDigraph can be used for composing the \e residual digraph
2670 2667
  /// for directed flow and circulation problems. Let \f$ G=(V, A) \f$
2671 2668
  /// be a directed graph and let \f$ F \f$ be a number type.
2672 2669
  /// Let \f$ flow, cap: A\to F \f$ be functions on the arcs.
2673 2670
  /// This adaptor implements a digraph structure with node set \f$ V \f$
2674 2671
  /// and arc set \f$ A_{forward}\cup A_{backward} \f$,
2675 2672
  /// where \f$ A_{forward}=\{uv : uv\in A, flow(uv)<cap(uv)\} \f$ and
2676 2673
  /// \f$ A_{backward}=\{vu : uv\in A, flow(uv)>0\} \f$, i.e. the so
2677 2674
  /// called residual digraph.
2678 2675
  /// When the union \f$ A_{forward}\cup A_{backward} \f$ is taken,
2679 2676
  /// multiplicities are counted, i.e. the adaptor has exactly
2680 2677
  /// \f$ |A_{forward}| + |A_{backward}|\f$ arcs (it may have parallel
2681 2678
  /// arcs).
2682 2679
  /// This class conforms to the \ref concepts::Digraph "Digraph" concept.
2683 2680
  ///
2684 2681
  /// \tparam DGR The type of the adapted digraph.
2685 2682
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
2686 2683
  /// It is implicitly \c const.
2687 2684
  /// \tparam CM The type of the capacity map.
2688 2685
  /// It must be an arc map of some numerical type, which defines
2689 2686
  /// the capacities in the flow problem. It is implicitly \c const.
2690 2687
  /// The default type is
2691 2688
  /// \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
2692 2689
  /// \tparam FM The type of the flow map.
2693 2690
  /// It must be an arc map of some numerical type, which defines
2694 2691
  /// the flow values in the flow problem. The default type is \c CM.
2695 2692
  /// \tparam TL The tolerance type for handling inexact computation.
2696 2693
  /// The default tolerance type depends on the value type of the
2697 2694
  /// capacity map.
2698 2695
  ///
2699 2696
  /// \note This adaptor is implemented using Undirector and FilterArcs
2700 2697
  /// adaptors.
2701 2698
  ///
2702 2699
  /// \note The \c Node type of this adaptor and the adapted digraph are
2703 2700
  /// convertible to each other, moreover the \c Arc type of the adaptor
2704 2701
  /// is convertible to the \c Arc type of the adapted digraph.
2705 2702
#ifdef DOXYGEN
2706 2703
  template<typename DGR, typename CM, typename FM, typename TL>
2707 2704
  class ResidualDigraph
2708 2705
#else
2709 2706
  template<typename DGR,
2710 2707
           typename CM = typename DGR::template ArcMap<int>,
2711 2708
           typename FM = CM,
2712 2709
           typename TL = Tolerance<typename CM::Value> >
2713 2710
  class ResidualDigraph 
2714 2711
    : public SubDigraph<
2715 2712
        Undirector<const DGR>,
2716 2713
        ConstMap<typename DGR::Node, Const<bool, true> >,
2717 2714
        typename Undirector<const DGR>::template CombinedArcMap<
2718 2715
          _adaptor_bits::ResForwardFilter<const DGR, CM, FM, TL>,
2719 2716
          _adaptor_bits::ResBackwardFilter<const DGR, CM, FM, TL> > >
2720 2717
#endif
2721 2718
  {
2722 2719
  public:
2723 2720

	
2724 2721
    /// The type of the underlying digraph.
2725 2722
    typedef DGR Digraph;
2726 2723
    /// The type of the capacity map.
2727 2724
    typedef CM CapacityMap;
2728 2725
    /// The type of the flow map.
2729 2726
    typedef FM FlowMap;
2730 2727
    /// The tolerance type.
2731 2728
    typedef TL Tolerance;
2732 2729

	
2733 2730
    typedef typename CapacityMap::Value Value;
2734 2731
    typedef ResidualDigraph Adaptor;
2735 2732

	
2736 2733
  protected:
2737 2734

	
2738 2735
    typedef Undirector<const Digraph> Undirected;
2739 2736

	
2740 2737
    typedef ConstMap<typename DGR::Node, Const<bool, true> > NodeFilter;
2741 2738

	
2742 2739
    typedef _adaptor_bits::ResForwardFilter<const DGR, CM,
2743 2740
                                            FM, TL> ForwardFilter;
2744 2741

	
2745 2742
    typedef _adaptor_bits::ResBackwardFilter<const DGR, CM,
2746 2743
                                             FM, TL> BackwardFilter;
2747 2744

	
2748 2745
    typedef typename Undirected::
2749 2746
      template CombinedArcMap<ForwardFilter, BackwardFilter> ArcFilter;
2750 2747

	
2751 2748
    typedef SubDigraph<Undirected, NodeFilter, ArcFilter> Parent;
2752 2749

	
2753 2750
    const CapacityMap* _capacity;
2754 2751
    FlowMap* _flow;
2755 2752

	
2756 2753
    Undirected _graph;
2757 2754
    NodeFilter _node_filter;
2758 2755
    ForwardFilter _forward_filter;
2759 2756
    BackwardFilter _backward_filter;
2760 2757
    ArcFilter _arc_filter;
2761 2758

	
2762 2759
  public:
2763 2760

	
2764 2761
    /// \brief Constructor
2765 2762
    ///
2766 2763
    /// Constructor of the residual digraph adaptor. The parameters are the
2767 2764
    /// digraph, the capacity map, the flow map, and a tolerance object.
2768 2765
    ResidualDigraph(const DGR& digraph, const CM& capacity,
2769 2766
                    FM& flow, const TL& tolerance = Tolerance())
2770 2767
      : Parent(), _capacity(&capacity), _flow(&flow), 
2771 2768
        _graph(digraph), _node_filter(),
2772 2769
        _forward_filter(capacity, flow, tolerance),
2773 2770
        _backward_filter(capacity, flow, tolerance),
2774 2771
        _arc_filter(_forward_filter, _backward_filter)
2775 2772
    {
2776 2773
      Parent::initialize(_graph, _node_filter, _arc_filter);
2777 2774
    }
2778 2775

	
2779 2776
    typedef typename Parent::Arc Arc;
2780 2777

	
2781 2778
    /// \brief Returns the residual capacity of the given arc.
2782 2779
    ///
2783 2780
    /// Returns the residual capacity of the given arc.
2784 2781
    Value residualCapacity(const Arc& a) const {
2785 2782
      if (Undirected::direction(a)) {
2786 2783
        return (*_capacity)[a] - (*_flow)[a];
2787 2784
      } else {
2788 2785
        return (*_flow)[a];
2789 2786
      }
2790 2787
    }
2791 2788

	
2792 2789
    /// \brief Augments on the given arc in the residual digraph.
2793 2790
    ///
2794 2791
    /// Augments on the given arc in the residual digraph. It increases
2795 2792
    /// or decreases the flow value on the original arc according to the
2796 2793
    /// direction of the residual arc.
2797 2794
    void augment(const Arc& a, const Value& v) const {
2798 2795
      if (Undirected::direction(a)) {
2799 2796
        _flow->set(a, (*_flow)[a] + v);
2800 2797
      } else {
2801 2798
        _flow->set(a, (*_flow)[a] - v);
2802 2799
      }
2803 2800
    }
2804 2801

	
2805 2802
    /// \brief Returns \c true if the given residual arc is a forward arc.
2806 2803
    ///
2807 2804
    /// Returns \c true if the given residual arc has the same orientation
2808 2805
    /// as the original arc, i.e. it is a so called forward arc.
2809 2806
    static bool forward(const Arc& a) {
2810 2807
      return Undirected::direction(a);
2811 2808
    }
2812 2809

	
2813 2810
    /// \brief Returns \c true if the given residual arc is a backward arc.
2814 2811
    ///
2815 2812
    /// Returns \c true if the given residual arc has the opposite orientation
2816 2813
    /// than the original arc, i.e. it is a so called backward arc.
2817 2814
    static bool backward(const Arc& a) {
2818 2815
      return !Undirected::direction(a);
2819 2816
    }
2820 2817

	
2821 2818
    /// \brief Returns the forward oriented residual arc.
2822 2819
    ///
2823 2820
    /// Returns the forward oriented residual arc related to the given
2824 2821
    /// arc of the underlying digraph.
2825 2822
    static Arc forward(const typename Digraph::Arc& a) {
2826 2823
      return Undirected::direct(a, true);
2827 2824
    }
2828 2825

	
2829 2826
    /// \brief Returns the backward oriented residual arc.
2830 2827
    ///
2831 2828
    /// Returns the backward oriented residual arc related to the given
2832 2829
    /// arc of the underlying digraph.
2833 2830
    static Arc backward(const typename Digraph::Arc& a) {
2834 2831
      return Undirected::direct(a, false);
2835 2832
    }
2836 2833

	
2837 2834
    /// \brief Residual capacity map.
2838 2835
    ///
2839 2836
    /// This map adaptor class can be used for obtaining the residual
2840 2837
    /// capacities as an arc map of the residual digraph.
2841 2838
    /// Its value type is inherited from the capacity map.
2842 2839
    class ResidualCapacity {
2843 2840
    protected:
2844 2841
      const Adaptor* _adaptor;
2845 2842
    public:
2846 2843
      /// The key type of the map
2847 2844
      typedef Arc Key;
2848 2845
      /// The value type of the map
2849 2846
      typedef typename CapacityMap::Value Value;
2850 2847

	
2851 2848
      /// Constructor
2852 2849
      ResidualCapacity(const ResidualDigraph<DGR, CM, FM, TL>& adaptor) 
2853 2850
        : _adaptor(&adaptor) {}
2854 2851

	
2855 2852
      /// Returns the value associated with the given residual arc
2856 2853
      Value operator[](const Arc& a) const {
2857 2854
        return _adaptor->residualCapacity(a);
2858 2855
      }
2859 2856

	
2860 2857
    };
2861 2858

	
2862 2859
    /// \brief Returns a residual capacity map
2863 2860
    ///
2864 2861
    /// This function just returns a residual capacity map.
2865 2862
    ResidualCapacity residualCapacity() const {
2866 2863
      return ResidualCapacity(*this);
2867 2864
    }
2868 2865

	
2869 2866
  };
2870 2867

	
2871 2868
  /// \brief Returns a (read-only) Residual adaptor
2872 2869
  ///
2873 2870
  /// This function just returns a (read-only) \ref ResidualDigraph adaptor.
2874 2871
  /// \ingroup graph_adaptors
2875 2872
  /// \relates ResidualDigraph
2876 2873
    template<typename DGR, typename CM, typename FM>
2877 2874
  ResidualDigraph<DGR, CM, FM>
2878 2875
  residualDigraph(const DGR& digraph, const CM& capacity_map, FM& flow_map) {
2879 2876
    return ResidualDigraph<DGR, CM, FM> (digraph, capacity_map, flow_map);
2880 2877
  }
2881 2878

	
2882 2879

	
2883 2880
  template <typename DGR>
2884 2881
  class SplitNodesBase {
2885 2882
    typedef DigraphAdaptorBase<const DGR> Parent;
2886 2883

	
2887 2884
  public:
2888 2885

	
2889 2886
    typedef DGR Digraph;
2890 2887
    typedef SplitNodesBase Adaptor;
2891 2888

	
2892 2889
    typedef typename DGR::Node DigraphNode;
2893 2890
    typedef typename DGR::Arc DigraphArc;
2894 2891

	
2895 2892
    class Node;
2896 2893
    class Arc;
2897 2894

	
2898 2895
  private:
2899 2896

	
2900 2897
    template <typename T> class NodeMapBase;
2901 2898
    template <typename T> class ArcMapBase;
2902 2899

	
2903 2900
  public:
2904 2901

	
2905 2902
    class Node : public DigraphNode {
2906 2903
      friend class SplitNodesBase;
2907 2904
      template <typename T> friend class NodeMapBase;
2908 2905
    private:
2909 2906

	
2910 2907
      bool _in;
2911 2908
      Node(DigraphNode node, bool in)
2912 2909
        : DigraphNode(node), _in(in) {}
2913 2910

	
2914 2911
    public:
2915 2912

	
2916 2913
      Node() {}
2917 2914
      Node(Invalid) : DigraphNode(INVALID), _in(true) {}
2918 2915

	
2919 2916
      bool operator==(const Node& node) const {
2920 2917
        return DigraphNode::operator==(node) && _in == node._in;
2921 2918
      }
2922 2919

	
2923 2920
      bool operator!=(const Node& node) const {
2924 2921
        return !(*this == node);
2925 2922
      }
2926 2923

	
2927 2924
      bool operator<(const Node& node) const {
2928 2925
        return DigraphNode::operator<(node) ||
2929 2926
          (DigraphNode::operator==(node) && _in < node._in);
2930 2927
      }
2931 2928
    };
2932 2929

	
2933 2930
    class Arc {
2934 2931
      friend class SplitNodesBase;
2935 2932
      template <typename T> friend class ArcMapBase;
2936 2933
    private:
2937 2934
      typedef BiVariant<DigraphArc, DigraphNode> ArcImpl;
2938 2935

	
2939 2936
      explicit Arc(const DigraphArc& arc) : _item(arc) {}
2940 2937
      explicit Arc(const DigraphNode& node) : _item(node) {}
2941 2938

	
2942 2939
      ArcImpl _item;
2943 2940

	
2944 2941
    public:
2945 2942
      Arc() {}
2946 2943
      Arc(Invalid) : _item(DigraphArc(INVALID)) {}
2947 2944

	
2948 2945
      bool operator==(const Arc& arc) const {
2949 2946
        if (_item.firstState()) {
2950 2947
          if (arc._item.firstState()) {
2951 2948
            return _item.first() == arc._item.first();
2952 2949
          }
2953 2950
        } else {
2954 2951
          if (arc._item.secondState()) {
2955 2952
            return _item.second() == arc._item.second();
2956 2953
          }
2957 2954
        }
2958 2955
        return false;
2959 2956
      }
2960 2957

	
2961 2958
      bool operator!=(const Arc& arc) const {
2962 2959
        return !(*this == arc);
2963 2960
      }
2964 2961

	
2965 2962
      bool operator<(const Arc& arc) const {
2966 2963
        if (_item.firstState()) {
2967 2964
          if (arc._item.firstState()) {
2968 2965
            return _item.first() < arc._item.first();
2969 2966
          }
2970 2967
          return false;
2971 2968
        } else {
2972 2969
          if (arc._item.secondState()) {
2973 2970
            return _item.second() < arc._item.second();
2974 2971
          }
2975 2972
          return true;
2976 2973
        }
2977 2974
      }
2978 2975

	
2979 2976
      operator DigraphArc() const { return _item.first(); }
2980 2977
      operator DigraphNode() const { return _item.second(); }
2981 2978

	
2982 2979
    };
2983 2980

	
2984 2981
    void first(Node& n) const {
2985 2982
      _digraph->first(n);
2986 2983
      n._in = true;
2987 2984
    }
2988 2985

	
2989 2986
    void next(Node& n) const {
2990 2987
      if (n._in) {
2991 2988
        n._in = false;
2992 2989
      } else {
2993 2990
        n._in = true;
2994 2991
        _digraph->next(n);
2995 2992
      }
2996 2993
    }
2997 2994

	
2998 2995
    void first(Arc& e) const {
2999 2996
      e._item.setSecond();
3000 2997
      _digraph->first(e._item.second());
3001 2998
      if (e._item.second() == INVALID) {
3002 2999
        e._item.setFirst();
3003 3000
        _digraph->first(e._item.first());
3004 3001
      }
3005 3002
    }
3006 3003

	
3007 3004
    void next(Arc& e) const {
3008 3005
      if (e._item.secondState()) {
3009 3006
        _digraph->next(e._item.second());
3010 3007
        if (e._item.second() == INVALID) {
3011 3008
          e._item.setFirst();
3012 3009
          _digraph->first(e._item.first());
3013 3010
        }
3014 3011
      } else {
3015 3012
        _digraph->next(e._item.first());
3016 3013
      }
3017 3014
    }
3018 3015

	
3019 3016
    void firstOut(Arc& e, const Node& n) const {
3020 3017
      if (n._in) {
3021 3018
        e._item.setSecond(n);
3022 3019
      } else {
3023 3020
        e._item.setFirst();
3024 3021
        _digraph->firstOut(e._item.first(), n);
3025 3022
      }
3026 3023
    }
3027 3024

	
3028 3025
    void nextOut(Arc& e) const {
3029 3026
      if (!e._item.firstState()) {
3030 3027
        e._item.setFirst(INVALID);
3031 3028
      } else {
3032 3029
        _digraph->nextOut(e._item.first());
3033 3030
      }
3034 3031
    }
3035 3032

	
3036 3033
    void firstIn(Arc& e, const Node& n) const {
3037 3034
      if (!n._in) {
3038 3035
        e._item.setSecond(n);
3039 3036
      } else {
3040 3037
        e._item.setFirst();
3041 3038
        _digraph->firstIn(e._item.first(), n);
3042 3039
      }
3043 3040
    }
3044 3041

	
3045 3042
    void nextIn(Arc& e) const {
3046 3043
      if (!e._item.firstState()) {
3047 3044
        e._item.setFirst(INVALID);
3048 3045
      } else {
3049 3046
        _digraph->nextIn(e._item.first());
3050 3047
      }
3051 3048
    }
3052 3049

	
3053 3050
    Node source(const Arc& e) const {
3054 3051
      if (e._item.firstState()) {
3055 3052
        return Node(_digraph->source(e._item.first()), false);
3056 3053
      } else {
3057 3054
        return Node(e._item.second(), true);
3058 3055
      }
3059 3056
    }
3060 3057

	
3061 3058
    Node target(const Arc& e) const {
3062 3059
      if (e._item.firstState()) {
3063 3060
        return Node(_digraph->target(e._item.first()), true);
3064 3061
      } else {
3065 3062
        return Node(e._item.second(), false);
3066 3063
      }
3067 3064
    }
3068 3065

	
3069 3066
    int id(const Node& n) const {
3070 3067
      return (_digraph->id(n) << 1) | (n._in ? 0 : 1);
3071 3068
    }
3072 3069
    Node nodeFromId(int ix) const {
3073 3070
      return Node(_digraph->nodeFromId(ix >> 1), (ix & 1) == 0);
3074 3071
    }
3075 3072
    int maxNodeId() const {
3076 3073
      return 2 * _digraph->maxNodeId() + 1;
3077 3074
    }
3078 3075

	
3079 3076
    int id(const Arc& e) const {
3080 3077
      if (e._item.firstState()) {
3081 3078
        return _digraph->id(e._item.first()) << 1;
3082 3079
      } else {
3083 3080
        return (_digraph->id(e._item.second()) << 1) | 1;
3084 3081
      }
3085 3082
    }
3086 3083
    Arc arcFromId(int ix) const {
3087 3084
      if ((ix & 1) == 0) {
3088 3085
        return Arc(_digraph->arcFromId(ix >> 1));
3089 3086
      } else {
3090 3087
        return Arc(_digraph->nodeFromId(ix >> 1));
3091 3088
      }
3092 3089
    }
3093 3090
    int maxArcId() const {
3094 3091
      return std::max(_digraph->maxNodeId() << 1,
3095 3092
                      (_digraph->maxArcId() << 1) | 1);
3096 3093
    }
3097 3094

	
3098 3095
    static bool inNode(const Node& n) {
3099 3096
      return n._in;
3100 3097
    }
3101 3098

	
3102 3099
    static bool outNode(const Node& n) {
3103 3100
      return !n._in;
3104 3101
    }
3105 3102

	
3106 3103
    static bool origArc(const Arc& e) {
3107 3104
      return e._item.firstState();
3108 3105
    }
3109 3106

	
3110 3107
    static bool bindArc(const Arc& e) {
3111 3108
      return e._item.secondState();
3112 3109
    }
3113 3110

	
3114 3111
    static Node inNode(const DigraphNode& n) {
3115 3112
      return Node(n, true);
3116 3113
    }
3117 3114

	
3118 3115
    static Node outNode(const DigraphNode& n) {
3119 3116
      return Node(n, false);
3120 3117
    }
3121 3118

	
3122 3119
    static Arc arc(const DigraphNode& n) {
3123 3120
      return Arc(n);
3124 3121
    }
3125 3122

	
3126 3123
    static Arc arc(const DigraphArc& e) {
3127 3124
      return Arc(e);
3128 3125
    }
3129 3126

	
3130 3127
    typedef True NodeNumTag;
3131 3128
    int nodeNum() const {
3132 3129
      return  2 * countNodes(*_digraph);
3133 3130
    }
3134 3131

	
3135 3132
    typedef True ArcNumTag;
3136 3133
    int arcNum() const {
3137 3134
      return countArcs(*_digraph) + countNodes(*_digraph);
3138 3135
    }
3139 3136

	
3140 3137
    typedef True FindArcTag;
3141 3138
    Arc findArc(const Node& u, const Node& v,
3142 3139
                const Arc& prev = INVALID) const {
3143 3140
      if (inNode(u) && outNode(v)) {
3144 3141
        if (static_cast<const DigraphNode&>(u) ==
3145 3142
            static_cast<const DigraphNode&>(v) && prev == INVALID) {
3146 3143
          return Arc(u);
3147 3144
        }
3148 3145
      }
3149 3146
      else if (outNode(u) && inNode(v)) {
3150 3147
        return Arc(::lemon::findArc(*_digraph, u, v, prev));
3151 3148
      }
3152 3149
      return INVALID;
3153 3150
    }
3154 3151

	
3155 3152
  private:
3156 3153

	
3157 3154
    template <typename V>
3158 3155
    class NodeMapBase
3159 3156
      : public MapTraits<typename Parent::template NodeMap<V> > {
3160 3157
      typedef typename Parent::template NodeMap<V> NodeImpl;
3161 3158
    public:
3162 3159
      typedef Node Key;
3163 3160
      typedef V Value;
3164 3161
      typedef typename MapTraits<NodeImpl>::ReferenceMapTag ReferenceMapTag;
3165 3162
      typedef typename MapTraits<NodeImpl>::ReturnValue ReturnValue;
3166 3163
      typedef typename MapTraits<NodeImpl>::ConstReturnValue ConstReturnValue;
3167 3164
      typedef typename MapTraits<NodeImpl>::ReturnValue Reference;
3168 3165
      typedef typename MapTraits<NodeImpl>::ConstReturnValue ConstReference;
3169 3166

	
3170 3167
      NodeMapBase(const SplitNodesBase<DGR>& adaptor)
3171 3168
        : _in_map(*adaptor._digraph), _out_map(*adaptor._digraph) {}
3172 3169
      NodeMapBase(const SplitNodesBase<DGR>& adaptor, const V& value)
3173 3170
        : _in_map(*adaptor._digraph, value),
3174 3171
          _out_map(*adaptor._digraph, value) {}
3175 3172

	
3176 3173
      void set(const Node& key, const V& val) {
3177 3174
        if (SplitNodesBase<DGR>::inNode(key)) { _in_map.set(key, val); }
3178 3175
        else {_out_map.set(key, val); }
3179 3176
      }
3180 3177

	
3181 3178
      ReturnValue operator[](const Node& key) {
3182 3179
        if (SplitNodesBase<DGR>::inNode(key)) { return _in_map[key]; }
3183 3180
        else { return _out_map[key]; }
3184 3181
      }
3185 3182

	
3186 3183
      ConstReturnValue operator[](const Node& key) const {
3187 3184
        if (Adaptor::inNode(key)) { return _in_map[key]; }
3188 3185
        else { return _out_map[key]; }
3189 3186
      }
3190 3187

	
3191 3188
    private:
3192 3189
      NodeImpl _in_map, _out_map;
3193 3190
    };
3194 3191

	
3195 3192
    template <typename V>
3196 3193
    class ArcMapBase
3197 3194
      : public MapTraits<typename Parent::template ArcMap<V> > {
3198 3195
      typedef typename Parent::template ArcMap<V> ArcImpl;
3199 3196
      typedef typename Parent::template NodeMap<V> NodeImpl;
3200 3197
    public:
3201 3198
      typedef Arc Key;
3202 3199
      typedef V Value;
3203 3200
      typedef typename MapTraits<ArcImpl>::ReferenceMapTag ReferenceMapTag;
3204 3201
      typedef typename MapTraits<ArcImpl>::ReturnValue ReturnValue;
3205 3202
      typedef typename MapTraits<ArcImpl>::ConstReturnValue ConstReturnValue;
3206 3203
      typedef typename MapTraits<ArcImpl>::ReturnValue Reference;
3207 3204
      typedef typename MapTraits<ArcImpl>::ConstReturnValue ConstReference;
3208 3205

	
3209 3206
      ArcMapBase(const SplitNodesBase<DGR>& adaptor)
3210 3207
        : _arc_map(*adaptor._digraph), _node_map(*adaptor._digraph) {}
3211 3208
      ArcMapBase(const SplitNodesBase<DGR>& adaptor, const V& value)
3212 3209
        : _arc_map(*adaptor._digraph, value),
3213 3210
          _node_map(*adaptor._digraph, value) {}
3214 3211

	
3215 3212
      void set(const Arc& key, const V& val) {
3216 3213
        if (SplitNodesBase<DGR>::origArc(key)) {
3217 3214
          _arc_map.set(static_cast<const DigraphArc&>(key), val);
3218 3215
        } else {
3219 3216
          _node_map.set(static_cast<const DigraphNode&>(key), val);
3220 3217
        }
3221 3218
      }
3222 3219

	
3223 3220
      ReturnValue operator[](const Arc& key) {
3224 3221
        if (SplitNodesBase<DGR>::origArc(key)) {
3225 3222
          return _arc_map[static_cast<const DigraphArc&>(key)];
3226 3223
        } else {
3227 3224
          return _node_map[static_cast<const DigraphNode&>(key)];
3228 3225
        }
3229 3226
      }
3230 3227

	
3231 3228
      ConstReturnValue operator[](const Arc& key) const {
3232 3229
        if (SplitNodesBase<DGR>::origArc(key)) {
3233 3230
          return _arc_map[static_cast<const DigraphArc&>(key)];
3234 3231
        } else {
3235 3232
          return _node_map[static_cast<const DigraphNode&>(key)];
3236 3233
        }
3237 3234
      }
3238 3235

	
3239 3236
    private:
3240 3237
      ArcImpl _arc_map;
3241 3238
      NodeImpl _node_map;
3242 3239
    };
3243 3240

	
3244 3241
  public:
3245 3242

	
3246 3243
    template <typename V>
3247 3244
    class NodeMap
3248 3245
      : public SubMapExtender<SplitNodesBase<DGR>, NodeMapBase<V> > {
3249 3246
      typedef SubMapExtender<SplitNodesBase<DGR>, NodeMapBase<V> > Parent;
3250 3247

	
3251 3248
    public:
3252 3249
      typedef V Value;
3253 3250

	
3254 3251
      NodeMap(const SplitNodesBase<DGR>& adaptor)
3255 3252
        : Parent(adaptor) {}
3256 3253

	
3257 3254
      NodeMap(const SplitNodesBase<DGR>& adaptor, const V& value)
3258 3255
        : Parent(adaptor, value) {}
3259 3256

	
3260 3257
    private:
3261 3258
      NodeMap& operator=(const NodeMap& cmap) {
3262 3259
        return operator=<NodeMap>(cmap);
3263 3260
      }
3264 3261

	
3265 3262
      template <typename CMap>
3266 3263
      NodeMap& operator=(const CMap& cmap) {
3267 3264
        Parent::operator=(cmap);
3268 3265
        return *this;
3269 3266
      }
3270 3267
    };
3271 3268

	
3272 3269
    template <typename V>
3273 3270
    class ArcMap
3274 3271
      : public SubMapExtender<SplitNodesBase<DGR>, ArcMapBase<V> > {
3275 3272
      typedef SubMapExtender<SplitNodesBase<DGR>, ArcMapBase<V> > Parent;
3276 3273

	
3277 3274
    public:
3278 3275
      typedef V Value;
3279 3276

	
3280 3277
      ArcMap(const SplitNodesBase<DGR>& adaptor)
3281 3278
        : Parent(adaptor) {}
3282 3279

	
3283 3280
      ArcMap(const SplitNodesBase<DGR>& adaptor, const V& value)
3284 3281
        : Parent(adaptor, value) {}
3285 3282

	
3286 3283
    private:
3287 3284
      ArcMap& operator=(const ArcMap& cmap) {
3288 3285
        return operator=<ArcMap>(cmap);
3289 3286
      }
3290 3287

	
3291 3288
      template <typename CMap>
3292 3289
      ArcMap& operator=(const CMap& cmap) {
3293 3290
        Parent::operator=(cmap);
3294 3291
        return *this;
3295 3292
      }
3296 3293
    };
3297 3294

	
3298 3295
  protected:
3299 3296

	
3300 3297
    SplitNodesBase() : _digraph(0) {}
3301 3298

	
3302 3299
    DGR* _digraph;
3303 3300

	
3304 3301
    void initialize(Digraph& digraph) {
3305 3302
      _digraph = &digraph;
3306 3303
    }
3307 3304

	
3308 3305
  };
3309 3306

	
3310 3307
  /// \ingroup graph_adaptors
3311 3308
  ///
3312 3309
  /// \brief Adaptor class for splitting the nodes of a digraph.
3313 3310
  ///
3314 3311
  /// SplitNodes adaptor can be used for splitting each node into an
3315 3312
  /// \e in-node and an \e out-node in a digraph. Formaly, the adaptor
3316 3313
  /// replaces each node \f$ u \f$ in the digraph with two nodes,
3317 3314
  /// namely node \f$ u_{in} \f$ and node \f$ u_{out} \f$.
3318 3315
  /// If there is a \f$ (v, u) \f$ arc in the original digraph, then the
3319 3316
  /// new target of the arc will be \f$ u_{in} \f$ and similarly the
3320 3317
  /// source of each original \f$ (u, v) \f$ arc will be \f$ u_{out} \f$.
3321 3318
  /// The adaptor adds an additional \e bind \e arc from \f$ u_{in} \f$
3322 3319
  /// to \f$ u_{out} \f$ for each node \f$ u \f$ of the original digraph.
3323 3320
  ///
3324 3321
  /// The aim of this class is running an algorithm with respect to node
3325 3322
  /// costs or capacities if the algorithm considers only arc costs or
3326 3323
  /// capacities directly.
3327 3324
  /// In this case you can use \c SplitNodes adaptor, and set the node
3328 3325
  /// costs/capacities of the original digraph to the \e bind \e arcs
3329 3326
  /// in the adaptor.
3330 3327
  ///
3331 3328
  /// \tparam DGR The type of the adapted digraph.
3332 3329
  /// It must conform to the \ref concepts::Digraph "Digraph" concept.
3333 3330
  /// It is implicitly \c const.
3334 3331
  ///
3335 3332
  /// \note The \c Node type of this adaptor is converible to the \c Node
3336 3333
  /// type of the adapted digraph.
3337 3334
  template <typename DGR>
3338 3335
#ifdef DOXYGEN
3339 3336
  class SplitNodes {
3340 3337
#else
3341 3338
  class SplitNodes
3342 3339
    : public DigraphAdaptorExtender<SplitNodesBase<const DGR> > {
3343 3340
#endif
3344 3341
    typedef DigraphAdaptorExtender<SplitNodesBase<const DGR> > Parent;
3345 3342

	
3346 3343
  public:
3347 3344
    typedef DGR Digraph;
3348 3345

	
3349 3346
    typedef typename DGR::Node DigraphNode;
3350 3347
    typedef typename DGR::Arc DigraphArc;
3351 3348

	
3352 3349
    typedef typename Parent::Node Node;
3353 3350
    typedef typename Parent::Arc Arc;
3354 3351

	
3355 3352
    /// \brief Constructor
3356 3353
    ///
3357 3354
    /// Constructor of the adaptor.
3358 3355
    SplitNodes(const DGR& g) {
3359 3356
      Parent::initialize(g);
3360 3357
    }
3361 3358

	
3362 3359
    /// \brief Returns \c true if the given node is an in-node.
3363 3360
    ///
3364 3361
    /// Returns \c true if the given node is an in-node.
3365 3362
    static bool inNode(const Node& n) {
3366 3363
      return Parent::inNode(n);
3367 3364
    }
3368 3365

	
3369 3366
    /// \brief Returns \c true if the given node is an out-node.
3370 3367
    ///
3371 3368
    /// Returns \c true if the given node is an out-node.
3372 3369
    static bool outNode(const Node& n) {
3373 3370
      return Parent::outNode(n);
3374 3371
    }
3375 3372

	
3376 3373
    /// \brief Returns \c true if the given arc is an original arc.
3377 3374
    ///
3378 3375
    /// Returns \c true if the given arc is one of the arcs in the
3379 3376
    /// original digraph.
3380 3377
    static bool origArc(const Arc& a) {
3381 3378
      return Parent::origArc(a);
3382 3379
    }
3383 3380

	
3384 3381
    /// \brief Returns \c true if the given arc is a bind arc.
3385 3382
    ///
3386 3383
    /// Returns \c true if the given arc is a bind arc, i.e. it connects
3387 3384
    /// an in-node and an out-node.
3388 3385
    static bool bindArc(const Arc& a) {
3389 3386
      return Parent::bindArc(a);
3390 3387
    }
3391 3388

	
3392 3389
    /// \brief Returns the in-node created from the given original node.
3393 3390
    ///
3394 3391
    /// Returns the in-node created from the given original node.
3395 3392
    static Node inNode(const DigraphNode& n) {
3396 3393
      return Parent::inNode(n);
3397 3394
    }
3398 3395

	
3399 3396
    /// \brief Returns the out-node created from the given original node.
3400 3397
    ///
3401 3398
    /// Returns the out-node created from the given original node.
3402 3399
    static Node outNode(const DigraphNode& n) {
3403 3400
      return Parent::outNode(n);
3404 3401
    }
3405 3402

	
3406 3403
    /// \brief Returns the bind arc that corresponds to the given
3407 3404
    /// original node.
3408 3405
    ///
3409 3406
    /// Returns the bind arc in the adaptor that corresponds to the given
3410 3407
    /// original node, i.e. the arc connecting the in-node and out-node
3411 3408
    /// of \c n.
3412 3409
    static Arc arc(const DigraphNode& n) {
3413 3410
      return Parent::arc(n);
3414 3411
    }
3415 3412

	
3416 3413
    /// \brief Returns the arc that corresponds to the given original arc.
3417 3414
    ///
3418 3415
    /// Returns the arc in the adaptor that corresponds to the given
3419 3416
    /// original arc.
3420 3417
    static Arc arc(const DigraphArc& a) {
3421 3418
      return Parent::arc(a);
3422 3419
    }
3423 3420

	
3424 3421
    /// \brief Node map combined from two original node maps
3425 3422
    ///
3426 3423
    /// This map adaptor class adapts two node maps of the original digraph
3427 3424
    /// to get a node map of the split digraph.
3428 3425
    /// Its value type is inherited from the first node map type (\c IN).
3429 3426
    /// \tparam IN The type of the node map for the in-nodes. 
3430 3427
    /// \tparam OUT The type of the node map for the out-nodes.
3431 3428
    template <typename IN, typename OUT>
3432 3429
    class CombinedNodeMap {
3433 3430
    public:
3434 3431

	
3435 3432
      /// The key type of the map
3436 3433
      typedef Node Key;
3437 3434
      /// The value type of the map
3438 3435
      typedef typename IN::Value Value;
3439 3436

	
3440 3437
      typedef typename MapTraits<IN>::ReferenceMapTag ReferenceMapTag;
3441 3438
      typedef typename MapTraits<IN>::ReturnValue ReturnValue;
3442 3439
      typedef typename MapTraits<IN>::ConstReturnValue ConstReturnValue;
3443 3440
      typedef typename MapTraits<IN>::ReturnValue Reference;
3444 3441
      typedef typename MapTraits<IN>::ConstReturnValue ConstReference;
3445 3442

	
3446 3443
      /// Constructor
3447 3444
      CombinedNodeMap(IN& in_map, OUT& out_map)
3448 3445
        : _in_map(in_map), _out_map(out_map) {}
3449 3446

	
3450 3447
      /// Returns the value associated with the given key.
3451 3448
      Value operator[](const Key& key) const {
3452 3449
        if (SplitNodesBase<const DGR>::inNode(key)) {
3453 3450
          return _in_map[key];
3454 3451
        } else {
3455 3452
          return _out_map[key];
3456 3453
        }
3457 3454
      }
3458 3455

	
3459 3456
      /// Returns a reference to the value associated with the given key.
3460 3457
      Value& operator[](const Key& key) {
3461 3458
        if (SplitNodesBase<const DGR>::inNode(key)) {
3462 3459
          return _in_map[key];
3463 3460
        } else {
3464 3461
          return _out_map[key];
3465 3462
        }
3466 3463
      }
3467 3464

	
3468 3465
      /// Sets the value associated with the given key.
3469 3466
      void set(const Key& key, const Value& value) {
3470 3467
        if (SplitNodesBase<const DGR>::inNode(key)) {
3471 3468
          _in_map.set(key, value);
3472 3469
        } else {
3473 3470
          _out_map.set(key, value);
3474 3471
        }
3475 3472
      }
3476 3473

	
3477 3474
    private:
3478 3475

	
3479 3476
      IN& _in_map;
3480 3477
      OUT& _out_map;
3481 3478

	
3482 3479
    };
3483 3480

	
3484 3481

	
3485 3482
    /// \brief Returns a combined node map
3486 3483
    ///
3487 3484
    /// This function just returns a combined node map.
3488 3485
    template <typename IN, typename OUT>
3489 3486
    static CombinedNodeMap<IN, OUT>
3490 3487
    combinedNodeMap(IN& in_map, OUT& out_map) {
3491 3488
      return CombinedNodeMap<IN, OUT>(in_map, out_map);
3492 3489
    }
3493 3490

	
3494 3491
    template <typename IN, typename OUT>
3495 3492
    static CombinedNodeMap<const IN, OUT>
3496 3493
    combinedNodeMap(const IN& in_map, OUT& out_map) {
3497 3494
      return CombinedNodeMap<const IN, OUT>(in_map, out_map);
3498 3495
    }
3499 3496

	
3500 3497
    template <typename IN, typename OUT>
3501 3498
    static CombinedNodeMap<IN, const OUT>
3502 3499
    combinedNodeMap(IN& in_map, const OUT& out_map) {
3503 3500
      return CombinedNodeMap<IN, const OUT>(in_map, out_map);
3504 3501
    }
3505 3502

	
3506 3503
    template <typename IN, typename OUT>
3507 3504
    static CombinedNodeMap<const IN, const OUT>
3508 3505
    combinedNodeMap(const IN& in_map, const OUT& out_map) {
3509 3506
      return CombinedNodeMap<const IN, const OUT>(in_map, out_map);
3510 3507
    }
3511 3508

	
3512 3509
    /// \brief Arc map combined from an arc map and a node map of the
3513 3510
    /// original digraph.
3514 3511
    ///
3515 3512
    /// This map adaptor class adapts an arc map and a node map of the
3516 3513
    /// original digraph to get an arc map of the split digraph.
3517 3514
    /// Its value type is inherited from the original arc map type (\c AM).
3518 3515
    /// \tparam AM The type of the arc map.
3519 3516
    /// \tparam NM the type of the node map.
3520 3517
    template <typename AM, typename NM>
3521 3518
    class CombinedArcMap {
3522 3519
    public:
3523 3520

	
3524 3521
      /// The key type of the map
3525 3522
      typedef Arc Key;
3526 3523
      /// The value type of the map
3527 3524
      typedef typename AM::Value Value;
3528 3525

	
3529 3526
      typedef typename MapTraits<AM>::ReferenceMapTag ReferenceMapTag;
3530 3527
      typedef typename MapTraits<AM>::ReturnValue ReturnValue;
3531 3528
      typedef typename MapTraits<AM>::ConstReturnValue ConstReturnValue;
3532 3529
      typedef typename MapTraits<AM>::ReturnValue Reference;
3533 3530
      typedef typename MapTraits<AM>::ConstReturnValue ConstReference;
3534 3531

	
3535 3532
      /// Constructor
3536 3533
      CombinedArcMap(AM& arc_map, NM& node_map)
3537 3534
        : _arc_map(arc_map), _node_map(node_map) {}
3538 3535

	
3539 3536
      /// Returns the value associated with the given key.
3540 3537
      Value operator[](const Key& arc) const {
3541 3538
        if (SplitNodesBase<const DGR>::origArc(arc)) {
3542 3539
          return _arc_map[arc];
3543 3540
        } else {
3544 3541
          return _node_map[arc];
3545 3542
        }
3546 3543
      }
3547 3544

	
3548 3545
      /// Returns a reference to the value associated with the given key.
3549 3546
      Value& operator[](const Key& arc) {
3550 3547
        if (SplitNodesBase<const DGR>::origArc(arc)) {
3551 3548
          return _arc_map[arc];
3552 3549
        } else {
3553 3550
          return _node_map[arc];
3554 3551
        }
3555 3552
      }
3556 3553

	
3557 3554
      /// Sets the value associated with the given key.
3558 3555
      void set(const Arc& arc, const Value& val) {
3559 3556
        if (SplitNodesBase<const DGR>::origArc(arc)) {
3560 3557
          _arc_map.set(arc, val);
3561 3558
        } else {
3562 3559
          _node_map.set(arc, val);
3563 3560
        }
3564 3561
      }
3565 3562

	
3566 3563
    private:
3567 3564

	
3568 3565
      AM& _arc_map;
3569 3566
      NM& _node_map;
3570 3567

	
3571 3568
    };
3572 3569

	
3573 3570
    /// \brief Returns a combined arc map
3574 3571
    ///
3575 3572
    /// This function just returns a combined arc map.
3576 3573
    template <typename ArcMap, typename NodeMap>
3577 3574
    static CombinedArcMap<ArcMap, NodeMap>
3578 3575
    combinedArcMap(ArcMap& arc_map, NodeMap& node_map) {
3579 3576
      return CombinedArcMap<ArcMap, NodeMap>(arc_map, node_map);
3580 3577
    }
3581 3578

	
3582 3579
    template <typename ArcMap, typename NodeMap>
3583 3580
    static CombinedArcMap<const ArcMap, NodeMap>
3584 3581
    combinedArcMap(const ArcMap& arc_map, NodeMap& node_map) {
3585 3582
      return CombinedArcMap<const ArcMap, NodeMap>(arc_map, node_map);
3586 3583
    }
3587 3584

	
3588 3585
    template <typename ArcMap, typename NodeMap>
3589 3586
    static CombinedArcMap<ArcMap, const NodeMap>
3590 3587
    combinedArcMap(ArcMap& arc_map, const NodeMap& node_map) {
3591 3588
      return CombinedArcMap<ArcMap, const NodeMap>(arc_map, node_map);
3592 3589
    }
3593 3590

	
3594 3591
    template <typename ArcMap, typename NodeMap>
3595 3592
    static CombinedArcMap<const ArcMap, const NodeMap>
3596 3593
    combinedArcMap(const ArcMap& arc_map, const NodeMap& node_map) {
3597 3594
      return CombinedArcMap<const ArcMap, const NodeMap>(arc_map, node_map);
3598 3595
    }
3599 3596

	
3600 3597
  };
3601 3598

	
3602 3599
  /// \brief Returns a (read-only) SplitNodes adaptor
3603 3600
  ///
3604 3601
  /// This function just returns a (read-only) \ref SplitNodes adaptor.
3605 3602
  /// \ingroup graph_adaptors
3606 3603
  /// \relates SplitNodes
3607 3604
  template<typename DGR>
3608 3605
  SplitNodes<DGR>
3609 3606
  splitNodes(const DGR& digraph) {
3610 3607
    return SplitNodes<DGR>(digraph);
3611 3608
  }
3612 3609

	
3613 3610
#undef LEMON_SCOPE_FIX
3614 3611

	
3615 3612
} //namespace lemon
3616 3613

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

	
19 19
///\ingroup graph_concepts
20 20
///\file
21 21
///\brief The concept of 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/core.h>
28 28

	
29 29
namespace lemon {
30 30
  namespace concepts {
31 31

	
32 32
    /// \ingroup graph_concepts
33 33
    ///
34 34
    /// \brief Class describing the concept of Undirected Graphs.
35 35
    ///
36 36
    /// This class describes the common interface of all Undirected
37 37
    /// Graphs.
38 38
    ///
39 39
    /// As all concept describing classes it provides only interface
40 40
    /// without any sensible implementation. So any algorithm for
41 41
    /// undirected graph should compile with this class, but it will not
42 42
    /// run properly, of course.
43 43
    ///
44 44
    /// The LEMON undirected graphs also fulfill the concept of
45 45
    /// directed graphs (\ref lemon::concepts::Digraph "Digraph
46 46
    /// Concept"). Each edges can be seen as two opposite
47 47
    /// directed arc and consequently the undirected graph can be
48 48
    /// seen as the direceted graph of these directed arcs. The
49 49
    /// Graph has the Edge inner class for the edges and
50 50
    /// the Arc type for the directed arcs. The Arc type is
51 51
    /// convertible to Edge or inherited from it so from a directed
52 52
    /// arc we can get the represented edge.
53 53
    ///
54 54
    /// In the sense of the LEMON each edge has a default
55 55
    /// direction (it should be in every computer implementation,
56 56
    /// because the order of edge's nodes defines an
57 57
    /// orientation). With the default orientation we can define that
58 58
    /// the directed arc is forward or backward directed. With the \c
59 59
    /// direction() and \c direct() function we can get the direction
60 60
    /// of the directed arc and we can direct an edge.
61 61
    ///
62 62
    /// The EdgeIt is an iterator for the edges. We can use
63 63
    /// the EdgeMap to map values for the edges. The InArcIt and
64 64
    /// OutArcIt iterates on the same edges but with opposite
65 65
    /// direction. The IncEdgeIt iterates also on the same edges
66 66
    /// as the OutArcIt and InArcIt but it is not convertible to Arc just
67 67
    /// to Edge.
68 68
    class Graph {
69 69
    public:
70 70
      /// \brief The undirected graph should be tagged by the
71 71
      /// UndirectedTag.
72 72
      ///
73 73
      /// The undirected graph should be tagged by the UndirectedTag. This
74 74
      /// tag helps the enable_if technics to make compile time
75 75
      /// specializations for undirected graphs.
76 76
      typedef True UndirectedTag;
77 77

	
78 78
      /// \brief The base type of node iterators,
79 79
      /// or in other words, the trivial node iterator.
80 80
      ///
81 81
      /// This is the base type of each node iterator,
82 82
      /// thus each kind of node iterator converts to this.
83 83
      /// More precisely each kind of node iterator should be inherited
84 84
      /// from the trivial node iterator.
85 85
      class Node {
86 86
      public:
87 87
        /// Default constructor
88 88

	
89 89
        /// @warning The default constructor sets the iterator
90 90
        /// to an undefined value.
91 91
        Node() { }
92 92
        /// Copy constructor.
93 93

	
94 94
        /// Copy constructor.
95 95
        ///
96 96
        Node(const Node&) { }
97 97

	
98 98
        /// Invalid constructor \& conversion.
99 99

	
100 100
        /// This constructor initializes the iterator to be invalid.
101 101
        /// \sa Invalid for more details.
102 102
        Node(Invalid) { }
103 103
        /// Equality operator
104 104

	
105 105
        /// Two iterators are equal if and only if they point to the
106 106
        /// same object or both are invalid.
107 107
        bool operator==(Node) const { return true; }
108 108

	
109 109
        /// Inequality operator
110 110

	
111 111
        /// \sa operator==(Node n)
112 112
        ///
113 113
        bool operator!=(Node) const { return true; }
114 114

	
115 115
        /// Artificial ordering operator.
116 116

	
117 117
        /// To allow the use of graph descriptors as key type in std::map or
118 118
        /// similar associative container we require this.
119 119
        ///
120 120
        /// \note This operator only have to define some strict ordering of
121 121
        /// the items; this order has nothing to do with the iteration
122 122
        /// ordering of the items.
123 123
        bool operator<(Node) const { return false; }
124 124

	
125 125
      };
126 126

	
127 127
      /// This iterator goes through each node.
128 128

	
129 129
      /// This iterator goes through each node.
130 130
      /// Its usage is quite simple, for example you can count the number
131 131
      /// of nodes in graph \c g of type \c Graph like this:
132 132
      ///\code
133 133
      /// int count=0;
134 134
      /// for (Graph::NodeIt n(g); n!=INVALID; ++n) ++count;
135 135
      ///\endcode
136 136
      class NodeIt : public Node {
137 137
      public:
138 138
        /// Default constructor
139 139

	
140 140
        /// @warning The default constructor sets the iterator
141 141
        /// to an undefined value.
142 142
        NodeIt() { }
143 143
        /// Copy constructor.
144 144

	
145 145
        /// Copy constructor.
146 146
        ///
147 147
        NodeIt(const NodeIt& n) : Node(n) { }
148 148
        /// Invalid constructor \& conversion.
149 149

	
150 150
        /// Initialize the iterator to be invalid.
151 151
        /// \sa Invalid for more details.
152 152
        NodeIt(Invalid) { }
153 153
        /// Sets the iterator to the first node.
154 154

	
155 155
        /// Sets the iterator to the first node of \c g.
156 156
        ///
157 157
        NodeIt(const Graph&) { }
158 158
        /// Node -> NodeIt conversion.
159 159

	
160 160
        /// Sets the iterator to the node of \c the graph pointed by
161 161
        /// the trivial iterator.
162 162
        /// This feature necessitates that each time we
163 163
        /// iterate the arc-set, the iteration order is the same.
164 164
        NodeIt(const Graph&, const Node&) { }
165 165
        /// Next node.
166 166

	
167 167
        /// Assign the iterator to the next node.
168 168
        ///
169 169
        NodeIt& operator++() { return *this; }
170 170
      };
171 171

	
172 172

	
173 173
      /// The base type of the edge iterators.
174 174

	
175 175
      /// The base type of the edge iterators.
176 176
      ///
177 177
      class Edge {
178 178
      public:
179 179
        /// Default constructor
180 180

	
181 181
        /// @warning The default constructor sets the iterator
182 182
        /// to an undefined value.
183 183
        Edge() { }
184 184
        /// Copy constructor.
185 185

	
186 186
        /// Copy constructor.
187 187
        ///
188 188
        Edge(const Edge&) { }
189 189
        /// Initialize the iterator to be invalid.
190 190

	
191 191
        /// Initialize the iterator to be invalid.
192 192
        ///
193 193
        Edge(Invalid) { }
194 194
        /// Equality operator
195 195

	
196 196
        /// Two iterators are equal if and only if they point to the
197 197
        /// same object or both are invalid.
198 198
        bool operator==(Edge) const { return true; }
199 199
        /// Inequality operator
200 200

	
201 201
        /// \sa operator==(Edge n)
202 202
        ///
203 203
        bool operator!=(Edge) const { return true; }
204 204

	
205 205
        /// Artificial ordering operator.
206 206

	
207 207
        /// To allow the use of graph descriptors as key type in std::map or
208 208
        /// similar associative container we require this.
209 209
        ///
210 210
        /// \note This operator only have to define some strict ordering of
211 211
        /// the items; this order has nothing to do with the iteration
212 212
        /// ordering of the items.
213 213
        bool operator<(Edge) const { return false; }
214 214
      };
215 215

	
216 216
      /// This iterator goes through each edge.
217 217

	
218 218
      /// This iterator goes through each edge of a graph.
219 219
      /// Its usage is quite simple, for example you can count the number
220 220
      /// of edges in a graph \c g of type \c Graph as follows:
221 221
      ///\code
222 222
      /// int count=0;
223 223
      /// for(Graph::EdgeIt e(g); e!=INVALID; ++e) ++count;
224 224
      ///\endcode
225 225
      class EdgeIt : public Edge {
226 226
      public:
227 227
        /// Default constructor
228 228

	
229 229
        /// @warning The default constructor sets the iterator
230 230
        /// to an undefined value.
231 231
        EdgeIt() { }
232 232
        /// Copy constructor.
233 233

	
234 234
        /// Copy constructor.
235 235
        ///
236 236
        EdgeIt(const EdgeIt& e) : Edge(e) { }
237 237
        /// Initialize the iterator to be invalid.
238 238

	
239 239
        /// Initialize the iterator to be invalid.
240 240
        ///
241 241
        EdgeIt(Invalid) { }
242 242
        /// This constructor sets the iterator to the first edge.
243 243

	
244 244
        /// This constructor sets the iterator to the first edge.
245 245
        EdgeIt(const Graph&) { }
246 246
        /// Edge -> EdgeIt conversion
247 247

	
248 248
        /// Sets the iterator to the value of the trivial iterator.
249 249
        /// This feature necessitates that each time we
250 250
        /// iterate the edge-set, the iteration order is the
251 251
        /// same.
252 252
        EdgeIt(const Graph&, const Edge&) { }
253 253
        /// Next edge
254 254

	
255 255
        /// Assign the iterator to the next edge.
256 256
        EdgeIt& operator++() { return *this; }
257 257
      };
258 258

	
259 259
      /// \brief This iterator goes trough the incident undirected
260 260
      /// arcs of a node.
261 261
      ///
262 262
      /// This iterator goes trough the incident edges
263 263
      /// of a certain node of a graph. You should assume that the
264 264
      /// loop arcs will be iterated twice.
265 265
      ///
266 266
      /// Its usage is quite simple, for example you can compute the
267 267
      /// degree (i.e. count the number of incident arcs of a node \c n
268 268
      /// in graph \c g of type \c Graph as follows.
269 269
      ///
270 270
      ///\code
271 271
      /// int count=0;
272 272
      /// for(Graph::IncEdgeIt e(g, n); e!=INVALID; ++e) ++count;
273 273
      ///\endcode
274 274
      class IncEdgeIt : public Edge {
275 275
      public:
276 276
        /// Default constructor
277 277

	
278 278
        /// @warning The default constructor sets the iterator
279 279
        /// to an undefined value.
280 280
        IncEdgeIt() { }
281 281
        /// Copy constructor.
282 282

	
283 283
        /// Copy constructor.
284 284
        ///
285 285
        IncEdgeIt(const IncEdgeIt& e) : Edge(e) { }
286 286
        /// Initialize the iterator to be invalid.
287 287

	
288 288
        /// Initialize the iterator to be invalid.
289 289
        ///
290 290
        IncEdgeIt(Invalid) { }
291 291
        /// This constructor sets the iterator to first incident arc.
292 292

	
293 293
        /// This constructor set the iterator to the first incident arc of
294 294
        /// the node.
295 295
        IncEdgeIt(const Graph&, const Node&) { }
296 296
        /// Edge -> IncEdgeIt conversion
297 297

	
298 298
        /// Sets the iterator to the value of the trivial iterator \c e.
299 299
        /// This feature necessitates that each time we
300 300
        /// iterate the arc-set, the iteration order is the same.
301 301
        IncEdgeIt(const Graph&, const Edge&) { }
302 302
        /// Next incident arc
303 303

	
304 304
        /// Assign the iterator to the next incident arc
305 305
        /// of the corresponding node.
306 306
        IncEdgeIt& operator++() { return *this; }
307 307
      };
308 308

	
309 309
      /// The directed arc type.
310 310

	
311 311
      /// The directed arc type. It can be converted to the
312 312
      /// edge or it should be inherited from the undirected
313
      /// arc.
314
      class Arc : public Edge {
313
      /// edge.
314
      class Arc {
315 315
      public:
316 316
        /// Default constructor
317 317

	
318 318
        /// @warning The default constructor sets the iterator
319 319
        /// to an undefined value.
320 320
        Arc() { }
321 321
        /// Copy constructor.
322 322

	
323 323
        /// Copy constructor.
324 324
        ///
325
        Arc(const Arc& e) : Edge(e) { }
325
        Arc(const Arc&) { }
326 326
        /// Initialize the iterator to be invalid.
327 327

	
328 328
        /// Initialize the iterator to be invalid.
329 329
        ///
330 330
        Arc(Invalid) { }
331 331
        /// Equality operator
332 332

	
333 333
        /// Two iterators are equal if and only if they point to the
334 334
        /// same object or both are invalid.
335 335
        bool operator==(Arc) const { return true; }
336 336
        /// Inequality operator
337 337

	
338 338
        /// \sa operator==(Arc n)
339 339
        ///
340 340
        bool operator!=(Arc) const { return true; }
341 341

	
342 342
        /// Artificial ordering operator.
343 343

	
344 344
        /// To allow the use of graph descriptors as key type in std::map or
345 345
        /// similar associative container we require this.
346 346
        ///
347 347
        /// \note This operator only have to define some strict ordering of
348 348
        /// the items; this order has nothing to do with the iteration
349 349
        /// ordering of the items.
350 350
        bool operator<(Arc) const { return false; }
351 351

	
352
        /// Converison to Edge
353
        operator Edge() const { return Edge(); }
352 354
      };
353 355
      /// This iterator goes through each directed arc.
354 356

	
355 357
      /// This iterator goes through each arc of a graph.
356 358
      /// Its usage is quite simple, for example you can count the number
357 359
      /// of arcs in a graph \c g of type \c Graph as follows:
358 360
      ///\code
359 361
      /// int count=0;
360 362
      /// for(Graph::ArcIt e(g); e!=INVALID; ++e) ++count;
361 363
      ///\endcode
362 364
      class ArcIt : public Arc {
363 365
      public:
364 366
        /// Default constructor
365 367

	
366 368
        /// @warning The default constructor sets the iterator
367 369
        /// to an undefined value.
368 370
        ArcIt() { }
369 371
        /// Copy constructor.
370 372

	
371 373
        /// Copy constructor.
372 374
        ///
373 375
        ArcIt(const ArcIt& e) : Arc(e) { }
374 376
        /// Initialize the iterator to be invalid.
375 377

	
376 378
        /// Initialize the iterator to be invalid.
377 379
        ///
378 380
        ArcIt(Invalid) { }
379 381
        /// This constructor sets the iterator to the first arc.
380 382

	
381 383
        /// This constructor sets the iterator to the first arc of \c g.
382 384
        ///@param g the graph
383 385
        ArcIt(const Graph &g) { ignore_unused_variable_warning(g); }
384 386
        /// Arc -> ArcIt conversion
385 387

	
386 388
        /// Sets the iterator to the value of the trivial iterator \c e.
387 389
        /// This feature necessitates that each time we
388 390
        /// iterate the arc-set, the iteration order is the same.
389 391
        ArcIt(const Graph&, const Arc&) { }
390 392
        ///Next arc
391 393

	
392 394
        /// Assign the iterator to the next arc.
393 395
        ArcIt& operator++() { return *this; }
394 396
      };
395 397

	
396 398
      /// This iterator goes trough the outgoing directed arcs of a node.
397 399

	
398 400
      /// This iterator goes trough the \e outgoing arcs of a certain node
399 401
      /// of a graph.
400 402
      /// Its usage is quite simple, for example you can count the number
401 403
      /// of outgoing arcs of a node \c n
402 404
      /// in graph \c g of type \c Graph as follows.
403 405
      ///\code
404 406
      /// int count=0;
405 407
      /// for (Graph::OutArcIt e(g, n); e!=INVALID; ++e) ++count;
406 408
      ///\endcode
407 409

	
408 410
      class OutArcIt : public Arc {
409 411
      public:
410 412
        /// Default constructor
411 413

	
412 414
        /// @warning The default constructor sets the iterator
413 415
        /// to an undefined value.
414 416
        OutArcIt() { }
415 417
        /// Copy constructor.
416 418

	
417 419
        /// Copy constructor.
418 420
        ///
419 421
        OutArcIt(const OutArcIt& e) : Arc(e) { }
420 422
        /// Initialize the iterator to be invalid.
421 423

	
422 424
        /// Initialize the iterator to be invalid.
423 425
        ///
424 426
        OutArcIt(Invalid) { }
425 427
        /// This constructor sets the iterator to the first outgoing arc.
426 428

	
427 429
        /// This constructor sets the iterator to the first outgoing arc of
428 430
        /// the node.
429 431
        ///@param n the node
430 432
        ///@param g the graph
431 433
        OutArcIt(const Graph& n, const Node& g) {
432 434
          ignore_unused_variable_warning(n);
433 435
          ignore_unused_variable_warning(g);
434 436
        }
435 437
        /// Arc -> OutArcIt conversion
436 438

	
437 439
        /// Sets the iterator to the value of the trivial iterator.
438 440
        /// This feature necessitates that each time we
439 441
        /// iterate the arc-set, the iteration order is the same.
440 442
        OutArcIt(const Graph&, const Arc&) { }
441 443
        ///Next outgoing arc
442 444

	
443 445
        /// Assign the iterator to the next
444 446
        /// outgoing arc of the corresponding node.
445 447
        OutArcIt& operator++() { return *this; }
446 448
      };
447 449

	
448 450
      /// This iterator goes trough the incoming directed arcs of a node.
449 451

	
450 452
      /// This iterator goes trough the \e incoming arcs of a certain node
451 453
      /// of a graph.
452 454
      /// Its usage is quite simple, for example you can count the number
453 455
      /// of outgoing arcs of a node \c n
454 456
      /// in graph \c g of type \c Graph as follows.
455 457
      ///\code
456 458
      /// int count=0;
457 459
      /// for(Graph::InArcIt e(g, n); e!=INVALID; ++e) ++count;
458 460
      ///\endcode
459 461

	
460 462
      class InArcIt : public Arc {
461 463
      public:
462 464
        /// Default constructor
463 465

	
464 466
        /// @warning The default constructor sets the iterator
465 467
        /// to an undefined value.
466 468
        InArcIt() { }
467 469
        /// Copy constructor.
468 470

	
469 471
        /// Copy constructor.
470 472
        ///
471 473
        InArcIt(const InArcIt& e) : Arc(e) { }
472 474
        /// Initialize the iterator to be invalid.
473 475

	
474 476
        /// Initialize the iterator to be invalid.
475 477
        ///
476 478
        InArcIt(Invalid) { }
477 479
        /// This constructor sets the iterator to first incoming arc.
478 480

	
479 481
        /// This constructor set the iterator to the first incoming arc of
480 482
        /// the node.
481 483
        ///@param n the node
482 484
        ///@param g the graph
483 485
        InArcIt(const Graph& g, const Node& n) {
484 486
          ignore_unused_variable_warning(n);
485 487
          ignore_unused_variable_warning(g);
486 488
        }
487 489
        /// Arc -> InArcIt conversion
488 490

	
489 491
        /// Sets the iterator to the value of the trivial iterator \c e.
490 492
        /// This feature necessitates that each time we
491 493
        /// iterate the arc-set, the iteration order is the same.
492 494
        InArcIt(const Graph&, const Arc&) { }
493 495
        /// Next incoming arc
494 496

	
495 497
        /// Assign the iterator to the next inarc of the corresponding node.
496 498
        ///
497 499
        InArcIt& operator++() { return *this; }
498 500
      };
499 501

	
500 502
      /// \brief Reference map of the nodes to type \c T.
501 503
      ///
502 504
      /// Reference map of the nodes to type \c T.
503 505
      template<class T>
504 506
      class NodeMap : public ReferenceMap<Node, T, T&, const T&>
505 507
      {
506 508
      public:
507 509

	
508 510
        ///\e
509 511
        NodeMap(const Graph&) { }
510 512
        ///\e
511 513
        NodeMap(const Graph&, T) { }
512 514

	
513 515
      private:
514 516
        ///Copy constructor
515 517
        NodeMap(const NodeMap& nm) :
516 518
          ReferenceMap<Node, T, T&, const T&>(nm) { }
517 519
        ///Assignment operator
518 520
        template <typename CMap>
519 521
        NodeMap& operator=(const CMap&) {
520 522
          checkConcept<ReadMap<Node, T>, CMap>();
521 523
          return *this;
522 524
        }
523 525
      };
524 526

	
525 527
      /// \brief Reference map of the arcs to type \c T.
526 528
      ///
527 529
      /// Reference map of the arcs to type \c T.
528 530
      template<class T>
529 531
      class ArcMap : public ReferenceMap<Arc, T, T&, const T&>
530 532
      {
531 533
      public:
532 534

	
533 535
        ///\e
534 536
        ArcMap(const Graph&) { }
535 537
        ///\e
536 538
        ArcMap(const Graph&, T) { }
537 539
      private:
538 540
        ///Copy constructor
539 541
        ArcMap(const ArcMap& em) :
540 542
          ReferenceMap<Arc, T, T&, const T&>(em) { }
541 543
        ///Assignment operator
542 544
        template <typename CMap>
543 545
        ArcMap& operator=(const CMap&) {
544 546
          checkConcept<ReadMap<Arc, T>, CMap>();
545 547
          return *this;
546 548
        }
547 549
      };
548 550

	
549 551
      /// Reference map of the edges to type \c T.
550 552

	
551 553
      /// Reference map of the edges to type \c T.
552 554
      template<class T>
553 555
      class EdgeMap : public ReferenceMap<Edge, T, T&, const T&>
554 556
      {
555 557
      public:
556 558

	
557 559
        ///\e
558 560
        EdgeMap(const Graph&) { }
559 561
        ///\e
560 562
        EdgeMap(const Graph&, T) { }
561 563
      private:
562 564
        ///Copy constructor
563 565
        EdgeMap(const EdgeMap& em) :
564 566
          ReferenceMap<Edge, T, T&, const T&>(em) {}
565 567
        ///Assignment operator
566 568
        template <typename CMap>
567 569
        EdgeMap& operator=(const CMap&) {
568 570
          checkConcept<ReadMap<Edge, T>, CMap>();
569 571
          return *this;
570 572
        }
571 573
      };
572 574

	
573 575
      /// \brief Direct the given edge.
574 576
      ///
575 577
      /// Direct the given edge. The returned arc source
576 578
      /// will be the given node.
577 579
      Arc direct(const Edge&, const Node&) const {
578 580
        return INVALID;
579 581
      }
580 582

	
581 583
      /// \brief Direct the given edge.
582 584
      ///
583 585
      /// Direct the given edge. The returned arc
584 586
      /// represents the given edge and the direction comes
585 587
      /// from the bool parameter. The source of the edge and
586 588
      /// the directed arc is the same when the given bool is true.
587 589
      Arc direct(const Edge&, bool) const {
588 590
        return INVALID;
589 591
      }
590 592

	
591 593
      /// \brief Returns true if the arc has default orientation.
592 594
      ///
593 595
      /// Returns whether the given directed arc is same orientation as
594 596
      /// the corresponding edge's default orientation.
595 597
      bool direction(Arc) const { return true; }
596 598

	
597 599
      /// \brief Returns the opposite directed arc.
598 600
      ///
599 601
      /// Returns the opposite directed arc.
600 602
      Arc oppositeArc(Arc) const { return INVALID; }
601 603

	
602 604
      /// \brief Opposite node on an arc
603 605
      ///
604 606
      /// \return The opposite of the given node on the given edge.
605 607
      Node oppositeNode(Node, Edge) const { return INVALID; }
606 608

	
607 609
      /// \brief First node of the edge.
608 610
      ///
609 611
      /// \return The first node of the given edge.
610 612
      ///
611 613
      /// Naturally edges don't have direction and thus
612 614
      /// don't have source and target node. However we use \c u() and \c v()
613 615
      /// methods to query the two nodes of the arc. The direction of the
614 616
      /// arc which arises this way is called the inherent direction of the
615 617
      /// edge, and is used to define the "default" direction
616 618
      /// of the directed versions of the arcs.
617 619
      /// \sa v()
618 620
      /// \sa direction()
619 621
      Node u(Edge) const { return INVALID; }
620 622

	
621 623
      /// \brief Second node of the edge.
622 624
      ///
623 625
      /// \return The second node of the given edge.
624 626
      ///
625 627
      /// Naturally edges don't have direction and thus
626 628
      /// don't have source and target node. However we use \c u() and \c v()
627 629
      /// methods to query the two nodes of the arc. The direction of the
628 630
      /// arc which arises this way is called the inherent direction of the
629 631
      /// edge, and is used to define the "default" direction
630 632
      /// of the directed versions of the arcs.
631 633
      /// \sa u()
632 634
      /// \sa direction()
633 635
      Node v(Edge) const { return INVALID; }
634 636

	
635 637
      /// \brief Source node of the directed arc.
636 638
      Node source(Arc) const { return INVALID; }
637 639

	
638 640
      /// \brief Target node of the directed arc.
639 641
      Node target(Arc) const { return INVALID; }
640 642

	
641 643
      /// \brief Returns the id of the node.
642 644
      int id(Node) const { return -1; }
643 645

	
644 646
      /// \brief Returns the id of the edge.
645 647
      int id(Edge) const { return -1; }
646 648

	
647 649
      /// \brief Returns the id of the arc.
648 650
      int id(Arc) const { return -1; }
649 651

	
650 652
      /// \brief Returns the node with the given id.
651 653
      ///
652 654
      /// \pre The argument should be a valid node id in the graph.
653 655
      Node nodeFromId(int) const { return INVALID; }
654 656

	
655 657
      /// \brief Returns the edge with the given id.
656 658
      ///
657 659
      /// \pre The argument should be a valid edge id in the graph.
658 660
      Edge edgeFromId(int) const { return INVALID; }
659 661

	
660 662
      /// \brief Returns the arc with the given id.
661 663
      ///
662 664
      /// \pre The argument should be a valid arc id in the graph.
663 665
      Arc arcFromId(int) const { return INVALID; }
664 666

	
665 667
      /// \brief Returns an upper bound on the node IDs.
666 668
      int maxNodeId() const { return -1; }
667 669

	
668 670
      /// \brief Returns an upper bound on the edge IDs.
669 671
      int maxEdgeId() const { return -1; }
670 672

	
671 673
      /// \brief Returns an upper bound on the arc IDs.
672 674
      int maxArcId() const { return -1; }
673 675

	
674 676
      void first(Node&) const {}
675 677
      void next(Node&) const {}
676 678

	
677 679
      void first(Edge&) const {}
678 680
      void next(Edge&) const {}
679 681

	
680 682
      void first(Arc&) const {}
681 683
      void next(Arc&) const {}
682 684

	
683 685
      void firstOut(Arc&, Node) const {}
684 686
      void nextOut(Arc&) const {}
685 687

	
686 688
      void firstIn(Arc&, Node) const {}
687 689
      void nextIn(Arc&) const {}
688 690

	
689 691
      void firstInc(Edge &, bool &, const Node &) const {}
690 692
      void nextInc(Edge &, bool &) const {}
691 693

	
692 694
      // The second parameter is dummy.
693 695
      Node fromId(int, Node) const { return INVALID; }
694 696
      // The second parameter is dummy.
695 697
      Edge fromId(int, Edge) const { return INVALID; }
696 698
      // The second parameter is dummy.
697 699
      Arc fromId(int, Arc) const { return INVALID; }
698 700

	
699 701
      // Dummy parameter.
700 702
      int maxId(Node) const { return -1; }
701 703
      // Dummy parameter.
702 704
      int maxId(Edge) const { return -1; }
703 705
      // Dummy parameter.
704 706
      int maxId(Arc) const { return -1; }
705 707

	
706 708
      /// \brief Base node of the iterator
707 709
      ///
708 710
      /// Returns the base node (the source in this case) of the iterator
709 711
      Node baseNode(OutArcIt e) const {
710 712
        return source(e);
711 713
      }
712 714
      /// \brief Running node of the iterator
713 715
      ///
714 716
      /// Returns the running node (the target in this case) of the
715 717
      /// iterator
716 718
      Node runningNode(OutArcIt e) const {
717 719
        return target(e);
718 720
      }
719 721

	
720 722
      /// \brief Base node of the iterator
721 723
      ///
722 724
      /// Returns the base node (the target in this case) of the iterator
723 725
      Node baseNode(InArcIt e) const {
724 726
        return target(e);
725 727
      }
726 728
      /// \brief Running node of the iterator
727 729
      ///
728 730
      /// Returns the running node (the source in this case) of the
729 731
      /// iterator
730 732
      Node runningNode(InArcIt e) const {
731 733
        return source(e);
732 734
      }
733 735

	
734 736
      /// \brief Base node of the iterator
735 737
      ///
736 738
      /// Returns the base node of the iterator
737 739
      Node baseNode(IncEdgeIt) const {
738 740
        return INVALID;
739 741
      }
740 742

	
741 743
      /// \brief Running node of the iterator
742 744
      ///
743 745
      /// Returns the running node of the iterator
744 746
      Node runningNode(IncEdgeIt) const {
745 747
        return INVALID;
746 748
      }
747 749

	
748 750
      template <typename _Graph>
749 751
      struct Constraints {
750 752
        void constraints() {
751 753
          checkConcept<BaseGraphComponent, _Graph>();
752 754
          checkConcept<IterableGraphComponent<>, _Graph>();
753 755
          checkConcept<IDableGraphComponent<>, _Graph>();
754 756
          checkConcept<MappableGraphComponent<>, _Graph>();
755 757
        }
756 758
      };
757 759

	
758 760
    };
759 761

	
760 762
  }
761 763

	
762 764
}
763 765

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

	
19 19
#ifndef LEMON_CONNECTIVITY_H
20 20
#define LEMON_CONNECTIVITY_H
21 21

	
22 22
#include <lemon/dfs.h>
23 23
#include <lemon/bfs.h>
24 24
#include <lemon/core.h>
25 25
#include <lemon/maps.h>
26 26
#include <lemon/adaptors.h>
27 27

	
28 28
#include <lemon/concepts/digraph.h>
29 29
#include <lemon/concepts/graph.h>
30 30
#include <lemon/concept_check.h>
31 31

	
32 32
#include <stack>
33 33
#include <functional>
34 34

	
35 35
/// \ingroup graph_properties
36 36
/// \file
37 37
/// \brief Connectivity algorithms
38 38
///
39 39
/// Connectivity algorithms
40 40

	
41 41
namespace lemon {
42 42

	
43 43
  /// \ingroup graph_properties
44 44
  ///
45
  /// \brief Check whether the given undirected graph is connected.
45
  /// \brief Check whether an undirected graph is connected.
46 46
  ///
47
  /// Check whether the given undirected graph is connected.
48
  /// \param graph The undirected graph.
49
  /// \return \c true when there is path between any two nodes in the graph.
47
  /// This function checks whether the given undirected graph is connected,
48
  /// i.e. there is a path between any two nodes in the graph.
49
  ///
50
  /// \return \c true if the graph is connected.
50 51
  /// \note By definition, the empty graph is connected.
52
  ///
53
  /// \see countConnectedComponents(), connectedComponents()
54
  /// \see stronglyConnected()
51 55
  template <typename Graph>
52 56
  bool connected(const Graph& graph) {
53 57
    checkConcept<concepts::Graph, Graph>();
54 58
    typedef typename Graph::NodeIt NodeIt;
55 59
    if (NodeIt(graph) == INVALID) return true;
56 60
    Dfs<Graph> dfs(graph);
57 61
    dfs.run(NodeIt(graph));
58 62
    for (NodeIt it(graph); it != INVALID; ++it) {
59 63
      if (!dfs.reached(it)) {
60 64
        return false;
61 65
      }
62 66
    }
63 67
    return true;
64 68
  }
65 69

	
66 70
  /// \ingroup graph_properties
67 71
  ///
68 72
  /// \brief Count the number of connected components of an undirected graph
69 73
  ///
70
  /// Count the number of connected components of an undirected graph
74
  /// This function counts the number of connected components of the given
75
  /// undirected graph.
71 76
  ///
72
  /// \param graph The graph. It must be undirected.
73
  /// \return The number of components
77
  /// The connected components are the classes of an equivalence relation
78
  /// on the nodes of an undirected graph. Two nodes are in the same class
79
  /// if they are connected with a path.
80
  ///
81
  /// \return The number of connected components.
74 82
  /// \note By definition, the empty graph consists
75 83
  /// of zero connected components.
84
  ///
85
  /// \see connected(), connectedComponents()
76 86
  template <typename Graph>
77 87
  int countConnectedComponents(const Graph &graph) {
78 88
    checkConcept<concepts::Graph, Graph>();
79 89
    typedef typename Graph::Node Node;
80 90
    typedef typename Graph::Arc Arc;
81 91

	
82 92
    typedef NullMap<Node, Arc> PredMap;
83 93
    typedef NullMap<Node, int> DistMap;
84 94

	
85 95
    int compNum = 0;
86 96
    typename Bfs<Graph>::
87 97
      template SetPredMap<PredMap>::
88 98
      template SetDistMap<DistMap>::
89 99
      Create bfs(graph);
90 100

	
91 101
    PredMap predMap;
92 102
    bfs.predMap(predMap);
93 103

	
94 104
    DistMap distMap;
95 105
    bfs.distMap(distMap);
96 106

	
97 107
    bfs.init();
98 108
    for(typename Graph::NodeIt n(graph); n != INVALID; ++n) {
99 109
      if (!bfs.reached(n)) {
100 110
        bfs.addSource(n);
101 111
        bfs.start();
102 112
        ++compNum;
103 113
      }
104 114
    }
105 115
    return compNum;
106 116
  }
107 117

	
108 118
  /// \ingroup graph_properties
109 119
  ///
110 120
  /// \brief Find the connected components of an undirected graph
111 121
  ///
112
  /// Find the connected components of an undirected graph.
122
  /// This function finds the connected components of the given undirected
123
  /// graph.
124
  ///
125
  /// The connected components are the classes of an equivalence relation
126
  /// on the nodes of an undirected graph. Two nodes are in the same class
127
  /// if they are connected with a path.
113 128
  ///
114 129
  /// \image html connected_components.png
115 130
  /// \image latex connected_components.eps "Connected components" width=\textwidth
116 131
  ///
117
  /// \param graph The graph. It must be undirected.
132
  /// \param graph The undirected graph.
118 133
  /// \retval compMap A writable node map. The values will be set from 0 to
119
  /// the number of the connected components minus one. Each values of the map
120
  /// will be set exactly once, the values of a certain component will be
134
  /// the number of the connected components minus one. Each value of the map
135
  /// will be set exactly once, and the values of a certain component will be
121 136
  /// set continuously.
122
  /// \return The number of components
137
  /// \return The number of connected components.
138
  /// \note By definition, the empty graph consists
139
  /// of zero connected components.
140
  ///
141
  /// \see connected(), countConnectedComponents()
123 142
  template <class Graph, class NodeMap>
124 143
  int connectedComponents(const Graph &graph, NodeMap &compMap) {
125 144
    checkConcept<concepts::Graph, Graph>();
126 145
    typedef typename Graph::Node Node;
127 146
    typedef typename Graph::Arc Arc;
128 147
    checkConcept<concepts::WriteMap<Node, int>, NodeMap>();
129 148

	
130 149
    typedef NullMap<Node, Arc> PredMap;
131 150
    typedef NullMap<Node, int> DistMap;
132 151

	
133 152
    int compNum = 0;
134 153
    typename Bfs<Graph>::
135 154
      template SetPredMap<PredMap>::
136 155
      template SetDistMap<DistMap>::
137 156
      Create bfs(graph);
138 157

	
139 158
    PredMap predMap;
140 159
    bfs.predMap(predMap);
141 160

	
142 161
    DistMap distMap;
143 162
    bfs.distMap(distMap);
144 163

	
145 164
    bfs.init();
146 165
    for(typename Graph::NodeIt n(graph); n != INVALID; ++n) {
147 166
      if(!bfs.reached(n)) {
148 167
        bfs.addSource(n);
149 168
        while (!bfs.emptyQueue()) {
150 169
          compMap.set(bfs.nextNode(), compNum);
151 170
          bfs.processNextNode();
152 171
        }
153 172
        ++compNum;
154 173
      }
155 174
    }
156 175
    return compNum;
157 176
  }
158 177

	
159 178
  namespace _connectivity_bits {
160 179

	
161 180
    template <typename Digraph, typename Iterator >
162 181
    struct LeaveOrderVisitor : public DfsVisitor<Digraph> {
163 182
    public:
164 183
      typedef typename Digraph::Node Node;
165 184
      LeaveOrderVisitor(Iterator it) : _it(it) {}
166 185

	
167 186
      void leave(const Node& node) {
168 187
        *(_it++) = node;
169 188
      }
170 189

	
171 190
    private:
172 191
      Iterator _it;
173 192
    };
174 193

	
175 194
    template <typename Digraph, typename Map>
176 195
    struct FillMapVisitor : public DfsVisitor<Digraph> {
177 196
    public:
178 197
      typedef typename Digraph::Node Node;
179 198
      typedef typename Map::Value Value;
180 199

	
181 200
      FillMapVisitor(Map& map, Value& value)
182 201
        : _map(map), _value(value) {}
183 202

	
184 203
      void reach(const Node& node) {
185 204
        _map.set(node, _value);
186 205
      }
187 206
    private:
188 207
      Map& _map;
189 208
      Value& _value;
190 209
    };
191 210

	
192 211
    template <typename Digraph, typename ArcMap>
193 212
    struct StronglyConnectedCutArcsVisitor : public DfsVisitor<Digraph> {
194 213
    public:
195 214
      typedef typename Digraph::Node Node;
196 215
      typedef typename Digraph::Arc Arc;
197 216

	
198 217
      StronglyConnectedCutArcsVisitor(const Digraph& digraph,
199 218
                                      ArcMap& cutMap,
200 219
                                      int& cutNum)
201 220
        : _digraph(digraph), _cutMap(cutMap), _cutNum(cutNum),
202 221
          _compMap(digraph, -1), _num(-1) {
203 222
      }
204 223

	
205 224
      void start(const Node&) {
206 225
        ++_num;
207 226
      }
208 227

	
209 228
      void reach(const Node& node) {
210 229
        _compMap.set(node, _num);
211 230
      }
212 231

	
213 232
      void examine(const Arc& arc) {
214 233
         if (_compMap[_digraph.source(arc)] !=
215 234
             _compMap[_digraph.target(arc)]) {
216 235
           _cutMap.set(arc, true);
217 236
           ++_cutNum;
218 237
         }
219 238
      }
220 239
    private:
221 240
      const Digraph& _digraph;
222 241
      ArcMap& _cutMap;
223 242
      int& _cutNum;
224 243

	
225 244
      typename Digraph::template NodeMap<int> _compMap;
226 245
      int _num;
227 246
    };
228 247

	
229 248
  }
230 249

	
231 250

	
232 251
  /// \ingroup graph_properties
233 252
  ///
234
  /// \brief Check whether the given directed graph is strongly connected.
253
  /// \brief Check whether a directed graph is strongly connected.
235 254
  ///
236
  /// Check whether the given directed graph is strongly connected. The
237
  /// graph is strongly connected when any two nodes of the graph are
255
  /// This function checks whether the given directed graph is strongly
256
  /// connected, i.e. any two nodes of the digraph are
238 257
  /// connected with directed paths in both direction.
239
  /// \return \c false when the graph is not strongly connected.
240
  /// \see connected
241 258
  ///
242
  /// \note By definition, the empty graph is strongly connected.
259
  /// \return \c true if the digraph is strongly connected.
260
  /// \note By definition, the empty digraph is strongly connected.
261
  /// 
262
  /// \see countStronglyConnectedComponents(), stronglyConnectedComponents()
263
  /// \see connected()
243 264
  template <typename Digraph>
244 265
  bool stronglyConnected(const Digraph& digraph) {
245 266
    checkConcept<concepts::Digraph, Digraph>();
246 267

	
247 268
    typedef typename Digraph::Node Node;
248 269
    typedef typename Digraph::NodeIt NodeIt;
249 270

	
250 271
    typename Digraph::Node source = NodeIt(digraph);
251 272
    if (source == INVALID) return true;
252 273

	
253 274
    using namespace _connectivity_bits;
254 275

	
255 276
    typedef DfsVisitor<Digraph> Visitor;
256 277
    Visitor visitor;
257 278

	
258 279
    DfsVisit<Digraph, Visitor> dfs(digraph, visitor);
259 280
    dfs.init();
260 281
    dfs.addSource(source);
261 282
    dfs.start();
262 283

	
263 284
    for (NodeIt it(digraph); it != INVALID; ++it) {
264 285
      if (!dfs.reached(it)) {
265 286
        return false;
266 287
      }
267 288
    }
268 289

	
269 290
    typedef ReverseDigraph<const Digraph> RDigraph;
270 291
    typedef typename RDigraph::NodeIt RNodeIt;
271 292
    RDigraph rdigraph(digraph);
272 293

	
273
    typedef DfsVisitor<Digraph> RVisitor;
294
    typedef DfsVisitor<RDigraph> RVisitor;
274 295
    RVisitor rvisitor;
275 296

	
276 297
    DfsVisit<RDigraph, RVisitor> rdfs(rdigraph, rvisitor);
277 298
    rdfs.init();
278 299
    rdfs.addSource(source);
279 300
    rdfs.start();
280 301

	
281 302
    for (RNodeIt it(rdigraph); it != INVALID; ++it) {
282 303
      if (!rdfs.reached(it)) {
283 304
        return false;
284 305
      }
285 306
    }
286 307

	
287 308
    return true;
288 309
  }
289 310

	
290 311
  /// \ingroup graph_properties
291 312
  ///
292
  /// \brief Count the strongly connected components of a directed graph
313
  /// \brief Count the number of strongly connected components of a 
314
  /// directed graph
293 315
  ///
294
  /// Count the strongly connected components of a directed graph.
316
  /// This function counts the number of strongly connected components of
317
  /// the given directed graph.
318
  ///
295 319
  /// The strongly connected components are the classes of an
296
  /// equivalence relation on the nodes of the graph. Two nodes are in
320
  /// equivalence relation on the nodes of a digraph. Two nodes are in
297 321
  /// the same class if they are connected with directed paths in both
298 322
  /// direction.
299 323
  ///
300
  /// \param digraph The graph.
301
  /// \return The number of components
302
  /// \note By definition, the empty graph has zero
324
  /// \return The number of strongly connected components.
325
  /// \note By definition, the empty digraph has zero
303 326
  /// strongly connected components.
327
  ///
328
  /// \see stronglyConnected(), stronglyConnectedComponents()
304 329
  template <typename Digraph>
305 330
  int countStronglyConnectedComponents(const Digraph& digraph) {
306 331
    checkConcept<concepts::Digraph, Digraph>();
307 332

	
308 333
    using namespace _connectivity_bits;
309 334

	
310 335
    typedef typename Digraph::Node Node;
311 336
    typedef typename Digraph::Arc Arc;
312 337
    typedef typename Digraph::NodeIt NodeIt;
313 338
    typedef typename Digraph::ArcIt ArcIt;
314 339

	
315 340
    typedef std::vector<Node> Container;
316 341
    typedef typename Container::iterator Iterator;
317 342

	
318 343
    Container nodes(countNodes(digraph));
319 344
    typedef LeaveOrderVisitor<Digraph, Iterator> Visitor;
320 345
    Visitor visitor(nodes.begin());
321 346

	
322 347
    DfsVisit<Digraph, Visitor> dfs(digraph, visitor);
323 348
    dfs.init();
324 349
    for (NodeIt it(digraph); it != INVALID; ++it) {
325 350
      if (!dfs.reached(it)) {
326 351
        dfs.addSource(it);
327 352
        dfs.start();
328 353
      }
329 354
    }
330 355

	
331 356
    typedef typename Container::reverse_iterator RIterator;
332 357
    typedef ReverseDigraph<const Digraph> RDigraph;
333 358

	
334 359
    RDigraph rdigraph(digraph);
335 360

	
336 361
    typedef DfsVisitor<Digraph> RVisitor;
337 362
    RVisitor rvisitor;
338 363

	
339 364
    DfsVisit<RDigraph, RVisitor> rdfs(rdigraph, rvisitor);
340 365

	
341 366
    int compNum = 0;
342 367

	
343 368
    rdfs.init();
344 369
    for (RIterator it = nodes.rbegin(); it != nodes.rend(); ++it) {
345 370
      if (!rdfs.reached(*it)) {
346 371
        rdfs.addSource(*it);
347 372
        rdfs.start();
348 373
        ++compNum;
349 374
      }
350 375
    }
351 376
    return compNum;
352 377
  }
353 378

	
354 379
  /// \ingroup graph_properties
355 380
  ///
356 381
  /// \brief Find the strongly connected components of a directed graph
357 382
  ///
358
  /// Find the strongly connected components of a directed graph.  The
359
  /// strongly connected components are the classes of an equivalence
360
  /// relation on the nodes of the graph. Two nodes are in
361
  /// relationship when there are directed paths between them in both
362
  /// direction. In addition, the numbering of components will satisfy
363
  /// that there is no arc going from a higher numbered component to
364
  /// a lower.
383
  /// This function finds the strongly connected components of the given
384
  /// directed graph. In addition, the numbering of the components will
385
  /// satisfy that there is no arc going from a higher numbered component
386
  /// to a lower one (i.e. it provides a topological order of the components).
387
  ///
388
  /// The strongly connected components are the classes of an
389
  /// equivalence relation on the nodes of a digraph. Two nodes are in
390
  /// the same class if they are connected with directed paths in both
391
  /// direction.
365 392
  ///
366 393
  /// \image html strongly_connected_components.png
367 394
  /// \image latex strongly_connected_components.eps "Strongly connected components" width=\textwidth
368 395
  ///
369 396
  /// \param digraph The digraph.
370 397
  /// \retval compMap A writable node map. The values will be set from 0 to
371 398
  /// the number of the strongly connected components minus one. Each value
372
  /// of the map will be set exactly once, the values of a certain component
373
  /// will be set continuously.
374
  /// \return The number of components
399
  /// of the map will be set exactly once, and the values of a certain
400
  /// component will be set continuously.
401
  /// \return The number of strongly connected components.
402
  /// \note By definition, the empty digraph has zero
403
  /// strongly connected components.
404
  ///
405
  /// \see stronglyConnected(), countStronglyConnectedComponents()
375 406
  template <typename Digraph, typename NodeMap>
376 407
  int stronglyConnectedComponents(const Digraph& digraph, NodeMap& compMap) {
377 408
    checkConcept<concepts::Digraph, Digraph>();
378 409
    typedef typename Digraph::Node Node;
379 410
    typedef typename Digraph::NodeIt NodeIt;
380 411
    checkConcept<concepts::WriteMap<Node, int>, NodeMap>();
381 412

	
382 413
    using namespace _connectivity_bits;
383 414

	
384 415
    typedef std::vector<Node> Container;
385 416
    typedef typename Container::iterator Iterator;
386 417

	
387 418
    Container nodes(countNodes(digraph));
388 419
    typedef LeaveOrderVisitor<Digraph, Iterator> Visitor;
389 420
    Visitor visitor(nodes.begin());
390 421

	
391 422
    DfsVisit<Digraph, Visitor> dfs(digraph, visitor);
392 423
    dfs.init();
393 424
    for (NodeIt it(digraph); it != INVALID; ++it) {
394 425
      if (!dfs.reached(it)) {
395 426
        dfs.addSource(it);
396 427
        dfs.start();
397 428
      }
398 429
    }
399 430

	
400 431
    typedef typename Container::reverse_iterator RIterator;
401 432
    typedef ReverseDigraph<const Digraph> RDigraph;
402 433

	
403 434
    RDigraph rdigraph(digraph);
404 435

	
405 436
    int compNum = 0;
406 437

	
407 438
    typedef FillMapVisitor<RDigraph, NodeMap> RVisitor;
408 439
    RVisitor rvisitor(compMap, compNum);
409 440

	
410 441
    DfsVisit<RDigraph, RVisitor> rdfs(rdigraph, rvisitor);
411 442

	
412 443
    rdfs.init();
413 444
    for (RIterator it = nodes.rbegin(); it != nodes.rend(); ++it) {
414 445
      if (!rdfs.reached(*it)) {
415 446
        rdfs.addSource(*it);
416 447
        rdfs.start();
417 448
        ++compNum;
418 449
      }
419 450
    }
420 451
    return compNum;
421 452
  }
422 453

	
423 454
  /// \ingroup graph_properties
424 455
  ///
425 456
  /// \brief Find the cut arcs of the strongly connected components.
426 457
  ///
427
  /// Find the cut arcs of the strongly connected components.
428
  /// The strongly connected components are the classes of an equivalence
429
  /// relation on the nodes of the graph. Two nodes are in relationship
430
  /// when there are directed paths between them in both direction.
458
  /// This function finds the cut arcs of the strongly connected components
459
  /// of the given digraph.
460
  ///
461
  /// The strongly connected components are the classes of an
462
  /// equivalence relation on the nodes of a digraph. Two nodes are in
463
  /// the same class if they are connected with directed paths in both
464
  /// direction.
431 465
  /// The strongly connected components are separated by the cut arcs.
432 466
  ///
433
  /// \param graph The graph.
434
  /// \retval cutMap A writable node map. The values will be set true when the
435
  /// arc is a cut arc.
467
  /// \param digraph The digraph.
468
  /// \retval cutMap A writable arc map. The values will be set to \c true
469
  /// for the cut arcs (exactly once for each cut arc), and will not be
470
  /// changed for other arcs.
471
  /// \return The number of cut arcs.
436 472
  ///
437
  /// \return The number of cut arcs
473
  /// \see stronglyConnected(), stronglyConnectedComponents()
438 474
  template <typename Digraph, typename ArcMap>
439
  int stronglyConnectedCutArcs(const Digraph& graph, ArcMap& cutMap) {
475
  int stronglyConnectedCutArcs(const Digraph& digraph, ArcMap& cutMap) {
440 476
    checkConcept<concepts::Digraph, Digraph>();
441 477
    typedef typename Digraph::Node Node;
442 478
    typedef typename Digraph::Arc Arc;
443 479
    typedef typename Digraph::NodeIt NodeIt;
444 480
    checkConcept<concepts::WriteMap<Arc, bool>, ArcMap>();
445 481

	
446 482
    using namespace _connectivity_bits;
447 483

	
448 484
    typedef std::vector<Node> Container;
449 485
    typedef typename Container::iterator Iterator;
450 486

	
451
    Container nodes(countNodes(graph));
487
    Container nodes(countNodes(digraph));
452 488
    typedef LeaveOrderVisitor<Digraph, Iterator> Visitor;
453 489
    Visitor visitor(nodes.begin());
454 490

	
455
    DfsVisit<Digraph, Visitor> dfs(graph, visitor);
491
    DfsVisit<Digraph, Visitor> dfs(digraph, visitor);
456 492
    dfs.init();
457
    for (NodeIt it(graph); it != INVALID; ++it) {
493
    for (NodeIt it(digraph); it != INVALID; ++it) {
458 494
      if (!dfs.reached(it)) {
459 495
        dfs.addSource(it);
460 496
        dfs.start();
461 497
      }
462 498
    }
463 499

	
464 500
    typedef typename Container::reverse_iterator RIterator;
465 501
    typedef ReverseDigraph<const Digraph> RDigraph;
466 502

	
467
    RDigraph rgraph(graph);
503
    RDigraph rdigraph(digraph);
468 504

	
469 505
    int cutNum = 0;
470 506

	
471 507
    typedef StronglyConnectedCutArcsVisitor<RDigraph, ArcMap> RVisitor;
472
    RVisitor rvisitor(rgraph, cutMap, cutNum);
508
    RVisitor rvisitor(rdigraph, cutMap, cutNum);
473 509

	
474
    DfsVisit<RDigraph, RVisitor> rdfs(rgraph, rvisitor);
510
    DfsVisit<RDigraph, RVisitor> rdfs(rdigraph, rvisitor);
475 511

	
476 512
    rdfs.init();
477 513
    for (RIterator it = nodes.rbegin(); it != nodes.rend(); ++it) {
478 514
      if (!rdfs.reached(*it)) {
479 515
        rdfs.addSource(*it);
480 516
        rdfs.start();
481 517
      }
482 518
    }
483 519
    return cutNum;
484 520
  }
485 521

	
486 522
  namespace _connectivity_bits {
487 523

	
488 524
    template <typename Digraph>
489 525
    class CountBiNodeConnectedComponentsVisitor : public DfsVisitor<Digraph> {
490 526
    public:
491 527
      typedef typename Digraph::Node Node;
492 528
      typedef typename Digraph::Arc Arc;
493 529
      typedef typename Digraph::Edge Edge;
494 530

	
495 531
      CountBiNodeConnectedComponentsVisitor(const Digraph& graph, int &compNum)
496 532
        : _graph(graph), _compNum(compNum),
497 533
          _numMap(graph), _retMap(graph), _predMap(graph), _num(0) {}
498 534

	
499 535
      void start(const Node& node) {
500 536
        _predMap.set(node, INVALID);
501 537
      }
502 538

	
503 539
      void reach(const Node& node) {
504 540
        _numMap.set(node, _num);
505 541
        _retMap.set(node, _num);
506 542
        ++_num;
507 543
      }
508 544

	
509 545
      void discover(const Arc& edge) {
510 546
        _predMap.set(_graph.target(edge), _graph.source(edge));
511 547
      }
512 548

	
513 549
      void examine(const Arc& edge) {
514 550
        if (_graph.source(edge) == _graph.target(edge) &&
515 551
            _graph.direction(edge)) {
516 552
          ++_compNum;
517 553
          return;
518 554
        }
519 555
        if (_predMap[_graph.source(edge)] == _graph.target(edge)) {
520 556
          return;
521 557
        }
522 558
        if (_retMap[_graph.source(edge)] > _numMap[_graph.target(edge)]) {
523 559
          _retMap.set(_graph.source(edge), _numMap[_graph.target(edge)]);
524 560
        }
525 561
      }
526 562

	
527 563
      void backtrack(const Arc& edge) {
528 564
        if (_retMap[_graph.source(edge)] > _retMap[_graph.target(edge)]) {
529 565
          _retMap.set(_graph.source(edge), _retMap[_graph.target(edge)]);
530 566
        }
531 567
        if (_numMap[_graph.source(edge)] <= _retMap[_graph.target(edge)]) {
532 568
          ++_compNum;
533 569
        }
534 570
      }
535 571

	
536 572
    private:
537 573
      const Digraph& _graph;
538 574
      int& _compNum;
539 575

	
540 576
      typename Digraph::template NodeMap<int> _numMap;
541 577
      typename Digraph::template NodeMap<int> _retMap;
542 578
      typename Digraph::template NodeMap<Node> _predMap;
543 579
      int _num;
544 580
    };
545 581

	
546 582
    template <typename Digraph, typename ArcMap>
547 583
    class BiNodeConnectedComponentsVisitor : public DfsVisitor<Digraph> {
548 584
    public:
549 585
      typedef typename Digraph::Node Node;
550 586
      typedef typename Digraph::Arc Arc;
551 587
      typedef typename Digraph::Edge Edge;
552 588

	
553 589
      BiNodeConnectedComponentsVisitor(const Digraph& graph,
554 590
                                       ArcMap& compMap, int &compNum)
555 591
        : _graph(graph), _compMap(compMap), _compNum(compNum),
556 592
          _numMap(graph), _retMap(graph), _predMap(graph), _num(0) {}
557 593

	
558 594
      void start(const Node& node) {
559 595
        _predMap.set(node, INVALID);
560 596
      }
561 597

	
562 598
      void reach(const Node& node) {
563 599
        _numMap.set(node, _num);
564 600
        _retMap.set(node, _num);
565 601
        ++_num;
566 602
      }
567 603

	
568 604
      void discover(const Arc& edge) {
569 605
        Node target = _graph.target(edge);
570 606
        _predMap.set(target, edge);
571 607
        _edgeStack.push(edge);
572 608
      }
573 609

	
574 610
      void examine(const Arc& edge) {
575 611
        Node source = _graph.source(edge);
576 612
        Node target = _graph.target(edge);
577 613
        if (source == target && _graph.direction(edge)) {
578 614
          _compMap.set(edge, _compNum);
579 615
          ++_compNum;
580 616
          return;
581 617
        }
582 618
        if (_numMap[target] < _numMap[source]) {
583 619
          if (_predMap[source] != _graph.oppositeArc(edge)) {
584 620
            _edgeStack.push(edge);
585 621
          }
586 622
        }
587 623
        if (_predMap[source] != INVALID &&
588 624
            target == _graph.source(_predMap[source])) {
589 625
          return;
590 626
        }
591 627
        if (_retMap[source] > _numMap[target]) {
592 628
          _retMap.set(source, _numMap[target]);
593 629
        }
594 630
      }
595 631

	
596 632
      void backtrack(const Arc& edge) {
597 633
        Node source = _graph.source(edge);
598 634
        Node target = _graph.target(edge);
599 635
        if (_retMap[source] > _retMap[target]) {
600 636
          _retMap.set(source, _retMap[target]);
601 637
        }
602 638
        if (_numMap[source] <= _retMap[target]) {
603 639
          while (_edgeStack.top() != edge) {
604 640
            _compMap.set(_edgeStack.top(), _compNum);
605 641
            _edgeStack.pop();
606 642
          }
607 643
          _compMap.set(edge, _compNum);
608 644
          _edgeStack.pop();
609 645
          ++_compNum;
610 646
        }
611 647
      }
612 648

	
613 649
    private:
614 650
      const Digraph& _graph;
615 651
      ArcMap& _compMap;
616 652
      int& _compNum;
617 653

	
618 654
      typename Digraph::template NodeMap<int> _numMap;
619 655
      typename Digraph::template NodeMap<int> _retMap;
620 656
      typename Digraph::template NodeMap<Arc> _predMap;
621 657
      std::stack<Edge> _edgeStack;
622 658
      int _num;
623 659
    };
624 660

	
625 661

	
626 662
    template <typename Digraph, typename NodeMap>
627 663
    class BiNodeConnectedCutNodesVisitor : public DfsVisitor<Digraph> {
628 664
    public:
629 665
      typedef typename Digraph::Node Node;
630 666
      typedef typename Digraph::Arc Arc;
631 667
      typedef typename Digraph::Edge Edge;
632 668

	
633 669
      BiNodeConnectedCutNodesVisitor(const Digraph& graph, NodeMap& cutMap,
634 670
                                     int& cutNum)
635 671
        : _graph(graph), _cutMap(cutMap), _cutNum(cutNum),
636 672
          _numMap(graph), _retMap(graph), _predMap(graph), _num(0) {}
637 673

	
638 674
      void start(const Node& node) {
639 675
        _predMap.set(node, INVALID);
640 676
        rootCut = false;
641 677
      }
642 678

	
643 679
      void reach(const Node& node) {
644 680
        _numMap.set(node, _num);
645 681
        _retMap.set(node, _num);
646 682
        ++_num;
647 683
      }
648 684

	
649 685
      void discover(const Arc& edge) {
650 686
        _predMap.set(_graph.target(edge), _graph.source(edge));
651 687
      }
652 688

	
653 689
      void examine(const Arc& edge) {
654 690
        if (_graph.source(edge) == _graph.target(edge) &&
655 691
            _graph.direction(edge)) {
656 692
          if (!_cutMap[_graph.source(edge)]) {
657 693
            _cutMap.set(_graph.source(edge), true);
658 694
            ++_cutNum;
659 695
          }
660 696
          return;
661 697
        }
662 698
        if (_predMap[_graph.source(edge)] == _graph.target(edge)) return;
663 699
        if (_retMap[_graph.source(edge)] > _numMap[_graph.target(edge)]) {
664 700
          _retMap.set(_graph.source(edge), _numMap[_graph.target(edge)]);
665 701
        }
666 702
      }
667 703

	
668 704
      void backtrack(const Arc& edge) {
669 705
        if (_retMap[_graph.source(edge)] > _retMap[_graph.target(edge)]) {
670 706
          _retMap.set(_graph.source(edge), _retMap[_graph.target(edge)]);
671 707
        }
672 708
        if (_numMap[_graph.source(edge)] <= _retMap[_graph.target(edge)]) {
673 709
          if (_predMap[_graph.source(edge)] != INVALID) {
674 710
            if (!_cutMap[_graph.source(edge)]) {
675 711
              _cutMap.set(_graph.source(edge), true);
676 712
              ++_cutNum;
677 713
            }
678 714
          } else if (rootCut) {
679 715
            if (!_cutMap[_graph.source(edge)]) {
680 716
              _cutMap.set(_graph.source(edge), true);
681 717
              ++_cutNum;
682 718
            }
683 719
          } else {
684 720
            rootCut = true;
685 721
          }
686 722
        }
687 723
      }
688 724

	
689 725
    private:
690 726
      const Digraph& _graph;
691 727
      NodeMap& _cutMap;
692 728
      int& _cutNum;
693 729

	
694 730
      typename Digraph::template NodeMap<int> _numMap;
695 731
      typename Digraph::template NodeMap<int> _retMap;
696 732
      typename Digraph::template NodeMap<Node> _predMap;
697 733
      std::stack<Edge> _edgeStack;
698 734
      int _num;
699 735
      bool rootCut;
700 736
    };
701 737

	
702 738
  }
703 739

	
704 740
  template <typename Graph>
705 741
  int countBiNodeConnectedComponents(const Graph& graph);
706 742

	
707 743
  /// \ingroup graph_properties
708 744
  ///
709
  /// \brief Checks the graph is bi-node-connected.
745
  /// \brief Check whether an undirected graph is bi-node-connected.
710 746
  ///
711
  /// This function checks that the undirected graph is bi-node-connected
712
  /// graph. The graph is bi-node-connected if any two undirected edge is
713
  /// on same circle.
747
  /// This function checks whether the given undirected graph is 
748
  /// bi-node-connected, i.e. any two edges are on same circle.
714 749
  ///
715
  /// \param graph The graph.
716
  /// \return \c true when the graph bi-node-connected.
750
  /// \return \c true if the graph bi-node-connected.
751
  /// \note By definition, the empty graph is bi-node-connected.
752
  ///
753
  /// \see countBiNodeConnectedComponents(), biNodeConnectedComponents()
717 754
  template <typename Graph>
718 755
  bool biNodeConnected(const Graph& graph) {
719 756
    return countBiNodeConnectedComponents(graph) <= 1;
720 757
  }
721 758

	
722 759
  /// \ingroup graph_properties
723 760
  ///
724
  /// \brief Count the biconnected components.
761
  /// \brief Count the number of bi-node-connected components of an 
762
  /// undirected graph.
725 763
  ///
726
  /// This function finds the bi-node-connected components in an undirected
727
  /// graph. The biconnected components are the classes of an equivalence
728
  /// relation on the undirected edges. Two undirected edge is in relationship
729
  /// when they are on same circle.
764
  /// This function counts the number of bi-node-connected components of
765
  /// the given undirected graph.
730 766
  ///
731
  /// \param graph The graph.
732
  /// \return The number of components.
767
  /// The bi-node-connected components are the classes of an equivalence
768
  /// relation on the edges of a undirected graph. Two edges are in the
769
  /// same class if they are on same circle.
770
  ///
771
  /// \return The number of bi-node-connected components.
772
  ///
773
  /// \see biNodeConnected(), biNodeConnectedComponents()
733 774
  template <typename Graph>
734 775
  int countBiNodeConnectedComponents(const Graph& graph) {
735 776
    checkConcept<concepts::Graph, Graph>();
736 777
    typedef typename Graph::NodeIt NodeIt;
737 778

	
738 779
    using namespace _connectivity_bits;
739 780

	
740 781
    typedef CountBiNodeConnectedComponentsVisitor<Graph> Visitor;
741 782

	
742 783
    int compNum = 0;
743 784
    Visitor visitor(graph, compNum);
744 785

	
745 786
    DfsVisit<Graph, Visitor> dfs(graph, visitor);
746 787
    dfs.init();
747 788

	
748 789
    for (NodeIt it(graph); it != INVALID; ++it) {
749 790
      if (!dfs.reached(it)) {
750 791
        dfs.addSource(it);
751 792
        dfs.start();
752 793
      }
753 794
    }
754 795
    return compNum;
755 796
  }
756 797

	
757 798
  /// \ingroup graph_properties
758 799
  ///
759
  /// \brief Find the bi-node-connected components.
800
  /// \brief Find the bi-node-connected components of an undirected graph.
760 801
  ///
761
  /// This function finds the bi-node-connected components in an undirected
762
  /// graph. The bi-node-connected components are the classes of an equivalence
763
  /// relation on the undirected edges. Two undirected edge are in relationship
764
  /// when they are on same circle.
802
  /// This function finds the bi-node-connected components of the given
803
  /// undirected graph.
804
  ///
805
  /// The bi-node-connected components are the classes of an equivalence
806
  /// relation on the edges of a undirected graph. Two edges are in the
807
  /// same class if they are on same circle.
765 808
  ///
766 809
  /// \image html node_biconnected_components.png
767 810
  /// \image latex node_biconnected_components.eps "bi-node-connected components" width=\textwidth
768 811
  ///
769
  /// \param graph The graph.
770
  /// \retval compMap A writable uedge map. The values will be set from 0
771
  /// to the number of the biconnected components minus one. Each values
772
  /// of the map will be set exactly once, the values of a certain component
773
  /// will be set continuously.
774
  /// \return The number of components.
812
  /// \param graph The undirected graph.
813
  /// \retval compMap A writable edge map. The values will be set from 0
814
  /// to the number of the bi-node-connected components minus one. Each
815
  /// value of the map will be set exactly once, and the values of a 
816
  /// certain component will be set continuously.
817
  /// \return The number of bi-node-connected components.
818
  ///
819
  /// \see biNodeConnected(), countBiNodeConnectedComponents()
775 820
  template <typename Graph, typename EdgeMap>
776 821
  int biNodeConnectedComponents(const Graph& graph,
777 822
                                EdgeMap& compMap) {
778 823
    checkConcept<concepts::Graph, Graph>();
779 824
    typedef typename Graph::NodeIt NodeIt;
780 825
    typedef typename Graph::Edge Edge;
781 826
    checkConcept<concepts::WriteMap<Edge, int>, EdgeMap>();
782 827

	
783 828
    using namespace _connectivity_bits;
784 829

	
785 830
    typedef BiNodeConnectedComponentsVisitor<Graph, EdgeMap> Visitor;
786 831

	
787 832
    int compNum = 0;
788 833
    Visitor visitor(graph, compMap, compNum);
789 834

	
790 835
    DfsVisit<Graph, Visitor> dfs(graph, visitor);
791 836
    dfs.init();
792 837

	
793 838
    for (NodeIt it(graph); it != INVALID; ++it) {
794 839
      if (!dfs.reached(it)) {
795 840
        dfs.addSource(it);
796 841
        dfs.start();
797 842
      }
798 843
    }
799 844
    return compNum;
800 845
  }
801 846

	
802 847
  /// \ingroup graph_properties
803 848
  ///
804
  /// \brief Find the bi-node-connected cut nodes.
849
  /// \brief Find the bi-node-connected cut nodes in an undirected graph.
805 850
  ///
806
  /// This function finds the bi-node-connected cut nodes in an undirected
807
  /// graph. The bi-node-connected components are the classes of an equivalence
808
  /// relation on the undirected edges. Two undirected edges are in
809
  /// relationship when they are on same circle. The biconnected components
810
  /// are separted by nodes which are the cut nodes of the components.
851
  /// This function finds the bi-node-connected cut nodes in the given
852
  /// undirected graph.
811 853
  ///
812
  /// \param graph The graph.
813
  /// \retval cutMap A writable edge map. The values will be set true when
814
  /// the node separate two or more components.
854
  /// The bi-node-connected components are the classes of an equivalence
855
  /// relation on the edges of a undirected graph. Two edges are in the
856
  /// same class if they are on same circle.
857
  /// The bi-node-connected components are separted by the cut nodes of
858
  /// the components.
859
  ///
860
  /// \param graph The undirected graph.
861
  /// \retval cutMap A writable node map. The values will be set to 
862
  /// \c true for the nodes that separate two or more components
863
  /// (exactly once for each cut node), and will not be changed for
864
  /// other nodes.
815 865
  /// \return The number of the cut nodes.
866
  ///
867
  /// \see biNodeConnected(), biNodeConnectedComponents()
816 868
  template <typename Graph, typename NodeMap>
817 869
  int biNodeConnectedCutNodes(const Graph& graph, NodeMap& cutMap) {
818 870
    checkConcept<concepts::Graph, Graph>();
819 871
    typedef typename Graph::Node Node;
820 872
    typedef typename Graph::NodeIt NodeIt;
821 873
    checkConcept<concepts::WriteMap<Node, bool>, NodeMap>();
822 874

	
823 875
    using namespace _connectivity_bits;
824 876

	
825 877
    typedef BiNodeConnectedCutNodesVisitor<Graph, NodeMap> Visitor;
826 878

	
827 879
    int cutNum = 0;
828 880
    Visitor visitor(graph, cutMap, cutNum);
829 881

	
830 882
    DfsVisit<Graph, Visitor> dfs(graph, visitor);
831 883
    dfs.init();
832 884

	
833 885
    for (NodeIt it(graph); it != INVALID; ++it) {
834 886
      if (!dfs.reached(it)) {
835 887
        dfs.addSource(it);
836 888
        dfs.start();
837 889
      }
838 890
    }
839 891
    return cutNum;
840 892
  }
841 893

	
842 894
  namespace _connectivity_bits {
843 895

	
844 896
    template <typename Digraph>
845 897
    class CountBiEdgeConnectedComponentsVisitor : public DfsVisitor<Digraph> {
846 898
    public:
847 899
      typedef typename Digraph::Node Node;
848 900
      typedef typename Digraph::Arc Arc;
849 901
      typedef typename Digraph::Edge Edge;
850 902

	
851 903
      CountBiEdgeConnectedComponentsVisitor(const Digraph& graph, int &compNum)
852 904
        : _graph(graph), _compNum(compNum),
853 905
          _numMap(graph), _retMap(graph), _predMap(graph), _num(0) {}
854 906

	
855 907
      void start(const Node& node) {
856 908
        _predMap.set(node, INVALID);
857 909
      }
858 910

	
859 911
      void reach(const Node& node) {
860 912
        _numMap.set(node, _num);
861 913
        _retMap.set(node, _num);
862 914
        ++_num;
863 915
      }
864 916

	
865 917
      void leave(const Node& node) {
866 918
        if (_numMap[node] <= _retMap[node]) {
867 919
          ++_compNum;
868 920
        }
869 921
      }
870 922

	
871 923
      void discover(const Arc& edge) {
872 924
        _predMap.set(_graph.target(edge), edge);
873 925
      }
874 926

	
875 927
      void examine(const Arc& edge) {
876 928
        if (_predMap[_graph.source(edge)] == _graph.oppositeArc(edge)) {
877 929
          return;
878 930
        }
879 931
        if (_retMap[_graph.source(edge)] > _retMap[_graph.target(edge)]) {
880 932
          _retMap.set(_graph.source(edge), _retMap[_graph.target(edge)]);
881 933
        }
882 934
      }
883 935

	
884 936
      void backtrack(const Arc& edge) {
885 937
        if (_retMap[_graph.source(edge)] > _retMap[_graph.target(edge)]) {
886 938
          _retMap.set(_graph.source(edge), _retMap[_graph.target(edge)]);
887 939
        }
888 940
      }
889 941

	
890 942
    private:
891 943
      const Digraph& _graph;
892 944
      int& _compNum;
893 945

	
894 946
      typename Digraph::template NodeMap<int> _numMap;
895 947
      typename Digraph::template NodeMap<int> _retMap;
896 948
      typename Digraph::template NodeMap<Arc> _predMap;
897 949
      int _num;
898 950
    };
899 951

	
900 952
    template <typename Digraph, typename NodeMap>
901 953
    class BiEdgeConnectedComponentsVisitor : public DfsVisitor<Digraph> {
902 954
    public:
903 955
      typedef typename Digraph::Node Node;
904 956
      typedef typename Digraph::Arc Arc;
905 957
      typedef typename Digraph::Edge Edge;
906 958

	
907 959
      BiEdgeConnectedComponentsVisitor(const Digraph& graph,
908 960
                                       NodeMap& compMap, int &compNum)
909 961
        : _graph(graph), _compMap(compMap), _compNum(compNum),
910 962
          _numMap(graph), _retMap(graph), _predMap(graph), _num(0) {}
911 963

	
912 964
      void start(const Node& node) {
913 965
        _predMap.set(node, INVALID);
914 966
      }
915 967

	
916 968
      void reach(const Node& node) {
917 969
        _numMap.set(node, _num);
918 970
        _retMap.set(node, _num);
919 971
        _nodeStack.push(node);
920 972
        ++_num;
921 973
      }
922 974

	
923 975
      void leave(const Node& node) {
924 976
        if (_numMap[node] <= _retMap[node]) {
925 977
          while (_nodeStack.top() != node) {
926 978
            _compMap.set(_nodeStack.top(), _compNum);
927 979
            _nodeStack.pop();
928 980
          }
929 981
          _compMap.set(node, _compNum);
930 982
          _nodeStack.pop();
931 983
          ++_compNum;
932 984
        }
933 985
      }
934 986

	
935 987
      void discover(const Arc& edge) {
936 988
        _predMap.set(_graph.target(edge), edge);
937 989
      }
938 990

	
939 991
      void examine(const Arc& edge) {
940 992
        if (_predMap[_graph.source(edge)] == _graph.oppositeArc(edge)) {
941 993
          return;
942 994
        }
943 995
        if (_retMap[_graph.source(edge)] > _retMap[_graph.target(edge)]) {
944 996
          _retMap.set(_graph.source(edge), _retMap[_graph.target(edge)]);
945 997
        }
946 998
      }
947 999

	
948 1000
      void backtrack(const Arc& edge) {
949 1001
        if (_retMap[_graph.source(edge)] > _retMap[_graph.target(edge)]) {
950 1002
          _retMap.set(_graph.source(edge), _retMap[_graph.target(edge)]);
951 1003
        }
952 1004
      }
953 1005

	
954 1006
    private:
955 1007
      const Digraph& _graph;
956 1008
      NodeMap& _compMap;
957 1009
      int& _compNum;
958 1010

	
959 1011
      typename Digraph::template NodeMap<int> _numMap;
960 1012
      typename Digraph::template NodeMap<int> _retMap;
961 1013
      typename Digraph::template NodeMap<Arc> _predMap;
962 1014
      std::stack<Node> _nodeStack;
963 1015
      int _num;
964 1016
    };
965 1017

	
966 1018

	
967 1019
    template <typename Digraph, typename ArcMap>
968 1020
    class BiEdgeConnectedCutEdgesVisitor : public DfsVisitor<Digraph> {
969 1021
    public:
970 1022
      typedef typename Digraph::Node Node;
971 1023
      typedef typename Digraph::Arc Arc;
972 1024
      typedef typename Digraph::Edge Edge;
973 1025

	
974 1026
      BiEdgeConnectedCutEdgesVisitor(const Digraph& graph,
975 1027
                                     ArcMap& cutMap, int &cutNum)
976 1028
        : _graph(graph), _cutMap(cutMap), _cutNum(cutNum),
977 1029
          _numMap(graph), _retMap(graph), _predMap(graph), _num(0) {}
978 1030

	
979 1031
      void start(const Node& node) {
980 1032
        _predMap[node] = INVALID;
981 1033
      }
982 1034

	
983 1035
      void reach(const Node& node) {
984 1036
        _numMap.set(node, _num);
985 1037
        _retMap.set(node, _num);
986 1038
        ++_num;
987 1039
      }
988 1040

	
989 1041
      void leave(const Node& node) {
990 1042
        if (_numMap[node] <= _retMap[node]) {
991 1043
          if (_predMap[node] != INVALID) {
992 1044
            _cutMap.set(_predMap[node], true);
993 1045
            ++_cutNum;
994 1046
          }
995 1047
        }
996 1048
      }
997 1049

	
998 1050
      void discover(const Arc& edge) {
999 1051
        _predMap.set(_graph.target(edge), edge);
1000 1052
      }
1001 1053

	
1002 1054
      void examine(const Arc& edge) {
1003 1055
        if (_predMap[_graph.source(edge)] == _graph.oppositeArc(edge)) {
1004 1056
          return;
1005 1057
        }
1006 1058
        if (_retMap[_graph.source(edge)] > _retMap[_graph.target(edge)]) {
1007 1059
          _retMap.set(_graph.source(edge), _retMap[_graph.target(edge)]);
1008 1060
        }
1009 1061
      }
1010 1062

	
1011 1063
      void backtrack(const Arc& edge) {
1012 1064
        if (_retMap[_graph.source(edge)] > _retMap[_graph.target(edge)]) {
1013 1065
          _retMap.set(_graph.source(edge), _retMap[_graph.target(edge)]);
1014 1066
        }
1015 1067
      }
1016 1068

	
1017 1069
    private:
1018 1070
      const Digraph& _graph;
1019 1071
      ArcMap& _cutMap;
1020 1072
      int& _cutNum;
1021 1073

	
1022 1074
      typename Digraph::template NodeMap<int> _numMap;
1023 1075
      typename Digraph::template NodeMap<int> _retMap;
1024 1076
      typename Digraph::template NodeMap<Arc> _predMap;
1025 1077
      int _num;
1026 1078
    };
1027 1079
  }
1028 1080

	
1029 1081
  template <typename Graph>
1030 1082
  int countBiEdgeConnectedComponents(const Graph& graph);
1031 1083

	
1032 1084
  /// \ingroup graph_properties
1033 1085
  ///
1034
  /// \brief Checks that the graph is bi-edge-connected.
1086
  /// \brief Check whether an undirected graph is bi-edge-connected.
1035 1087
  ///
1036
  /// This function checks that the graph is bi-edge-connected. The undirected
1037
  /// graph is bi-edge-connected when any two nodes are connected with two
1038
  /// edge-disjoint paths.
1088
  /// This function checks whether the given undirected graph is 
1089
  /// bi-edge-connected, i.e. any two nodes are connected with at least
1090
  /// two edge-disjoint paths.
1039 1091
  ///
1040
  /// \param graph The undirected graph.
1041
  /// \return The number of components.
1092
  /// \return \c true if the graph is bi-edge-connected.
1093
  /// \note By definition, the empty graph is bi-edge-connected.
1094
  ///
1095
  /// \see countBiEdgeConnectedComponents(), biEdgeConnectedComponents()
1042 1096
  template <typename Graph>
1043 1097
  bool biEdgeConnected(const Graph& graph) {
1044 1098
    return countBiEdgeConnectedComponents(graph) <= 1;
1045 1099
  }
1046 1100

	
1047 1101
  /// \ingroup graph_properties
1048 1102
  ///
1049
  /// \brief Count the bi-edge-connected components.
1103
  /// \brief Count the number of bi-edge-connected components of an
1104
  /// undirected graph.
1050 1105
  ///
1051
  /// This function count the bi-edge-connected components in an undirected
1052
  /// graph. The bi-edge-connected components are the classes of an equivalence
1053
  /// relation on the nodes. Two nodes are in relationship when they are
1054
  /// connected with at least two edge-disjoint paths.
1106
  /// This function counts the number of bi-edge-connected components of
1107
  /// the given undirected graph.
1055 1108
  ///
1056
  /// \param graph The undirected graph.
1057
  /// \return The number of components.
1109
  /// The bi-edge-connected components are the classes of an equivalence
1110
  /// relation on the nodes of an undirected graph. Two nodes are in the
1111
  /// same class if they are connected with at least two edge-disjoint
1112
  /// paths.
1113
  ///
1114
  /// \return The number of bi-edge-connected components.
1115
  ///
1116
  /// \see biEdgeConnected(), biEdgeConnectedComponents()
1058 1117
  template <typename Graph>
1059 1118
  int countBiEdgeConnectedComponents(const Graph& graph) {
1060 1119
    checkConcept<concepts::Graph, Graph>();
1061 1120
    typedef typename Graph::NodeIt NodeIt;
1062 1121

	
1063 1122
    using namespace _connectivity_bits;
1064 1123

	
1065 1124
    typedef CountBiEdgeConnectedComponentsVisitor<Graph> Visitor;
1066 1125

	
1067 1126
    int compNum = 0;
1068 1127
    Visitor visitor(graph, compNum);
1069 1128

	
1070 1129
    DfsVisit<Graph, Visitor> dfs(graph, visitor);
1071 1130
    dfs.init();
1072 1131

	
1073 1132
    for (NodeIt it(graph); it != INVALID; ++it) {
1074 1133
      if (!dfs.reached(it)) {
1075 1134
        dfs.addSource(it);
1076 1135
        dfs.start();
1077 1136
      }
1078 1137
    }
1079 1138
    return compNum;
1080 1139
  }
1081 1140

	
1082 1141
  /// \ingroup graph_properties
1083 1142
  ///
1084
  /// \brief Find the bi-edge-connected components.
1143
  /// \brief Find the bi-edge-connected components of an undirected graph.
1085 1144
  ///
1086
  /// This function finds the bi-edge-connected components in an undirected
1087
  /// graph. The bi-edge-connected components are the classes of an equivalence
1088
  /// relation on the nodes. Two nodes are in relationship when they are
1089
  /// connected at least two edge-disjoint paths.
1145
  /// This function finds the bi-edge-connected components of the given
1146
  /// undirected graph.
1147
  ///
1148
  /// The bi-edge-connected components are the classes of an equivalence
1149
  /// relation on the nodes of an undirected graph. Two nodes are in the
1150
  /// same class if they are connected with at least two edge-disjoint
1151
  /// paths.
1090 1152
  ///
1091 1153
  /// \image html edge_biconnected_components.png
1092 1154
  /// \image latex edge_biconnected_components.eps "bi-edge-connected components" width=\textwidth
1093 1155
  ///
1094
  /// \param graph The graph.
1156
  /// \param graph The undirected graph.
1095 1157
  /// \retval compMap A writable node map. The values will be set from 0 to
1096
  /// the number of the biconnected components minus one. Each values
1097
  /// of the map will be set exactly once, the values of a certain component
1098
  /// will be set continuously.
1099
  /// \return The number of components.
1158
  /// the number of the bi-edge-connected components minus one. Each value
1159
  /// of the map will be set exactly once, and the values of a certain
1160
  /// component will be set continuously.
1161
  /// \return The number of bi-edge-connected components.
1162
  ///
1163
  /// \see biEdgeConnected(), countBiEdgeConnectedComponents()
1100 1164
  template <typename Graph, typename NodeMap>
1101 1165
  int biEdgeConnectedComponents(const Graph& graph, NodeMap& compMap) {
1102 1166
    checkConcept<concepts::Graph, Graph>();
1103 1167
    typedef typename Graph::NodeIt NodeIt;
1104 1168
    typedef typename Graph::Node Node;
1105 1169
    checkConcept<concepts::WriteMap<Node, int>, NodeMap>();
1106 1170

	
1107 1171
    using namespace _connectivity_bits;
1108 1172

	
1109 1173
    typedef BiEdgeConnectedComponentsVisitor<Graph, NodeMap> Visitor;
1110 1174

	
1111 1175
    int compNum = 0;
1112 1176
    Visitor visitor(graph, compMap, compNum);
1113 1177

	
1114 1178
    DfsVisit<Graph, Visitor> dfs(graph, visitor);
1115 1179
    dfs.init();
1116 1180

	
1117 1181
    for (NodeIt it(graph); it != INVALID; ++it) {
1118 1182
      if (!dfs.reached(it)) {
1119 1183
        dfs.addSource(it);
1120 1184
        dfs.start();
1121 1185
      }
1122 1186
    }
1123 1187
    return compNum;
1124 1188
  }
1125 1189

	
1126 1190
  /// \ingroup graph_properties
1127 1191
  ///
1128
  /// \brief Find the bi-edge-connected cut edges.
1192
  /// \brief Find the bi-edge-connected cut edges in an undirected graph.
1129 1193
  ///
1130
  /// This function finds the bi-edge-connected components in an undirected
1131
  /// graph. The bi-edge-connected components are the classes of an equivalence
1132
  /// relation on the nodes. Two nodes are in relationship when they are
1133
  /// connected with at least two edge-disjoint paths. The bi-edge-connected
1134
  /// components are separted by edges which are the cut edges of the
1135
  /// components.
1194
  /// This function finds the bi-edge-connected cut edges in the given
1195
  /// undirected graph. 
1136 1196
  ///
1137
  /// \param graph The graph.
1138
  /// \retval cutMap A writable node map. The values will be set true when the
1139
  /// edge is a cut edge.
1197
  /// The bi-edge-connected components are the classes of an equivalence
1198
  /// relation on the nodes of an undirected graph. Two nodes are in the
1199
  /// same class if they are connected with at least two edge-disjoint
1200
  /// paths.
1201
  /// The bi-edge-connected components are separted by the cut edges of
1202
  /// the components.
1203
  ///
1204
  /// \param graph The undirected graph.
1205
  /// \retval cutMap A writable edge map. The values will be set to \c true
1206
  /// for the cut edges (exactly once for each cut edge), and will not be
1207
  /// changed for other edges.
1140 1208
  /// \return The number of cut edges.
1209
  ///
1210
  /// \see biEdgeConnected(), biEdgeConnectedComponents()
1141 1211
  template <typename Graph, typename EdgeMap>
1142 1212
  int biEdgeConnectedCutEdges(const Graph& graph, EdgeMap& cutMap) {
1143 1213
    checkConcept<concepts::Graph, Graph>();
1144 1214
    typedef typename Graph::NodeIt NodeIt;
1145 1215
    typedef typename Graph::Edge Edge;
1146 1216
    checkConcept<concepts::WriteMap<Edge, bool>, EdgeMap>();
1147 1217

	
1148 1218
    using namespace _connectivity_bits;
1149 1219

	
1150 1220
    typedef BiEdgeConnectedCutEdgesVisitor<Graph, EdgeMap> Visitor;
1151 1221

	
1152 1222
    int cutNum = 0;
1153 1223
    Visitor visitor(graph, cutMap, cutNum);
1154 1224

	
1155 1225
    DfsVisit<Graph, Visitor> dfs(graph, visitor);
1156 1226
    dfs.init();
1157 1227

	
1158 1228
    for (NodeIt it(graph); it != INVALID; ++it) {
1159 1229
      if (!dfs.reached(it)) {
1160 1230
        dfs.addSource(it);
1161 1231
        dfs.start();
1162 1232
      }
1163 1233
    }
1164 1234
    return cutNum;
1165 1235
  }
1166 1236

	
1167 1237

	
1168 1238
  namespace _connectivity_bits {
1169 1239

	
1170 1240
    template <typename Digraph, typename IntNodeMap>
1171 1241
    class TopologicalSortVisitor : public DfsVisitor<Digraph> {
1172 1242
    public:
1173 1243
      typedef typename Digraph::Node Node;
1174 1244
      typedef typename Digraph::Arc edge;
1175 1245

	
1176 1246
      TopologicalSortVisitor(IntNodeMap& order, int num)
1177 1247
        : _order(order), _num(num) {}
1178 1248

	
1179 1249
      void leave(const Node& node) {
1180 1250
        _order.set(node, --_num);
1181 1251
      }
1182 1252

	
1183 1253
    private:
1184 1254
      IntNodeMap& _order;
1185 1255
      int _num;
1186 1256
    };
1187 1257

	
1188 1258
  }
1189 1259

	
1190 1260
  /// \ingroup graph_properties
1191 1261
  ///
1262
  /// \brief Check whether a digraph is DAG.
1263
  ///
1264
  /// This function checks whether the given digraph is DAG, i.e.
1265
  /// \e Directed \e Acyclic \e Graph.
1266
  /// \return \c true if there is no directed cycle in the digraph.
1267
  /// \see acyclic()
1268
  template <typename Digraph>
1269
  bool dag(const Digraph& digraph) {
1270

	
1271
    checkConcept<concepts::Digraph, Digraph>();
1272

	
1273
    typedef typename Digraph::Node Node;
1274
    typedef typename Digraph::NodeIt NodeIt;
1275
    typedef typename Digraph::Arc Arc;
1276

	
1277
    typedef typename Digraph::template NodeMap<bool> ProcessedMap;
1278

	
1279
    typename Dfs<Digraph>::template SetProcessedMap<ProcessedMap>::
1280
      Create dfs(digraph);
1281

	
1282
    ProcessedMap processed(digraph);
1283
    dfs.processedMap(processed);
1284

	
1285
    dfs.init();
1286
    for (NodeIt it(digraph); it != INVALID; ++it) {
1287
      if (!dfs.reached(it)) {
1288
        dfs.addSource(it);
1289
        while (!dfs.emptyQueue()) {
1290
          Arc arc = dfs.nextArc();
1291
          Node target = digraph.target(arc);
1292
          if (dfs.reached(target) && !processed[target]) {
1293
            return false;
1294
          }
1295
          dfs.processNextArc();
1296
        }
1297
      }
1298
    }
1299
    return true;
1300
  }
1301

	
1302
  /// \ingroup graph_properties
1303
  ///
1192 1304
  /// \brief Sort the nodes of a DAG into topolgical order.
1193 1305
  ///
1194
  /// Sort the nodes of a DAG into topolgical order.
1306
  /// This function sorts the nodes of the given acyclic digraph (DAG)
1307
  /// into topolgical order.
1195 1308
  ///
1196
  /// \param graph The graph. It must be directed and acyclic.
1309
  /// \param digraph The digraph, which must be DAG.
1197 1310
  /// \retval order A writable node map. The values will be set from 0 to
1198
  /// the number of the nodes in the graph minus one. Each values of the map
1199
  /// will be set exactly once, the values  will be set descending order.
1311
  /// the number of the nodes in the digraph minus one. Each value of the
1312
  /// map will be set exactly once, and the values will be set descending
1313
  /// order.
1200 1314
  ///
1201
  /// \see checkedTopologicalSort
1202
  /// \see dag
1315
  /// \see dag(), checkedTopologicalSort()
1203 1316
  template <typename Digraph, typename NodeMap>
1204
  void topologicalSort(const Digraph& graph, NodeMap& order) {
1317
  void topologicalSort(const Digraph& digraph, NodeMap& order) {
1205 1318
    using namespace _connectivity_bits;
1206 1319

	
1207 1320
    checkConcept<concepts::Digraph, Digraph>();
1208 1321
    checkConcept<concepts::WriteMap<typename Digraph::Node, int>, NodeMap>();
1209 1322

	
1210 1323
    typedef typename Digraph::Node Node;
1211 1324
    typedef typename Digraph::NodeIt NodeIt;
1212 1325
    typedef typename Digraph::Arc Arc;
1213 1326

	
1214 1327
    TopologicalSortVisitor<Digraph, NodeMap>
1215
      visitor(order, countNodes(graph));
1328
      visitor(order, countNodes(digraph));
1216 1329

	
1217 1330
    DfsVisit<Digraph, TopologicalSortVisitor<Digraph, NodeMap> >
1218
      dfs(graph, visitor);
1331
      dfs(digraph, visitor);
1219 1332

	
1220 1333
    dfs.init();
1221
    for (NodeIt it(graph); it != INVALID; ++it) {
1334
    for (NodeIt it(digraph); it != INVALID; ++it) {
1222 1335
      if (!dfs.reached(it)) {
1223 1336
        dfs.addSource(it);
1224 1337
        dfs.start();
1225 1338
      }
1226 1339
    }
1227 1340
  }
1228 1341

	
1229 1342
  /// \ingroup graph_properties
1230 1343
  ///
1231 1344
  /// \brief Sort the nodes of a DAG into topolgical order.
1232 1345
  ///
1233
  /// Sort the nodes of a DAG into topolgical order. It also checks
1234
  /// that the given graph is DAG.
1346
  /// This function sorts the nodes of the given acyclic digraph (DAG)
1347
  /// into topolgical order and also checks whether the given digraph
1348
  /// is DAG.
1235 1349
  ///
1236
  /// \param digraph The graph. It must be directed and acyclic.
1237
  /// \retval order A readable - writable node map. The values will be set
1238
  /// from 0 to the number of the nodes in the graph minus one. Each values
1239
  /// of the map will be set exactly once, the values will be set descending
1240
  /// order.
1241
  /// \return \c false when the graph is not DAG.
1350
  /// \param digraph The digraph.
1351
  /// \retval order A readable and writable node map. The values will be
1352
  /// set from 0 to the number of the nodes in the digraph minus one. 
1353
  /// Each value of the map will be set exactly once, and the values will
1354
  /// be set descending order.
1355
  /// \return \c false if the digraph is not DAG.
1242 1356
  ///
1243
  /// \see topologicalSort
1244
  /// \see dag
1357
  /// \see dag(), topologicalSort()
1245 1358
  template <typename Digraph, typename NodeMap>
1246 1359
  bool checkedTopologicalSort(const Digraph& digraph, NodeMap& order) {
1247 1360
    using namespace _connectivity_bits;
1248 1361

	
1249 1362
    checkConcept<concepts::Digraph, Digraph>();
1250 1363
    checkConcept<concepts::ReadWriteMap<typename Digraph::Node, int>,
1251 1364
      NodeMap>();
1252 1365

	
1253 1366
    typedef typename Digraph::Node Node;
1254 1367
    typedef typename Digraph::NodeIt NodeIt;
1255 1368
    typedef typename Digraph::Arc Arc;
1256 1369

	
1257 1370
    for (NodeIt it(digraph); it != INVALID; ++it) {
1258 1371
      order.set(it, -1);
1259 1372
    }
1260 1373

	
1261 1374
    TopologicalSortVisitor<Digraph, NodeMap>
1262 1375
      visitor(order, countNodes(digraph));
1263 1376

	
1264 1377
    DfsVisit<Digraph, TopologicalSortVisitor<Digraph, NodeMap> >
1265 1378
      dfs(digraph, visitor);
1266 1379

	
1267 1380
    dfs.init();
1268 1381
    for (NodeIt it(digraph); it != INVALID; ++it) {
1269 1382
      if (!dfs.reached(it)) {
1270 1383
        dfs.addSource(it);
1271 1384
        while (!dfs.emptyQueue()) {
1272 1385
           Arc arc = dfs.nextArc();
1273 1386
           Node target = digraph.target(arc);
1274 1387
           if (dfs.reached(target) && order[target] == -1) {
1275 1388
             return false;
1276 1389
           }
1277 1390
           dfs.processNextArc();
1278 1391
         }
1279 1392
      }
1280 1393
    }
1281 1394
    return true;
1282 1395
  }
1283 1396

	
1284 1397
  /// \ingroup graph_properties
1285 1398
  ///
1286
  /// \brief Check that the given directed graph is a DAG.
1399
  /// \brief Check whether an undirected graph is acyclic.
1287 1400
  ///
1288
  /// Check that the given directed graph is a DAG. The DAG is
1289
  /// an Directed Acyclic Digraph.
1290
  /// \return \c false when the graph is not DAG.
1291
  /// \see acyclic
1292
  template <typename Digraph>
1293
  bool dag(const Digraph& digraph) {
1294

	
1295
    checkConcept<concepts::Digraph, Digraph>();
1296

	
1297
    typedef typename Digraph::Node Node;
1298
    typedef typename Digraph::NodeIt NodeIt;
1299
    typedef typename Digraph::Arc Arc;
1300

	
1301
    typedef typename Digraph::template NodeMap<bool> ProcessedMap;
1302

	
1303
    typename Dfs<Digraph>::template SetProcessedMap<ProcessedMap>::
1304
      Create dfs(digraph);
1305

	
1306
    ProcessedMap processed(digraph);
1307
    dfs.processedMap(processed);
1308

	
1309
    dfs.init();
1310
    for (NodeIt it(digraph); it != INVALID; ++it) {
1311
      if (!dfs.reached(it)) {
1312
        dfs.addSource(it);
1313
        while (!dfs.emptyQueue()) {
1314
          Arc edge = dfs.nextArc();
1315
          Node target = digraph.target(edge);
1316
          if (dfs.reached(target) && !processed[target]) {
1317
            return false;
1318
          }
1319
          dfs.processNextArc();
1320
        }
1321
      }
1322
    }
1323
    return true;
1324
  }
1325

	
1326
  /// \ingroup graph_properties
1327
  ///
1328
  /// \brief Check that the given undirected graph is acyclic.
1329
  ///
1330
  /// Check that the given undirected graph acyclic.
1331
  /// \param graph The undirected graph.
1332
  /// \return \c true when there is no circle in the graph.
1333
  /// \see dag
1401
  /// This function checks whether the given undirected graph is acyclic.
1402
  /// \return \c true if there is no cycle in the graph.
1403
  /// \see dag()
1334 1404
  template <typename Graph>
1335 1405
  bool acyclic(const Graph& graph) {
1336 1406
    checkConcept<concepts::Graph, Graph>();
1337 1407
    typedef typename Graph::Node Node;
1338 1408
    typedef typename Graph::NodeIt NodeIt;
1339 1409
    typedef typename Graph::Arc Arc;
1340 1410
    Dfs<Graph> dfs(graph);
1341 1411
    dfs.init();
1342 1412
    for (NodeIt it(graph); it != INVALID; ++it) {
1343 1413
      if (!dfs.reached(it)) {
1344 1414
        dfs.addSource(it);
1345 1415
        while (!dfs.emptyQueue()) {
1346
          Arc edge = dfs.nextArc();
1347
          Node source = graph.source(edge);
1348
          Node target = graph.target(edge);
1416
          Arc arc = dfs.nextArc();
1417
          Node source = graph.source(arc);
1418
          Node target = graph.target(arc);
1349 1419
          if (dfs.reached(target) &&
1350
              dfs.predArc(source) != graph.oppositeArc(edge)) {
1420
              dfs.predArc(source) != graph.oppositeArc(arc)) {
1351 1421
            return false;
1352 1422
          }
1353 1423
          dfs.processNextArc();
1354 1424
        }
1355 1425
      }
1356 1426
    }
1357 1427
    return true;
1358 1428
  }
1359 1429

	
1360 1430
  /// \ingroup graph_properties
1361 1431
  ///
1362
  /// \brief Check that the given undirected graph is tree.
1432
  /// \brief Check whether an undirected graph is tree.
1363 1433
  ///
1364
  /// Check that the given undirected graph is tree.
1365
  /// \param graph The undirected graph.
1366
  /// \return \c true when the graph is acyclic and connected.
1434
  /// This function checks whether the given undirected graph is tree.
1435
  /// \return \c true if the graph is acyclic and connected.
1436
  /// \see acyclic(), connected()
1367 1437
  template <typename Graph>
1368 1438
  bool tree(const Graph& graph) {
1369 1439
    checkConcept<concepts::Graph, Graph>();
1370 1440
    typedef typename Graph::Node Node;
1371 1441
    typedef typename Graph::NodeIt NodeIt;
1372 1442
    typedef typename Graph::Arc Arc;
1443
    if (NodeIt(graph) == INVALID) return true;
1373 1444
    Dfs<Graph> dfs(graph);
1374 1445
    dfs.init();
1375 1446
    dfs.addSource(NodeIt(graph));
1376 1447
    while (!dfs.emptyQueue()) {
1377
      Arc edge = dfs.nextArc();
1378
      Node source = graph.source(edge);
1379
      Node target = graph.target(edge);
1448
      Arc arc = dfs.nextArc();
1449
      Node source = graph.source(arc);
1450
      Node target = graph.target(arc);
1380 1451
      if (dfs.reached(target) &&
1381
          dfs.predArc(source) != graph.oppositeArc(edge)) {
1452
          dfs.predArc(source) != graph.oppositeArc(arc)) {
1382 1453
        return false;
1383 1454
      }
1384 1455
      dfs.processNextArc();
1385 1456
    }
1386 1457
    for (NodeIt it(graph); it != INVALID; ++it) {
1387 1458
      if (!dfs.reached(it)) {
1388 1459
        return false;
1389 1460
      }
1390 1461
    }
1391 1462
    return true;
1392 1463
  }
1393 1464

	
1394 1465
  namespace _connectivity_bits {
1395 1466

	
1396 1467
    template <typename Digraph>
1397 1468
    class BipartiteVisitor : public BfsVisitor<Digraph> {
1398 1469
    public:
1399 1470
      typedef typename Digraph::Arc Arc;
1400 1471
      typedef typename Digraph::Node Node;
1401 1472

	
1402 1473
      BipartiteVisitor(const Digraph& graph, bool& bipartite)
1403 1474
        : _graph(graph), _part(graph), _bipartite(bipartite) {}
1404 1475

	
1405 1476
      void start(const Node& node) {
1406 1477
        _part[node] = true;
1407 1478
      }
1408 1479
      void discover(const Arc& edge) {
1409 1480
        _part.set(_graph.target(edge), !_part[_graph.source(edge)]);
1410 1481
      }
1411 1482
      void examine(const Arc& edge) {
1412 1483
        _bipartite = _bipartite &&
1413 1484
          _part[_graph.target(edge)] != _part[_graph.source(edge)];
1414 1485
      }
1415 1486

	
1416 1487
    private:
1417 1488

	
1418 1489
      const Digraph& _graph;
1419 1490
      typename Digraph::template NodeMap<bool> _part;
1420 1491
      bool& _bipartite;
1421 1492
    };
1422 1493

	
1423 1494
    template <typename Digraph, typename PartMap>
1424 1495
    class BipartitePartitionsVisitor : public BfsVisitor<Digraph> {
1425 1496
    public:
1426 1497
      typedef typename Digraph::Arc Arc;
1427 1498
      typedef typename Digraph::Node Node;
1428 1499

	
1429 1500
      BipartitePartitionsVisitor(const Digraph& graph,
1430 1501
                                 PartMap& part, bool& bipartite)
1431 1502
        : _graph(graph), _part(part), _bipartite(bipartite) {}
1432 1503

	
1433 1504
      void start(const Node& node) {
1434 1505
        _part.set(node, true);
1435 1506
      }
1436 1507
      void discover(const Arc& edge) {
1437 1508
        _part.set(_graph.target(edge), !_part[_graph.source(edge)]);
1438 1509
      }
1439 1510
      void examine(const Arc& edge) {
1440 1511
        _bipartite = _bipartite &&
1441 1512
          _part[_graph.target(edge)] != _part[_graph.source(edge)];
1442 1513
      }
1443 1514

	
1444 1515
    private:
1445 1516

	
1446 1517
      const Digraph& _graph;
1447 1518
      PartMap& _part;
1448 1519
      bool& _bipartite;
1449 1520
    };
1450 1521
  }
1451 1522

	
1452 1523
  /// \ingroup graph_properties
1453 1524
  ///
1454
  /// \brief Check if the given undirected graph is bipartite or not
1525
  /// \brief Check whether an undirected graph is bipartite.
1455 1526
  ///
1456
  /// The function checks if the given undirected \c graph graph is bipartite
1457
  /// or not. The \ref Bfs algorithm is used to calculate the result.
1458
  /// \param graph The undirected graph.
1459
  /// \return \c true if \c graph is bipartite, \c false otherwise.
1460
  /// \sa bipartitePartitions
1527
  /// The function checks whether the given undirected graph is bipartite.
1528
  /// \return \c true if the graph is bipartite.
1529
  ///
1530
  /// \see bipartitePartitions()
1461 1531
  template<typename Graph>
1462
  inline bool bipartite(const Graph &graph){
1532
  bool bipartite(const Graph &graph){
1463 1533
    using namespace _connectivity_bits;
1464 1534

	
1465 1535
    checkConcept<concepts::Graph, Graph>();
1466 1536

	
1467 1537
    typedef typename Graph::NodeIt NodeIt;
1468 1538
    typedef typename Graph::ArcIt ArcIt;
1469 1539

	
1470 1540
    bool bipartite = true;
1471 1541

	
1472 1542
    BipartiteVisitor<Graph>
1473 1543
      visitor(graph, bipartite);
1474 1544
    BfsVisit<Graph, BipartiteVisitor<Graph> >
1475 1545
      bfs(graph, visitor);
1476 1546
    bfs.init();
1477 1547
    for(NodeIt it(graph); it != INVALID; ++it) {
1478 1548
      if(!bfs.reached(it)){
1479 1549
        bfs.addSource(it);
1480 1550
        while (!bfs.emptyQueue()) {
1481 1551
          bfs.processNextNode();
1482 1552
          if (!bipartite) return false;
1483 1553
        }
1484 1554
      }
1485 1555
    }
1486 1556
    return true;
1487 1557
  }
1488 1558

	
1489 1559
  /// \ingroup graph_properties
1490 1560
  ///
1491
  /// \brief Check if the given undirected graph is bipartite or not
1561
  /// \brief Find the bipartite partitions of an undirected graph.
1492 1562
  ///
1493
  /// The function checks if the given undirected graph is bipartite
1494
  /// or not. The  \ref  Bfs  algorithm  is   used  to  calculate the result.
1495
  /// During the execution, the \c partMap will be set as the two
1496
  /// partitions of the graph.
1563
  /// This function checks whether the given undirected graph is bipartite
1564
  /// and gives back the bipartite partitions.
1497 1565
  ///
1498 1566
  /// \image html bipartite_partitions.png
1499 1567
  /// \image latex bipartite_partitions.eps "Bipartite partititions" width=\textwidth
1500 1568
  ///
1501 1569
  /// \param graph The undirected graph.
1502
  /// \retval partMap A writable bool map of nodes. It will be set as the
1503
  /// two partitions of the graph.
1504
  /// \return \c true if \c graph is bipartite, \c false otherwise.
1570
  /// \retval partMap A writable node map of \c bool (or convertible) value
1571
  /// type. The values will be set to \c true for one component and
1572
  /// \c false for the other one.
1573
  /// \return \c true if the graph is bipartite, \c false otherwise.
1574
  ///
1575
  /// \see bipartite()
1505 1576
  template<typename Graph, typename NodeMap>
1506
  inline bool bipartitePartitions(const Graph &graph, NodeMap &partMap){
1577
  bool bipartitePartitions(const Graph &graph, NodeMap &partMap){
1507 1578
    using namespace _connectivity_bits;
1508 1579

	
1509 1580
    checkConcept<concepts::Graph, Graph>();
1581
    checkConcept<concepts::WriteMap<typename Graph::Node, bool>, NodeMap>();
1510 1582

	
1511 1583
    typedef typename Graph::Node Node;
1512 1584
    typedef typename Graph::NodeIt NodeIt;
1513 1585
    typedef typename Graph::ArcIt ArcIt;
1514 1586

	
1515 1587
    bool bipartite = true;
1516 1588

	
1517 1589
    BipartitePartitionsVisitor<Graph, NodeMap>
1518 1590
      visitor(graph, partMap, bipartite);
1519 1591
    BfsVisit<Graph, BipartitePartitionsVisitor<Graph, NodeMap> >
1520 1592
      bfs(graph, visitor);
1521 1593
    bfs.init();
1522 1594
    for(NodeIt it(graph); it != INVALID; ++it) {
1523 1595
      if(!bfs.reached(it)){
1524 1596
        bfs.addSource(it);
1525 1597
        while (!bfs.emptyQueue()) {
1526 1598
          bfs.processNextNode();
1527 1599
          if (!bipartite) return false;
1528 1600
        }
1529 1601
      }
1530 1602
    }
1531 1603
    return true;
1532 1604
  }
1533 1605

	
1534
  /// \brief Returns true when there are not loop edges in the graph.
1606
  /// \ingroup graph_properties
1535 1607
  ///
1536
  /// Returns true when there are not loop edges in the graph.
1537
  template <typename Digraph>
1538
  bool loopFree(const Digraph& digraph) {
1539
    for (typename Digraph::ArcIt it(digraph); it != INVALID; ++it) {
1540
      if (digraph.source(it) == digraph.target(it)) return false;
1608
  /// \brief Check whether the given graph contains no loop arcs/edges.
1609
  ///
1610
  /// This function returns \c true if there are no loop arcs/edges in
1611
  /// the given graph. It works for both directed and undirected graphs.
1612
  template <typename Graph>
1613
  bool loopFree(const Graph& graph) {
1614
    for (typename Graph::ArcIt it(graph); it != INVALID; ++it) {
1615
      if (graph.source(it) == graph.target(it)) return false;
1541 1616
    }
1542 1617
    return true;
1543 1618
  }
1544 1619

	
1545
  /// \brief Returns true when there are not parallel edges in the graph.
1620
  /// \ingroup graph_properties
1546 1621
  ///
1547
  /// Returns true when there are not parallel edges in the graph.
1548
  template <typename Digraph>
1549
  bool parallelFree(const Digraph& digraph) {
1550
    typename Digraph::template NodeMap<bool> reached(digraph, false);
1551
    for (typename Digraph::NodeIt n(digraph); n != INVALID; ++n) {
1552
      for (typename Digraph::OutArcIt a(digraph, n); a != INVALID; ++a) {
1553
        if (reached[digraph.target(a)]) return false;
1554
        reached.set(digraph.target(a), true);
1622
  /// \brief Check whether the given graph contains no parallel arcs/edges.
1623
  ///
1624
  /// This function returns \c true if there are no parallel arcs/edges in
1625
  /// the given graph. It works for both directed and undirected graphs.
1626
  template <typename Graph>
1627
  bool parallelFree(const Graph& graph) {
1628
    typename Graph::template NodeMap<int> reached(graph, 0);
1629
    int cnt = 1;
1630
    for (typename Graph::NodeIt n(graph); n != INVALID; ++n) {
1631
      for (typename Graph::OutArcIt a(graph, n); a != INVALID; ++a) {
1632
        if (reached[graph.target(a)] == cnt) return false;
1633
        reached[graph.target(a)] = cnt;
1555 1634
      }
1556
      for (typename Digraph::OutArcIt a(digraph, n); a != INVALID; ++a) {
1557
        reached.set(digraph.target(a), false);
1558
      }
1635
      ++cnt;
1559 1636
    }
1560 1637
    return true;
1561 1638
  }
1562 1639

	
1563
  /// \brief Returns true when there are not loop edges and parallel
1564
  /// edges in the graph.
1640
  /// \ingroup graph_properties
1565 1641
  ///
1566
  /// Returns true when there are not loop edges and parallel edges in
1567
  /// the graph.
1568
  template <typename Digraph>
1569
  bool simpleDigraph(const Digraph& digraph) {
1570
    typename Digraph::template NodeMap<bool> reached(digraph, false);
1571
    for (typename Digraph::NodeIt n(digraph); n != INVALID; ++n) {
1572
      reached.set(n, true);
1573
      for (typename Digraph::OutArcIt a(digraph, n); a != INVALID; ++a) {
1574
        if (reached[digraph.target(a)]) return false;
1575
        reached.set(digraph.target(a), true);
1642
  /// \brief Check whether the given graph is simple.
1643
  ///
1644
  /// This function returns \c true if the given graph is simple, i.e.
1645
  /// it contains no loop arcs/edges and no parallel arcs/edges.
1646
  /// The function works for both directed and undirected graphs.
1647
  /// \see loopFree(), parallelFree()
1648
  template <typename Graph>
1649
  bool simpleGraph(const Graph& graph) {
1650
    typename Graph::template NodeMap<int> reached(graph, 0);
1651
    int cnt = 1;
1652
    for (typename Graph::NodeIt n(graph); n != INVALID; ++n) {
1653
      reached[n] = cnt;
1654
      for (typename Graph::OutArcIt a(graph, n); a != INVALID; ++a) {
1655
        if (reached[graph.target(a)] == cnt) return false;
1656
        reached[graph.target(a)] = cnt;
1576 1657
      }
1577
      for (typename Digraph::OutArcIt a(digraph, n); a != INVALID; ++a) {
1578
        reached.set(digraph.target(a), false);
1579
      }
1580
      reached.set(n, false);
1658
      ++cnt;
1581 1659
    }
1582 1660
    return true;
1583 1661
  }
1584 1662

	
1585 1663
} //namespace lemon
1586 1664

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

	
19 19
#ifndef LEMON_EDGE_SET_H
20 20
#define LEMON_EDGE_SET_H
21 21

	
22 22
#include <lemon/core.h>
23 23
#include <lemon/bits/edge_set_extender.h>
24 24

	
25
/// \ingroup semi_adaptors
25
/// \ingroup graphs
26 26
/// \file
27 27
/// \brief ArcSet and EdgeSet classes.
28 28
///
29 29
/// Graphs which use another graph's node-set as own.
30 30
namespace lemon {
31 31

	
32 32
  template <typename GR>
33 33
  class ListArcSetBase {
34 34
  public:
35 35

	
36 36
    typedef typename GR::Node Node;
37 37
    typedef typename GR::NodeIt NodeIt;
38 38

	
39 39
  protected:
40 40

	
41 41
    struct NodeT {
42 42
      int first_out, first_in;
43 43
      NodeT() : first_out(-1), first_in(-1) {}
44 44
    };
45 45

	
46 46
    typedef typename ItemSetTraits<GR, Node>::
47 47
    template Map<NodeT>::Type NodesImplBase;
48 48

	
49 49
    NodesImplBase* _nodes;
50 50

	
51 51
    struct ArcT {
52 52
      Node source, target;
53 53
      int next_out, next_in;
54 54
      int prev_out, prev_in;
55 55
      ArcT() : prev_out(-1), prev_in(-1) {}
56 56
    };
57 57

	
58 58
    std::vector<ArcT> arcs;
59 59

	
60 60
    int first_arc;
61 61
    int first_free_arc;
62 62

	
63 63
    const GR* _graph;
64 64

	
65 65
    void initalize(const GR& graph, NodesImplBase& nodes) {
66 66
      _graph = &graph;
67 67
      _nodes = &nodes;
68 68
    }
69 69

	
70 70
  public:
71 71

	
72 72
    class Arc {
73 73
      friend class ListArcSetBase<GR>;
74 74
    protected:
75 75
      Arc(int _id) : id(_id) {}
76 76
      int id;
77 77
    public:
78 78
      Arc() {}
79 79
      Arc(Invalid) : id(-1) {}
80 80
      bool operator==(const Arc& arc) const { return id == arc.id; }
81 81
      bool operator!=(const Arc& arc) const { return id != arc.id; }
82 82
      bool operator<(const Arc& arc) const { return id < arc.id; }
83 83
    };
84 84

	
85 85
    ListArcSetBase() : first_arc(-1), first_free_arc(-1) {}
86 86

	
87 87
    Arc addArc(const Node& u, const Node& v) {
88 88
      int n;
89 89
      if (first_free_arc == -1) {
90 90
        n = arcs.size();
91 91
        arcs.push_back(ArcT());
92 92
      } else {
93 93
        n = first_free_arc;
94 94
        first_free_arc = arcs[first_free_arc].next_in;
95 95
      }
96 96
      arcs[n].next_in = (*_nodes)[v].first_in;
97 97
      if ((*_nodes)[v].first_in != -1) {
98 98
        arcs[(*_nodes)[v].first_in].prev_in = n;
99 99
      }
100 100
      (*_nodes)[v].first_in = n;
101 101
      arcs[n].next_out = (*_nodes)[u].first_out;
102 102
      if ((*_nodes)[u].first_out != -1) {
103 103
        arcs[(*_nodes)[u].first_out].prev_out = n;
104 104
      }
105 105
      (*_nodes)[u].first_out = n;
106 106
      arcs[n].source = u;
107 107
      arcs[n].target = v;
108 108
      return Arc(n);
109 109
    }
110 110

	
111 111
    void erase(const Arc& arc) {
112 112
      int n = arc.id;
113 113
      if (arcs[n].prev_in != -1) {
114 114
        arcs[arcs[n].prev_in].next_in = arcs[n].next_in;
115 115
      } else {
116 116
        (*_nodes)[arcs[n].target].first_in = arcs[n].next_in;
117 117
      }
118 118
      if (arcs[n].next_in != -1) {
119 119
        arcs[arcs[n].next_in].prev_in = arcs[n].prev_in;
120 120
      }
121 121

	
122 122
      if (arcs[n].prev_out != -1) {
123 123
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
124 124
      } else {
125 125
        (*_nodes)[arcs[n].source].first_out = arcs[n].next_out;
126 126
      }
127 127
      if (arcs[n].next_out != -1) {
128 128
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
129 129
      }
130 130

	
131 131
    }
132 132

	
133 133
    void clear() {
134 134
      Node node;
135 135
      for (first(node); node != INVALID; next(node)) {
136 136
        (*_nodes)[node].first_in = -1;
137 137
        (*_nodes)[node].first_out = -1;
138 138
      }
139 139
      arcs.clear();
140 140
      first_arc = -1;
141 141
      first_free_arc = -1;
142 142
    }
143 143

	
144 144
    void first(Node& node) const {
145 145
      _graph->first(node);
146 146
    }
147 147

	
148 148
    void next(Node& node) const {
149 149
      _graph->next(node);
150 150
    }
151 151

	
152 152
    void first(Arc& arc) const {
153 153
      Node node;
154 154
      first(node);
155 155
      while (node != INVALID && (*_nodes)[node].first_in == -1) {
156 156
        next(node);
157 157
      }
158 158
      arc.id = (node == INVALID) ? -1 : (*_nodes)[node].first_in;
159 159
    }
160 160

	
161 161
    void next(Arc& arc) const {
162 162
      if (arcs[arc.id].next_in != -1) {
163 163
        arc.id = arcs[arc.id].next_in;
164 164
      } else {
165 165
        Node node = arcs[arc.id].target;
166 166
        next(node);
167 167
        while (node != INVALID && (*_nodes)[node].first_in == -1) {
168 168
          next(node);
169 169
        }
170 170
        arc.id = (node == INVALID) ? -1 : (*_nodes)[node].first_in;
171 171
      }
172 172
    }
173 173

	
174 174
    void firstOut(Arc& arc, const Node& node) const {
175 175
      arc.id = (*_nodes)[node].first_out;
176 176
    }
177 177

	
178 178
    void nextOut(Arc& arc) const {
179 179
      arc.id = arcs[arc.id].next_out;
180 180
    }
181 181

	
182 182
    void firstIn(Arc& arc, const Node& node) const {
183 183
      arc.id = (*_nodes)[node].first_in;
184 184
    }
185 185

	
186 186
    void nextIn(Arc& arc) const {
187 187
      arc.id = arcs[arc.id].next_in;
188 188
    }
189 189

	
190 190
    int id(const Node& node) const { return _graph->id(node); }
191 191
    int id(const Arc& arc) const { return arc.id; }
192 192

	
193 193
    Node nodeFromId(int ix) const { return _graph->nodeFromId(ix); }
194 194
    Arc arcFromId(int ix) const { return Arc(ix); }
195 195

	
196 196
    int maxNodeId() const { return _graph->maxNodeId(); };
197 197
    int maxArcId() const { return arcs.size() - 1; }
198 198

	
199 199
    Node source(const Arc& arc) const { return arcs[arc.id].source;}
200 200
    Node target(const Arc& arc) const { return arcs[arc.id].target;}
201 201

	
202 202
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
203 203

	
204 204
    NodeNotifier& notifier(Node) const {
205 205
      return _graph->notifier(Node());
206 206
    }
207 207

	
208 208
    template <typename V>
209 209
    class NodeMap : public GR::template NodeMap<V> {
210 210
      typedef typename GR::template NodeMap<V> Parent;
211 211

	
212 212
    public:
213 213

	
214 214
      explicit NodeMap(const ListArcSetBase<GR>& arcset)
215 215
        : Parent(*arcset._graph) {}
216 216

	
217 217
      NodeMap(const ListArcSetBase<GR>& arcset, const V& value)
218 218
        : Parent(*arcset._graph, value) {}
219 219

	
220 220
      NodeMap& operator=(const NodeMap& cmap) {
221 221
        return operator=<NodeMap>(cmap);
222 222
      }
223 223

	
224 224
      template <typename CMap>
225 225
      NodeMap& operator=(const CMap& cmap) {
226 226
        Parent::operator=(cmap);
227 227
        return *this;
228 228
      }
229 229
    };
230 230

	
231 231
  };
232 232

	
233
  /// \ingroup semi_adaptors
233
  /// \ingroup graphs
234 234
  ///
235 235
  /// \brief Digraph using a node set of another digraph or graph and
236 236
  /// an own arc set.
237 237
  ///
238 238
  /// This structure can be used to establish another directed graph
239 239
  /// over a node set of an existing one. This class uses the same
240 240
  /// Node type as the underlying graph, and each valid node of the
241 241
  /// original graph is valid in this arc set, therefore the node
242 242
  /// objects of the original graph can be used directly with this
243 243
  /// class. The node handling functions (id handling, observing, and
244 244
  /// iterators) works equivalently as in the original graph.
245 245
  ///
246 246
  /// This implementation is based on doubly-linked lists, from each
247 247
  /// node the outgoing and the incoming arcs make up lists, therefore
248 248
  /// one arc can be erased in constant time. It also makes possible,
249 249
  /// that node can be removed from the underlying graph, in this case
250 250
  /// all arcs incident to the given node is erased from the arc set.
251 251
  ///
252 252
  /// \param GR The type of the graph which shares its node set with
253 253
  /// this class. Its interface must conform to the
254 254
  /// \ref concepts::Digraph "Digraph" or \ref concepts::Graph "Graph"
255 255
  /// concept.
256 256
  ///
257 257
  /// This class fully conforms to the \ref concepts::Digraph
258 258
  /// "Digraph" concept.
259 259
  template <typename GR>
260 260
  class ListArcSet : public ArcSetExtender<ListArcSetBase<GR> > {
261 261
    typedef ArcSetExtender<ListArcSetBase<GR> > Parent;
262 262

	
263 263
  public:
264 264

	
265 265
    typedef typename Parent::Node Node;
266 266
    typedef typename Parent::Arc Arc;
267 267

	
268 268
    typedef typename Parent::NodesImplBase NodesImplBase;
269 269

	
270 270
    void eraseNode(const Node& node) {
271 271
      Arc arc;
272 272
      Parent::firstOut(arc, node);
273 273
      while (arc != INVALID ) {
274 274
        erase(arc);
275 275
        Parent::firstOut(arc, node);
276 276
      }
277 277

	
278 278
      Parent::firstIn(arc, node);
279 279
      while (arc != INVALID ) {
280 280
        erase(arc);
281 281
        Parent::firstIn(arc, node);
282 282
      }
283 283
    }
284 284

	
285 285
    void clearNodes() {
286 286
      Parent::clear();
287 287
    }
288 288

	
289 289
    class NodesImpl : public NodesImplBase {
290 290
      typedef NodesImplBase Parent;
291 291

	
292 292
    public:
293 293
      NodesImpl(const GR& graph, ListArcSet& arcset)
294 294
        : Parent(graph), _arcset(arcset) {}
295 295

	
296 296
      virtual ~NodesImpl() {}
297 297

	
298 298
    protected:
299 299

	
300 300
      virtual void erase(const Node& node) {
301 301
        _arcset.eraseNode(node);
302 302
        Parent::erase(node);
303 303
      }
304 304
      virtual void erase(const std::vector<Node>& nodes) {
305 305
        for (int i = 0; i < int(nodes.size()); ++i) {
306 306
          _arcset.eraseNode(nodes[i]);
307 307
        }
308 308
        Parent::erase(nodes);
309 309
      }
310 310
      virtual void clear() {
311 311
        _arcset.clearNodes();
312 312
        Parent::clear();
313 313
      }
314 314

	
315 315
    private:
316 316
      ListArcSet& _arcset;
317 317
    };
318 318

	
319 319
    NodesImpl _nodes;
320 320

	
321 321
  public:
322 322

	
323 323
    /// \brief Constructor of the ArcSet.
324 324
    ///
325 325
    /// Constructor of the ArcSet.
326 326
    ListArcSet(const GR& graph) : _nodes(graph, *this) {
327 327
      Parent::initalize(graph, _nodes);
328 328
    }
329 329

	
330 330
    /// \brief Add a new arc to the digraph.
331 331
    ///
332 332
    /// Add a new arc to the digraph with source node \c s
333 333
    /// and target node \c t.
334 334
    /// \return The new arc.
335 335
    Arc addArc(const Node& s, const Node& t) {
336 336
      return Parent::addArc(s, t);
337 337
    }
338 338

	
339 339
    /// \brief Erase an arc from the digraph.
340 340
    ///
341 341
    /// Erase an arc \c a from the digraph.
342 342
    void erase(const Arc& a) {
343 343
      return Parent::erase(a);
344 344
    }
345 345

	
346 346
  };
347 347

	
348 348
  template <typename GR>
349 349
  class ListEdgeSetBase {
350 350
  public:
351 351

	
352 352
    typedef typename GR::Node Node;
353 353
    typedef typename GR::NodeIt NodeIt;
354 354

	
355 355
  protected:
356 356

	
357 357
    struct NodeT {
358 358
      int first_out;
359 359
      NodeT() : first_out(-1) {}
360 360
    };
361 361

	
362 362
    typedef typename ItemSetTraits<GR, Node>::
363 363
    template Map<NodeT>::Type NodesImplBase;
364 364

	
365 365
    NodesImplBase* _nodes;
366 366

	
367 367
    struct ArcT {
368 368
      Node target;
369 369
      int prev_out, next_out;
370 370
      ArcT() : prev_out(-1), next_out(-1) {}
371 371
    };
372 372

	
373 373
    std::vector<ArcT> arcs;
374 374

	
375 375
    int first_arc;
376 376
    int first_free_arc;
377 377

	
378 378
    const GR* _graph;
379 379

	
380 380
    void initalize(const GR& graph, NodesImplBase& nodes) {
381 381
      _graph = &graph;
382 382
      _nodes = &nodes;
383 383
    }
384 384

	
385 385
  public:
386 386

	
387 387
    class Edge {
388 388
      friend class ListEdgeSetBase;
389 389
    protected:
390 390

	
391 391
      int id;
392 392
      explicit Edge(int _id) { id = _id;}
393 393

	
394 394
    public:
395 395
      Edge() {}
396 396
      Edge (Invalid) { id = -1; }
397 397
      bool operator==(const Edge& arc) const {return id == arc.id;}
398 398
      bool operator!=(const Edge& arc) const {return id != arc.id;}
399 399
      bool operator<(const Edge& arc) const {return id < arc.id;}
400 400
    };
401 401

	
402 402
    class Arc {
403 403
      friend class ListEdgeSetBase;
404 404
    protected:
405 405
      Arc(int _id) : id(_id) {}
406 406
      int id;
407 407
    public:
408 408
      operator Edge() const { return edgeFromId(id / 2); }
409 409

	
410 410
      Arc() {}
411 411
      Arc(Invalid) : id(-1) {}
412 412
      bool operator==(const Arc& arc) const { return id == arc.id; }
413 413
      bool operator!=(const Arc& arc) const { return id != arc.id; }
414 414
      bool operator<(const Arc& arc) const { return id < arc.id; }
415 415
    };
416 416

	
417 417
    ListEdgeSetBase() : first_arc(-1), first_free_arc(-1) {}
418 418

	
419 419
    Edge addEdge(const Node& u, const Node& v) {
420 420
      int n;
421 421

	
422 422
      if (first_free_arc == -1) {
423 423
        n = arcs.size();
424 424
        arcs.push_back(ArcT());
425 425
        arcs.push_back(ArcT());
426 426
      } else {
427 427
        n = first_free_arc;
428 428
        first_free_arc = arcs[n].next_out;
429 429
      }
430 430

	
431 431
      arcs[n].target = u;
432 432
      arcs[n | 1].target = v;
433 433

	
434 434
      arcs[n].next_out = (*_nodes)[v].first_out;
435 435
      if ((*_nodes)[v].first_out != -1) {
436 436
        arcs[(*_nodes)[v].first_out].prev_out = n;
437 437
      }
438 438
      (*_nodes)[v].first_out = n;
439 439
      arcs[n].prev_out = -1;
440 440

	
441 441
      if ((*_nodes)[u].first_out != -1) {
442 442
        arcs[(*_nodes)[u].first_out].prev_out = (n | 1);
443 443
      }
444 444
      arcs[n | 1].next_out = (*_nodes)[u].first_out;
445 445
      (*_nodes)[u].first_out = (n | 1);
446 446
      arcs[n | 1].prev_out = -1;
447 447

	
448 448
      return Edge(n / 2);
449 449
    }
450 450

	
451 451
    void erase(const Edge& arc) {
452 452
      int n = arc.id * 2;
453 453

	
454 454
      if (arcs[n].next_out != -1) {
455 455
        arcs[arcs[n].next_out].prev_out = arcs[n].prev_out;
456 456
      }
457 457

	
458 458
      if (arcs[n].prev_out != -1) {
459 459
        arcs[arcs[n].prev_out].next_out = arcs[n].next_out;
460 460
      } else {
461 461
        (*_nodes)[arcs[n | 1].target].first_out = arcs[n].next_out;
462 462
      }
463 463

	
464 464
      if (arcs[n | 1].next_out != -1) {
465 465
        arcs[arcs[n | 1].next_out].prev_out = arcs[n | 1].prev_out;
466 466
      }
467 467

	
468 468
      if (arcs[n | 1].prev_out != -1) {
469 469
        arcs[arcs[n | 1].prev_out].next_out = arcs[n | 1].next_out;
470 470
      } else {
471 471
        (*_nodes)[arcs[n].target].first_out = arcs[n | 1].next_out;
472 472
      }
473 473

	
474 474
      arcs[n].next_out = first_free_arc;
475 475
      first_free_arc = n;
476 476

	
477 477
    }
478 478

	
479 479
    void clear() {
480 480
      Node node;
481 481
      for (first(node); node != INVALID; next(node)) {
482 482
        (*_nodes)[node].first_out = -1;
483 483
      }
484 484
      arcs.clear();
485 485
      first_arc = -1;
486 486
      first_free_arc = -1;
487 487
    }
488 488

	
489 489
    void first(Node& node) const {
490 490
      _graph->first(node);
491 491
    }
492 492

	
493 493
    void next(Node& node) const {
494 494
      _graph->next(node);
495 495
    }
496 496

	
497 497
    void first(Arc& arc) const {
498 498
      Node node;
499 499
      first(node);
500 500
      while (node != INVALID && (*_nodes)[node].first_out == -1) {
501 501
        next(node);
502 502
      }
503 503
      arc.id = (node == INVALID) ? -1 : (*_nodes)[node].first_out;
504 504
    }
505 505

	
506 506
    void next(Arc& arc) const {
507 507
      if (arcs[arc.id].next_out != -1) {
508 508
        arc.id = arcs[arc.id].next_out;
509 509
      } else {
510 510
        Node node = arcs[arc.id ^ 1].target;
511 511
        next(node);
512 512
        while(node != INVALID && (*_nodes)[node].first_out == -1) {
513 513
          next(node);
514 514
        }
515 515
        arc.id = (node == INVALID) ? -1 : (*_nodes)[node].first_out;
516 516
      }
517 517
    }
518 518

	
519 519
    void first(Edge& edge) const {
520 520
      Node node;
521 521
      first(node);
522 522
      while (node != INVALID) {
523 523
        edge.id = (*_nodes)[node].first_out;
524 524
        while ((edge.id & 1) != 1) {
525 525
          edge.id = arcs[edge.id].next_out;
526 526
        }
527 527
        if (edge.id != -1) {
528 528
          edge.id /= 2;
529 529
          return;
530 530
        }
531 531
        next(node);
532 532
      }
533 533
      edge.id = -1;
534 534
    }
535 535

	
536 536
    void next(Edge& edge) const {
537 537
      Node node = arcs[edge.id * 2].target;
538 538
      edge.id = arcs[(edge.id * 2) | 1].next_out;
539 539
      while ((edge.id & 1) != 1) {
540 540
        edge.id = arcs[edge.id].next_out;
541 541
      }
542 542
      if (edge.id != -1) {
543 543
        edge.id /= 2;
544 544
        return;
545 545
      }
546 546
      next(node);
547 547
      while (node != INVALID) {
548 548
        edge.id = (*_nodes)[node].first_out;
549 549
        while ((edge.id & 1) != 1) {
550 550
          edge.id = arcs[edge.id].next_out;
551 551
        }
552 552
        if (edge.id != -1) {
553 553
          edge.id /= 2;
554 554
          return;
555 555
        }
556 556
        next(node);
557 557
      }
558 558
      edge.id = -1;
559 559
    }
560 560

	
561 561
    void firstOut(Arc& arc, const Node& node) const {
562 562
      arc.id = (*_nodes)[node].first_out;
563 563
    }
564 564

	
565 565
    void nextOut(Arc& arc) const {
566 566
      arc.id = arcs[arc.id].next_out;
567 567
    }
568 568

	
569 569
    void firstIn(Arc& arc, const Node& node) const {
570 570
      arc.id = (((*_nodes)[node].first_out) ^ 1);
571 571
      if (arc.id == -2) arc.id = -1;
572 572
    }
573 573

	
574 574
    void nextIn(Arc& arc) const {
575 575
      arc.id = ((arcs[arc.id ^ 1].next_out) ^ 1);
576 576
      if (arc.id == -2) arc.id = -1;
577 577
    }
578 578

	
579 579
    void firstInc(Edge &arc, bool& dir, const Node& node) const {
580 580
      int de = (*_nodes)[node].first_out;
581 581
      if (de != -1 ) {
582 582
        arc.id = de / 2;
583 583
        dir = ((de & 1) == 1);
584 584
      } else {
585 585
        arc.id = -1;
586 586
        dir = true;
587 587
      }
588 588
    }
589 589
    void nextInc(Edge &arc, bool& dir) const {
590 590
      int de = (arcs[(arc.id * 2) | (dir ? 1 : 0)].next_out);
591 591
      if (de != -1 ) {
592 592
        arc.id = de / 2;
593 593
        dir = ((de & 1) == 1);
594 594
      } else {
595 595
        arc.id = -1;
596 596
        dir = true;
597 597
      }
598 598
    }
599 599

	
600 600
    static bool direction(Arc arc) {
601 601
      return (arc.id & 1) == 1;
602 602
    }
603 603

	
604 604
    static Arc direct(Edge edge, bool dir) {
605 605
      return Arc(edge.id * 2 + (dir ? 1 : 0));
606 606
    }
607 607

	
608 608
    int id(const Node& node) const { return _graph->id(node); }
609 609
    static int id(Arc e) { return e.id; }
610 610
    static int id(Edge e) { return e.id; }
611 611

	
612 612
    Node nodeFromId(int id) const { return _graph->nodeFromId(id); }
613 613
    static Arc arcFromId(int id) { return Arc(id);}
614 614
    static Edge edgeFromId(int id) { return Edge(id);}
615 615

	
616 616
    int maxNodeId() const { return _graph->maxNodeId(); };
617 617
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
618 618
    int maxArcId() const { return arcs.size()-1; }
619 619

	
620 620
    Node source(Arc e) const { return arcs[e.id ^ 1].target; }
621 621
    Node target(Arc e) const { return arcs[e.id].target; }
622 622

	
623 623
    Node u(Edge e) const { return arcs[2 * e.id].target; }
624 624
    Node v(Edge e) const { return arcs[2 * e.id + 1].target; }
625 625

	
626 626
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
627 627

	
628 628
    NodeNotifier& notifier(Node) const {
629 629
      return _graph->notifier(Node());
630 630
    }
631 631

	
632 632
    template <typename V>
633 633
    class NodeMap : public GR::template NodeMap<V> {
634 634
      typedef typename GR::template NodeMap<V> Parent;
635 635

	
636 636
    public:
637 637

	
638 638
      explicit NodeMap(const ListEdgeSetBase<GR>& arcset)
639 639
        : Parent(*arcset._graph) {}
640 640

	
641 641
      NodeMap(const ListEdgeSetBase<GR>& arcset, const V& value)
642 642
        : Parent(*arcset._graph, value) {}
643 643

	
644 644
      NodeMap& operator=(const NodeMap& cmap) {
645 645
        return operator=<NodeMap>(cmap);
646 646
      }
647 647

	
648 648
      template <typename CMap>
649 649
      NodeMap& operator=(const CMap& cmap) {
650 650
        Parent::operator=(cmap);
651 651
        return *this;
652 652
      }
653 653
    };
654 654

	
655 655
  };
656 656

	
657
  /// \ingroup semi_adaptors
657
  /// \ingroup graphs
658 658
  ///
659 659
  /// \brief Graph using a node set of another digraph or graph and an
660 660
  /// own edge set.
661 661
  ///
662 662
  /// This structure can be used to establish another graph over a
663 663
  /// node set of an existing one. This class uses the same Node type
664 664
  /// as the underlying graph, and each valid node of the original
665 665
  /// graph is valid in this arc set, therefore the node objects of
666 666
  /// the original graph can be used directly with this class. The
667 667
  /// node handling functions (id handling, observing, and iterators)
668 668
  /// works equivalently as in the original graph.
669 669
  ///
670 670
  /// This implementation is based on doubly-linked lists, from each
671 671
  /// node the incident edges make up lists, therefore one edge can be
672 672
  /// erased in constant time. It also makes possible, that node can
673 673
  /// be removed from the underlying graph, in this case all edges
674 674
  /// incident to the given node is erased from the arc set.
675 675
  ///
676 676
  /// \param GR The type of the graph which shares its node set
677 677
  /// with this class. Its interface must conform to the
678 678
  /// \ref concepts::Digraph "Digraph" or \ref concepts::Graph "Graph"
679 679
  /// concept.
680 680
  ///
681 681
  /// This class fully conforms to the \ref concepts::Graph "Graph"
682 682
  /// concept.
683 683
  template <typename GR>
684 684
  class ListEdgeSet : public EdgeSetExtender<ListEdgeSetBase<GR> > {
685 685
    typedef EdgeSetExtender<ListEdgeSetBase<GR> > Parent;
686 686

	
687 687
  public:
688 688

	
689 689
    typedef typename Parent::Node Node;
690 690
    typedef typename Parent::Arc Arc;
691 691
    typedef typename Parent::Edge Edge;
692 692

	
693 693
    typedef typename Parent::NodesImplBase NodesImplBase;
694 694

	
695 695
    void eraseNode(const Node& node) {
696 696
      Arc arc;
697 697
      Parent::firstOut(arc, node);
698 698
      while (arc != INVALID ) {
699 699
        erase(arc);
700 700
        Parent::firstOut(arc, node);
701 701
      }
702 702

	
703 703
    }
704 704

	
705 705
    void clearNodes() {
706 706
      Parent::clear();
707 707
    }
708 708

	
709 709
    class NodesImpl : public NodesImplBase {
710 710
      typedef NodesImplBase Parent;
711 711

	
712 712
    public:
713 713
      NodesImpl(const GR& graph, ListEdgeSet& arcset)
714 714
        : Parent(graph), _arcset(arcset) {}
715 715

	
716 716
      virtual ~NodesImpl() {}
717 717

	
718 718
    protected:
719 719

	
720 720
      virtual void erase(const Node& node) {
721 721
        _arcset.eraseNode(node);
722 722
        Parent::erase(node);
723 723
      }
724 724
      virtual void erase(const std::vector<Node>& nodes) {
725 725
        for (int i = 0; i < int(nodes.size()); ++i) {
726 726
          _arcset.eraseNode(nodes[i]);
727 727
        }
728 728
        Parent::erase(nodes);
729 729
      }
730 730
      virtual void clear() {
731 731
        _arcset.clearNodes();
732 732
        Parent::clear();
733 733
      }
734 734

	
735 735
    private:
736 736
      ListEdgeSet& _arcset;
737 737
    };
738 738

	
739 739
    NodesImpl _nodes;
740 740

	
741 741
  public:
742 742

	
743 743
    /// \brief Constructor of the EdgeSet.
744 744
    ///
745 745
    /// Constructor of the EdgeSet.
746 746
    ListEdgeSet(const GR& graph) : _nodes(graph, *this) {
747 747
      Parent::initalize(graph, _nodes);
748 748
    }
749 749

	
750 750
    /// \brief Add a new edge to the graph.
751 751
    ///
752 752
    /// Add a new edge to the graph with node \c u
753 753
    /// and node \c v endpoints.
754 754
    /// \return The new edge.
755 755
    Edge addEdge(const Node& u, const Node& v) {
756 756
      return Parent::addEdge(u, v);
757 757
    }
758 758

	
759 759
    /// \brief Erase an edge from the graph.
760 760
    ///
761 761
    /// Erase the edge \c e from the graph.
762 762
    void erase(const Edge& e) {
763 763
      return Parent::erase(e);
764 764
    }
765 765

	
766 766
  };
767 767

	
768 768
  template <typename GR>
769 769
  class SmartArcSetBase {
770 770
  public:
771 771

	
772 772
    typedef typename GR::Node Node;
773 773
    typedef typename GR::NodeIt NodeIt;
774 774

	
775 775
  protected:
776 776

	
777 777
    struct NodeT {
778 778
      int first_out, first_in;
779 779
      NodeT() : first_out(-1), first_in(-1) {}
780 780
    };
781 781

	
782 782
    typedef typename ItemSetTraits<GR, Node>::
783 783
    template Map<NodeT>::Type NodesImplBase;
784 784

	
785 785
    NodesImplBase* _nodes;
786 786

	
787 787
    struct ArcT {
788 788
      Node source, target;
789 789
      int next_out, next_in;
790 790
      ArcT() {}
791 791
    };
792 792

	
793 793
    std::vector<ArcT> arcs;
794 794

	
795 795
    const GR* _graph;
796 796

	
797 797
    void initalize(const GR& graph, NodesImplBase& nodes) {
798 798
      _graph = &graph;
799 799
      _nodes = &nodes;
800 800
    }
801 801

	
802 802
  public:
803 803

	
804 804
    class Arc {
805 805
      friend class SmartArcSetBase<GR>;
806 806
    protected:
807 807
      Arc(int _id) : id(_id) {}
808 808
      int id;
809 809
    public:
810 810
      Arc() {}
811 811
      Arc(Invalid) : id(-1) {}
812 812
      bool operator==(const Arc& arc) const { return id == arc.id; }
813 813
      bool operator!=(const Arc& arc) const { return id != arc.id; }
814 814
      bool operator<(const Arc& arc) const { return id < arc.id; }
815 815
    };
816 816

	
817 817
    SmartArcSetBase() {}
818 818

	
819 819
    Arc addArc(const Node& u, const Node& v) {
820 820
      int n = arcs.size();
821 821
      arcs.push_back(ArcT());
822 822
      arcs[n].next_in = (*_nodes)[v].first_in;
823 823
      (*_nodes)[v].first_in = n;
824 824
      arcs[n].next_out = (*_nodes)[u].first_out;
825 825
      (*_nodes)[u].first_out = n;
826 826
      arcs[n].source = u;
827 827
      arcs[n].target = v;
828 828
      return Arc(n);
829 829
    }
830 830

	
831 831
    void clear() {
832 832
      Node node;
833 833
      for (first(node); node != INVALID; next(node)) {
834 834
        (*_nodes)[node].first_in = -1;
835 835
        (*_nodes)[node].first_out = -1;
836 836
      }
837 837
      arcs.clear();
838 838
    }
839 839

	
840 840
    void first(Node& node) const {
841 841
      _graph->first(node);
842 842
    }
843 843

	
844 844
    void next(Node& node) const {
845 845
      _graph->next(node);
846 846
    }
847 847

	
848 848
    void first(Arc& arc) const {
849 849
      arc.id = arcs.size() - 1;
850 850
    }
851 851

	
852 852
    void next(Arc& arc) const {
853 853
      --arc.id;
854 854
    }
855 855

	
856 856
    void firstOut(Arc& arc, const Node& node) const {
857 857
      arc.id = (*_nodes)[node].first_out;
858 858
    }
859 859

	
860 860
    void nextOut(Arc& arc) const {
861 861
      arc.id = arcs[arc.id].next_out;
862 862
    }
863 863

	
864 864
    void firstIn(Arc& arc, const Node& node) const {
865 865
      arc.id = (*_nodes)[node].first_in;
866 866
    }
867 867

	
868 868
    void nextIn(Arc& arc) const {
869 869
      arc.id = arcs[arc.id].next_in;
870 870
    }
871 871

	
872 872
    int id(const Node& node) const { return _graph->id(node); }
873 873
    int id(const Arc& arc) const { return arc.id; }
874 874

	
875 875
    Node nodeFromId(int ix) const { return _graph->nodeFromId(ix); }
876 876
    Arc arcFromId(int ix) const { return Arc(ix); }
877 877

	
878 878
    int maxNodeId() const { return _graph->maxNodeId(); };
879 879
    int maxArcId() const { return arcs.size() - 1; }
880 880

	
881 881
    Node source(const Arc& arc) const { return arcs[arc.id].source;}
882 882
    Node target(const Arc& arc) const { return arcs[arc.id].target;}
883 883

	
884 884
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
885 885

	
886 886
    NodeNotifier& notifier(Node) const {
887 887
      return _graph->notifier(Node());
888 888
    }
889 889

	
890 890
    template <typename V>
891 891
    class NodeMap : public GR::template NodeMap<V> {
892 892
      typedef typename GR::template NodeMap<V> Parent;
893 893

	
894 894
    public:
895 895

	
896 896
      explicit NodeMap(const SmartArcSetBase<GR>& arcset)
897 897
        : Parent(*arcset._graph) { }
898 898

	
899 899
      NodeMap(const SmartArcSetBase<GR>& arcset, const V& value)
900 900
        : Parent(*arcset._graph, value) { }
901 901

	
902 902
      NodeMap& operator=(const NodeMap& cmap) {
903 903
        return operator=<NodeMap>(cmap);
904 904
      }
905 905

	
906 906
      template <typename CMap>
907 907
      NodeMap& operator=(const CMap& cmap) {
908 908
        Parent::operator=(cmap);
909 909
        return *this;
910 910
      }
911 911
    };
912 912

	
913 913
  };
914 914

	
915 915

	
916
  /// \ingroup semi_adaptors
916
  /// \ingroup graphs
917 917
  ///
918 918
  /// \brief Digraph using a node set of another digraph or graph and
919 919
  /// an own arc set.
920 920
  ///
921 921
  /// This structure can be used to establish another directed graph
922 922
  /// over a node set of an existing one. This class uses the same
923 923
  /// Node type as the underlying graph, and each valid node of the
924 924
  /// original graph is valid in this arc set, therefore the node
925 925
  /// objects of the original graph can be used directly with this
926 926
  /// class. The node handling functions (id handling, observing, and
927 927
  /// iterators) works equivalently as in the original graph.
928 928
  ///
929 929
  /// \param GR The type of the graph which shares its node set with
930 930
  /// this class. Its interface must conform to the
931 931
  /// \ref concepts::Digraph "Digraph" or \ref concepts::Graph "Graph"
932 932
  /// concept.
933 933
  ///
934 934
  /// This implementation is slightly faster than the \c ListArcSet,
935 935
  /// because it uses continuous storage for arcs and it uses just
936 936
  /// single-linked lists for enumerate outgoing and incoming
937 937
  /// arcs. Therefore the arcs cannot be erased from the arc sets.
938 938
  ///
939 939
  /// \warning If a node is erased from the underlying graph and this
940 940
  /// node is the source or target of one arc in the arc set, then
941 941
  /// the arc set is invalidated, and it cannot be used anymore. The
942 942
  /// validity can be checked with the \c valid() member function.
943 943
  ///
944 944
  /// This class fully conforms to the \ref concepts::Digraph
945 945
  /// "Digraph" concept.
946 946
  template <typename GR>
947 947
  class SmartArcSet : public ArcSetExtender<SmartArcSetBase<GR> > {
948 948
    typedef ArcSetExtender<SmartArcSetBase<GR> > Parent;
949 949

	
950 950
  public:
951 951

	
952 952
    typedef typename Parent::Node Node;
953 953
    typedef typename Parent::Arc Arc;
954 954

	
955 955
  protected:
956 956

	
957 957
    typedef typename Parent::NodesImplBase NodesImplBase;
958 958

	
959 959
    void eraseNode(const Node& node) {
960 960
      if (typename Parent::InArcIt(*this, node) == INVALID &&
961 961
          typename Parent::OutArcIt(*this, node) == INVALID) {
962 962
        return;
963 963
      }
964 964
      throw typename NodesImplBase::Notifier::ImmediateDetach();
965 965
    }
966 966

	
967 967
    void clearNodes() {
968 968
      Parent::clear();
969 969
    }
970 970

	
971 971
    class NodesImpl : public NodesImplBase {
972 972
      typedef NodesImplBase Parent;
973 973

	
974 974
    public:
975 975
      NodesImpl(const GR& graph, SmartArcSet& arcset)
976 976
        : Parent(graph), _arcset(arcset) {}
977 977

	
978 978
      virtual ~NodesImpl() {}
979 979

	
980 980
      bool attached() const {
981 981
        return Parent::attached();
982 982
      }
983 983

	
984 984
    protected:
985 985

	
986 986
      virtual void erase(const Node& node) {
987 987
        try {
988 988
          _arcset.eraseNode(node);
989 989
          Parent::erase(node);
990 990
        } catch (const typename NodesImplBase::Notifier::ImmediateDetach&) {
991 991
          Parent::clear();
992 992
          throw;
993 993
        }
994 994
      }
995 995
      virtual void erase(const std::vector<Node>& nodes) {
996 996
        try {
997 997
          for (int i = 0; i < int(nodes.size()); ++i) {
998 998
            _arcset.eraseNode(nodes[i]);
999 999
          }
1000 1000
          Parent::erase(nodes);
1001 1001
        } catch (const typename NodesImplBase::Notifier::ImmediateDetach&) {
1002 1002
          Parent::clear();
1003 1003
          throw;
1004 1004
        }
1005 1005
      }
1006 1006
      virtual void clear() {
1007 1007
        _arcset.clearNodes();
1008 1008
        Parent::clear();
1009 1009
      }
1010 1010

	
1011 1011
    private:
1012 1012
      SmartArcSet& _arcset;
1013 1013
    };
1014 1014

	
1015 1015
    NodesImpl _nodes;
1016 1016

	
1017 1017
  public:
1018 1018

	
1019 1019
    /// \brief Constructor of the ArcSet.
1020 1020
    ///
1021 1021
    /// Constructor of the ArcSet.
1022 1022
    SmartArcSet(const GR& graph) : _nodes(graph, *this) {
1023 1023
      Parent::initalize(graph, _nodes);
1024 1024
    }
1025 1025

	
1026 1026
    /// \brief Add a new arc to the digraph.
1027 1027
    ///
1028 1028
    /// Add a new arc to the digraph with source node \c s
1029 1029
    /// and target node \c t.
1030 1030
    /// \return The new arc.
1031 1031
    Arc addArc(const Node& s, const Node& t) {
1032 1032
      return Parent::addArc(s, t);
1033 1033
    }
1034 1034

	
1035 1035
    /// \brief Validity check
1036 1036
    ///
1037 1037
    /// This functions gives back false if the ArcSet is
1038 1038
    /// invalidated. It occurs when a node in the underlying graph is
1039 1039
    /// erased and it is not isolated in the ArcSet.
1040 1040
    bool valid() const {
1041 1041
      return _nodes.attached();
1042 1042
    }
1043 1043

	
1044 1044
  };
1045 1045

	
1046 1046

	
1047 1047
  template <typename GR>
1048 1048
  class SmartEdgeSetBase {
1049 1049
  public:
1050 1050

	
1051 1051
    typedef typename GR::Node Node;
1052 1052
    typedef typename GR::NodeIt NodeIt;
1053 1053

	
1054 1054
  protected:
1055 1055

	
1056 1056
    struct NodeT {
1057 1057
      int first_out;
1058 1058
      NodeT() : first_out(-1) {}
1059 1059
    };
1060 1060

	
1061 1061
    typedef typename ItemSetTraits<GR, Node>::
1062 1062
    template Map<NodeT>::Type NodesImplBase;
1063 1063

	
1064 1064
    NodesImplBase* _nodes;
1065 1065

	
1066 1066
    struct ArcT {
1067 1067
      Node target;
1068 1068
      int next_out;
1069 1069
      ArcT() {}
1070 1070
    };
1071 1071

	
1072 1072
    std::vector<ArcT> arcs;
1073 1073

	
1074 1074
    const GR* _graph;
1075 1075

	
1076 1076
    void initalize(const GR& graph, NodesImplBase& nodes) {
1077 1077
      _graph = &graph;
1078 1078
      _nodes = &nodes;
1079 1079
    }
1080 1080

	
1081 1081
  public:
1082 1082

	
1083 1083
    class Edge {
1084 1084
      friend class SmartEdgeSetBase;
1085 1085
    protected:
1086 1086

	
1087 1087
      int id;
1088 1088
      explicit Edge(int _id) { id = _id;}
1089 1089

	
1090 1090
    public:
1091 1091
      Edge() {}
1092 1092
      Edge (Invalid) { id = -1; }
1093 1093
      bool operator==(const Edge& arc) const {return id == arc.id;}
1094 1094
      bool operator!=(const Edge& arc) const {return id != arc.id;}
1095 1095
      bool operator<(const Edge& arc) const {return id < arc.id;}
1096 1096
    };
1097 1097

	
1098 1098
    class Arc {
1099 1099
      friend class SmartEdgeSetBase;
1100 1100
    protected:
1101 1101
      Arc(int _id) : id(_id) {}
1102 1102
      int id;
1103 1103
    public:
1104 1104
      operator Edge() const { return edgeFromId(id / 2); }
1105 1105

	
1106 1106
      Arc() {}
1107 1107
      Arc(Invalid) : id(-1) {}
1108 1108
      bool operator==(const Arc& arc) const { return id == arc.id; }
1109 1109
      bool operator!=(const Arc& arc) const { return id != arc.id; }
1110 1110
      bool operator<(const Arc& arc) const { return id < arc.id; }
1111 1111
    };
1112 1112

	
1113 1113
    SmartEdgeSetBase() {}
1114 1114

	
1115 1115
    Edge addEdge(const Node& u, const Node& v) {
1116 1116
      int n = arcs.size();
1117 1117
      arcs.push_back(ArcT());
1118 1118
      arcs.push_back(ArcT());
1119 1119

	
1120 1120
      arcs[n].target = u;
1121 1121
      arcs[n | 1].target = v;
1122 1122

	
1123 1123
      arcs[n].next_out = (*_nodes)[v].first_out;
1124 1124
      (*_nodes)[v].first_out = n;
1125 1125

	
1126 1126
      arcs[n | 1].next_out = (*_nodes)[u].first_out;
1127 1127
      (*_nodes)[u].first_out = (n | 1);
1128 1128

	
1129 1129
      return Edge(n / 2);
1130 1130
    }
1131 1131

	
1132 1132
    void clear() {
1133 1133
      Node node;
1134 1134
      for (first(node); node != INVALID; next(node)) {
1135 1135
        (*_nodes)[node].first_out = -1;
1136 1136
      }
1137 1137
      arcs.clear();
1138 1138
    }
1139 1139

	
1140 1140
    void first(Node& node) const {
1141 1141
      _graph->first(node);
1142 1142
    }
1143 1143

	
1144 1144
    void next(Node& node) const {
1145 1145
      _graph->next(node);
1146 1146
    }
1147 1147

	
1148 1148
    void first(Arc& arc) const {
1149 1149
      arc.id = arcs.size() - 1;
1150 1150
    }
1151 1151

	
1152 1152
    void next(Arc& arc) const {
1153 1153
      --arc.id;
1154 1154
    }
1155 1155

	
1156 1156
    void first(Edge& arc) const {
1157 1157
      arc.id = arcs.size() / 2 - 1;
1158 1158
    }
1159 1159

	
1160 1160
    void next(Edge& arc) const {
1161 1161
      --arc.id;
1162 1162
    }
1163 1163

	
1164 1164
    void firstOut(Arc& arc, const Node& node) const {
1165 1165
      arc.id = (*_nodes)[node].first_out;
1166 1166
    }
1167 1167

	
1168 1168
    void nextOut(Arc& arc) const {
1169 1169
      arc.id = arcs[arc.id].next_out;
1170 1170
    }
1171 1171

	
1172 1172
    void firstIn(Arc& arc, const Node& node) const {
1173 1173
      arc.id = (((*_nodes)[node].first_out) ^ 1);
1174 1174
      if (arc.id == -2) arc.id = -1;
1175 1175
    }
1176 1176

	
1177 1177
    void nextIn(Arc& arc) const {
1178 1178
      arc.id = ((arcs[arc.id ^ 1].next_out) ^ 1);
1179 1179
      if (arc.id == -2) arc.id = -1;
1180 1180
    }
1181 1181

	
1182 1182
    void firstInc(Edge &arc, bool& dir, const Node& node) const {
1183 1183
      int de = (*_nodes)[node].first_out;
1184 1184
      if (de != -1 ) {
1185 1185
        arc.id = de / 2;
1186 1186
        dir = ((de & 1) == 1);
1187 1187
      } else {
1188 1188
        arc.id = -1;
1189 1189
        dir = true;
1190 1190
      }
1191 1191
    }
1192 1192
    void nextInc(Edge &arc, bool& dir) const {
1193 1193
      int de = (arcs[(arc.id * 2) | (dir ? 1 : 0)].next_out);
1194 1194
      if (de != -1 ) {
1195 1195
        arc.id = de / 2;
1196 1196
        dir = ((de & 1) == 1);
1197 1197
      } else {
1198 1198
        arc.id = -1;
1199 1199
        dir = true;
1200 1200
      }
1201 1201
    }
1202 1202

	
1203 1203
    static bool direction(Arc arc) {
1204 1204
      return (arc.id & 1) == 1;
1205 1205
    }
1206 1206

	
1207 1207
    static Arc direct(Edge edge, bool dir) {
1208 1208
      return Arc(edge.id * 2 + (dir ? 1 : 0));
1209 1209
    }
1210 1210

	
1211 1211
    int id(Node node) const { return _graph->id(node); }
1212 1212
    static int id(Arc arc) { return arc.id; }
1213 1213
    static int id(Edge arc) { return arc.id; }
1214 1214

	
1215 1215
    Node nodeFromId(int id) const { return _graph->nodeFromId(id); }
1216 1216
    static Arc arcFromId(int id) { return Arc(id); }
1217 1217
    static Edge edgeFromId(int id) { return Edge(id);}
1218 1218

	
1219 1219
    int maxNodeId() const { return _graph->maxNodeId(); };
1220 1220
    int maxArcId() const { return arcs.size() - 1; }
1221 1221
    int maxEdgeId() const { return arcs.size() / 2 - 1; }
1222 1222

	
1223 1223
    Node source(Arc e) const { return arcs[e.id ^ 1].target; }
1224 1224
    Node target(Arc e) const { return arcs[e.id].target; }
1225 1225

	
1226 1226
    Node u(Edge e) const { return arcs[2 * e.id].target; }
1227 1227
    Node v(Edge e) const { return arcs[2 * e.id + 1].target; }
1228 1228

	
1229 1229
    typedef typename ItemSetTraits<GR, Node>::ItemNotifier NodeNotifier;
1230 1230

	
1231 1231
    NodeNotifier& notifier(Node) const {
1232 1232
      return _graph->notifier(Node());
1233 1233
    }
1234 1234

	
1235 1235
    template <typename V>
1236 1236
    class NodeMap : public GR::template NodeMap<V> {
1237 1237
      typedef typename GR::template NodeMap<V> Parent;
1238 1238

	
1239 1239
    public:
1240 1240

	
1241 1241
      explicit NodeMap(const SmartEdgeSetBase<GR>& arcset)
1242 1242
        : Parent(*arcset._graph) { }
1243 1243

	
1244 1244
      NodeMap(const SmartEdgeSetBase<GR>& arcset, const V& value)
1245 1245
        : Parent(*arcset._graph, value) { }
1246 1246

	
1247 1247
      NodeMap& operator=(const NodeMap& cmap) {
1248 1248
        return operator=<NodeMap>(cmap);
1249 1249
      }
1250 1250

	
1251 1251
      template <typename CMap>
1252 1252
      NodeMap& operator=(const CMap& cmap) {
1253 1253
        Parent::operator=(cmap);
1254 1254
        return *this;
1255 1255
      }
1256 1256
    };
1257 1257

	
1258 1258
  };
1259 1259

	
1260
  /// \ingroup semi_adaptors
1260
  /// \ingroup graphs
1261 1261
  ///
1262 1262
  /// \brief Graph using a node set of another digraph or graph and an
1263 1263
  /// own edge set.
1264 1264
  ///
1265 1265
  /// This structure can be used to establish another graph over a
1266 1266
  /// node set of an existing one. This class uses the same Node type
1267 1267
  /// as the underlying graph, and each valid node of the original
1268 1268
  /// graph is valid in this arc set, therefore the node objects of
1269 1269
  /// the original graph can be used directly with this class. The
1270 1270
  /// node handling functions (id handling, observing, and iterators)
1271 1271
  /// works equivalently as in the original graph.
1272 1272
  ///
1273 1273
  /// \param GR The type of the graph which shares its node set
1274 1274
  /// with this class. Its interface must conform to the
1275 1275
  /// \ref concepts::Digraph "Digraph" or \ref concepts::Graph "Graph"
1276 1276
  ///  concept.
1277 1277
  ///
1278 1278
  /// This implementation is slightly faster than the \c ListEdgeSet,
1279 1279
  /// because it uses continuous storage for edges and it uses just
1280 1280
  /// single-linked lists for enumerate incident edges. Therefore the
1281 1281
  /// edges cannot be erased from the edge sets.
1282 1282
  ///
1283 1283
  /// \warning If a node is erased from the underlying graph and this
1284 1284
  /// node is incident to one edge in the edge set, then the edge set
1285 1285
  /// is invalidated, and it cannot be used anymore. The validity can
1286 1286
  /// be checked with the \c valid() member function.
1287 1287
  ///
1288 1288
  /// This class fully conforms to the \ref concepts::Graph
1289 1289
  /// "Graph" concept.
1290 1290
  template <typename GR>
1291 1291
  class SmartEdgeSet : public EdgeSetExtender<SmartEdgeSetBase<GR> > {
1292 1292
    typedef EdgeSetExtender<SmartEdgeSetBase<GR> > Parent;
1293 1293

	
1294 1294
  public:
1295 1295

	
1296 1296
    typedef typename Parent::Node Node;
1297 1297
    typedef typename Parent::Arc Arc;
1298 1298
    typedef typename Parent::Edge Edge;
1299 1299

	
1300 1300
  protected:
1301 1301

	
1302 1302
    typedef typename Parent::NodesImplBase NodesImplBase;
1303 1303

	
1304 1304
    void eraseNode(const Node& node) {
1305 1305
      if (typename Parent::IncEdgeIt(*this, node) == INVALID) {
1306 1306
        return;
1307 1307
      }
1308 1308
      throw typename NodesImplBase::Notifier::ImmediateDetach();
1309 1309
    }
1310 1310

	
1311 1311
    void clearNodes() {
1312 1312
      Parent::clear();
1313 1313
    }
1314 1314

	
1315 1315
    class NodesImpl : public NodesImplBase {
1316 1316
      typedef NodesImplBase Parent;
1317 1317

	
1318 1318
    public:
1319 1319
      NodesImpl(const GR& graph, SmartEdgeSet& arcset)
1320 1320
        : Parent(graph), _arcset(arcset) {}
1321 1321

	
1322 1322
      virtual ~NodesImpl() {}
1323 1323

	
1324 1324
      bool attached() const {
1325 1325
        return Parent::attached();
1326 1326
      }
1327 1327

	
1328 1328
    protected:
1329 1329

	
1330 1330
      virtual void erase(const Node& node) {
1331 1331
        try {
1332 1332
          _arcset.eraseNode(node);
1333 1333
          Parent::erase(node);
1334 1334
        } catch (const typename NodesImplBase::Notifier::ImmediateDetach&) {
1335 1335
          Parent::clear();
1336 1336
          throw;
1337 1337
        }
1338 1338
      }
1339 1339
      virtual void erase(const std::vector<Node>& nodes) {
1340 1340
        try {
1341 1341
          for (int i = 0; i < int(nodes.size()); ++i) {
1342 1342
            _arcset.eraseNode(nodes[i]);
1343 1343
          }
1344 1344
          Parent::erase(nodes);
1345 1345
        } catch (const typename NodesImplBase::Notifier::ImmediateDetach&) {
1346 1346
          Parent::clear();
1347 1347
          throw;
1348 1348
        }
1349 1349
      }
1350 1350
      virtual void clear() {
1351 1351
        _arcset.clearNodes();
1352 1352
        Parent::clear();
1353 1353
      }
1354 1354

	
1355 1355
    private:
1356 1356
      SmartEdgeSet& _arcset;
1357 1357
    };
1358 1358

	
1359 1359
    NodesImpl _nodes;
1360 1360

	
1361 1361
  public:
1362 1362

	
1363 1363
    /// \brief Constructor of the EdgeSet.
1364 1364
    ///
1365 1365
    /// Constructor of the EdgeSet.
1366 1366
    SmartEdgeSet(const GR& graph) : _nodes(graph, *this) {
1367 1367
      Parent::initalize(graph, _nodes);
1368 1368
    }
1369 1369

	
1370 1370
    /// \brief Add a new edge to the graph.
1371 1371
    ///
1372 1372
    /// Add a new edge to the graph with node \c u
1373 1373
    /// and node \c v endpoints.
1374 1374
    /// \return The new edge.
1375 1375
    Edge addEdge(const Node& u, const Node& v) {
1376 1376
      return Parent::addEdge(u, v);
1377 1377
    }
1378 1378

	
1379 1379
    /// \brief Validity check
1380 1380
    ///
1381 1381
    /// This functions gives back false if the EdgeSet is
1382 1382
    /// invalidated. It occurs when a node in the underlying graph is
1383 1383
    /// erased and it is not isolated in the EdgeSet.
1384 1384
    bool valid() const {
1385 1385
      return _nodes.attached();
1386 1386
    }
1387 1387

	
1388 1388
  };
1389 1389

	
1390 1390
}
1391 1391

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

	
19 19
#ifndef LEMON_EULER_H
20 20
#define LEMON_EULER_H
21 21

	
22 22
#include<lemon/core.h>
23 23
#include<lemon/adaptors.h>
24 24
#include<lemon/connectivity.h>
25 25
#include <list>
26 26

	
27 27
/// \ingroup graph_properties
28 28
/// \file
29 29
/// \brief Euler tour iterators and a function for checking the \e Eulerian 
30 30
/// property.
31 31
///
32 32
///This file provides Euler tour iterators and a function to check
33 33
///if a (di)graph is \e Eulerian.
34 34

	
35 35
namespace lemon {
36 36

	
37 37
  ///Euler tour iterator for digraphs.
38 38

	
39 39
  /// \ingroup graph_prop
40 40
  ///This iterator provides an Euler tour (Eulerian circuit) of a \e directed
41 41
  ///graph (if there exists) and it converts to the \c Arc type of the digraph.
42 42
  ///
43 43
  ///For example, if the given digraph has an Euler tour (i.e it has only one
44 44
  ///non-trivial component and the in-degree is equal to the out-degree 
45 45
  ///for all nodes), then the following code will put the arcs of \c g
46 46
  ///to the vector \c et according to an Euler tour of \c g.
47 47
  ///\code
48 48
  ///  std::vector<ListDigraph::Arc> et;
49 49
  ///  for(DiEulerIt<ListDigraph> e(g); e!=INVALID; ++e)
50 50
  ///    et.push_back(e);
51 51
  ///\endcode
52 52
  ///If \c g has no Euler tour, then the resulted walk will not be closed
53 53
  ///or not contain all arcs.
54 54
  ///\sa EulerIt
55 55
  template<typename GR>
56 56
  class DiEulerIt
57 57
  {
58 58
    typedef typename GR::Node Node;
59 59
    typedef typename GR::NodeIt NodeIt;
60 60
    typedef typename GR::Arc Arc;
61 61
    typedef typename GR::ArcIt ArcIt;
62 62
    typedef typename GR::OutArcIt OutArcIt;
63 63
    typedef typename GR::InArcIt InArcIt;
64 64

	
65 65
    const GR &g;
66 66
    typename GR::template NodeMap<OutArcIt> narc;
67 67
    std::list<Arc> euler;
68 68

	
69 69
  public:
70 70

	
71 71
    ///Constructor
72 72

	
73 73
    ///Constructor.
74 74
    ///\param gr A digraph.
75 75
    ///\param start The starting point of the tour. If it is not given,
76 76
    ///the tour will start from the first node that has an outgoing arc.
77 77
    DiEulerIt(const GR &gr, typename GR::Node start = INVALID)
78 78
      : g(gr), narc(g)
79 79
    {
80 80
      if (start==INVALID) {
81 81
        NodeIt n(g);
82 82
        while (n!=INVALID && OutArcIt(g,n)==INVALID) ++n;
83 83
        start=n;
84 84
      }
85 85
      if (start!=INVALID) {
86 86
        for (NodeIt n(g); n!=INVALID; ++n) narc[n]=OutArcIt(g,n);
87 87
        while (narc[start]!=INVALID) {
88 88
          euler.push_back(narc[start]);
89 89
          Node next=g.target(narc[start]);
90 90
          ++narc[start];
91 91
          start=next;
92 92
        }
93 93
      }
94 94
    }
95 95

	
96 96
    ///Arc conversion
97 97
    operator Arc() { return euler.empty()?INVALID:euler.front(); }
98 98
    ///Compare with \c INVALID
99 99
    bool operator==(Invalid) { return euler.empty(); }
100 100
    ///Compare with \c INVALID
101 101
    bool operator!=(Invalid) { return !euler.empty(); }
102 102

	
103 103
    ///Next arc of the tour
104 104

	
105 105
    ///Next arc of the tour
106 106
    ///
107 107
    DiEulerIt &operator++() {
108 108
      Node s=g.target(euler.front());
109 109
      euler.pop_front();
110 110
      typename std::list<Arc>::iterator next=euler.begin();
111 111
      while(narc[s]!=INVALID) {
112 112
        euler.insert(next,narc[s]);
113 113
        Node n=g.target(narc[s]);
114 114
        ++narc[s];
115 115
        s=n;
116 116
      }
117 117
      return *this;
118 118
    }
119 119
    ///Postfix incrementation
120 120

	
121 121
    /// Postfix incrementation.
122 122
    ///
123 123
    ///\warning This incrementation
124 124
    ///returns an \c Arc, not a \ref DiEulerIt, as one may
125 125
    ///expect.
126 126
    Arc operator++(int)
127 127
    {
128 128
      Arc e=*this;
129 129
      ++(*this);
130 130
      return e;
131 131
    }
132 132
  };
133 133

	
134 134
  ///Euler tour iterator for graphs.
135 135

	
136 136
  /// \ingroup graph_properties
137 137
  ///This iterator provides an Euler tour (Eulerian circuit) of an
138 138
  ///\e undirected graph (if there exists) and it converts to the \c Arc
139 139
  ///and \c Edge types of the graph.
140 140
  ///
141 141
  ///For example, if the given graph has an Euler tour (i.e it has only one 
142 142
  ///non-trivial component and the degree of each node is even),
143 143
  ///the following code will print the arc IDs according to an
144 144
  ///Euler tour of \c g.
145 145
  ///\code
146 146
  ///  for(EulerIt<ListGraph> e(g); e!=INVALID; ++e) {
147 147
  ///    std::cout << g.id(Edge(e)) << std::eol;
148 148
  ///  }
149 149
  ///\endcode
150 150
  ///Although this iterator is for undirected graphs, it still returns 
151 151
  ///arcs in order to indicate the direction of the tour.
152 152
  ///(But arcs convert to edges, of course.)
153 153
  ///
154 154
  ///If \c g has no Euler tour, then the resulted walk will not be closed
155 155
  ///or not contain all edges.
156 156
  template<typename GR>
157 157
  class EulerIt
158 158
  {
159 159
    typedef typename GR::Node Node;
160 160
    typedef typename GR::NodeIt NodeIt;
161 161
    typedef typename GR::Arc Arc;
162 162
    typedef typename GR::Edge Edge;
163 163
    typedef typename GR::ArcIt ArcIt;
164 164
    typedef typename GR::OutArcIt OutArcIt;
165 165
    typedef typename GR::InArcIt InArcIt;
166 166

	
167 167
    const GR &g;
168 168
    typename GR::template NodeMap<OutArcIt> narc;
169 169
    typename GR::template EdgeMap<bool> visited;
170 170
    std::list<Arc> euler;
171 171

	
172 172
  public:
173 173

	
174 174
    ///Constructor
175 175

	
176 176
    ///Constructor.
177 177
    ///\param gr A graph.
178 178
    ///\param start The starting point of the tour. If it is not given,
179 179
    ///the tour will start from the first node that has an incident edge.
180 180
    EulerIt(const GR &gr, typename GR::Node start = INVALID)
181 181
      : g(gr), narc(g), visited(g, false)
182 182
    {
183 183
      if (start==INVALID) {
184 184
        NodeIt n(g);
185 185
        while (n!=INVALID && OutArcIt(g,n)==INVALID) ++n;
186 186
        start=n;
187 187
      }
188 188
      if (start!=INVALID) {
189 189
        for (NodeIt n(g); n!=INVALID; ++n) narc[n]=OutArcIt(g,n);
190 190
        while(narc[start]!=INVALID) {
191 191
          euler.push_back(narc[start]);
192 192
          visited[narc[start]]=true;
193 193
          Node next=g.target(narc[start]);
194 194
          ++narc[start];
195 195
          start=next;
196 196
          while(narc[start]!=INVALID && visited[narc[start]]) ++narc[start];
197 197
        }
198 198
      }
199 199
    }
200 200

	
201 201
    ///Arc conversion
202 202
    operator Arc() const { return euler.empty()?INVALID:euler.front(); }
203 203
    ///Edge conversion
204 204
    operator Edge() const { return euler.empty()?INVALID:euler.front(); }
205 205
    ///Compare with \c INVALID
206 206
    bool operator==(Invalid) const { return euler.empty(); }
207 207
    ///Compare with \c INVALID
208 208
    bool operator!=(Invalid) const { return !euler.empty(); }
209 209

	
210 210
    ///Next arc of the tour
211 211

	
212 212
    ///Next arc of the tour
213 213
    ///
214 214
    EulerIt &operator++() {
215 215
      Node s=g.target(euler.front());
216 216
      euler.pop_front();
217 217
      typename std::list<Arc>::iterator next=euler.begin();
218 218
      while(narc[s]!=INVALID) {
219 219
        while(narc[s]!=INVALID && visited[narc[s]]) ++narc[s];
220 220
        if(narc[s]==INVALID) break;
221 221
        else {
222 222
          euler.insert(next,narc[s]);
223 223
          visited[narc[s]]=true;
224 224
          Node n=g.target(narc[s]);
225 225
          ++narc[s];
226 226
          s=n;
227 227
        }
228 228
      }
229 229
      return *this;
230 230
    }
231 231

	
232 232
    ///Postfix incrementation
233 233

	
234 234
    /// Postfix incrementation.
235 235
    ///
236 236
    ///\warning This incrementation returns an \c Arc (which converts to 
237 237
    ///an \c Edge), not an \ref EulerIt, as one may expect.
238 238
    Arc operator++(int)
239 239
    {
240 240
      Arc e=*this;
241 241
      ++(*this);
242 242
      return e;
243 243
    }
244 244
  };
245 245

	
246 246

	
247
  ///Check if the given graph is \e Eulerian
247
  ///Check if the given graph is Eulerian
248 248

	
249 249
  /// \ingroup graph_properties
250
  ///This function checks if the given graph is \e Eulerian.
250
  ///This function checks if the given graph is Eulerian.
251 251
  ///It works for both directed and undirected graphs.
252 252
  ///
253 253
  ///By definition, a digraph is called \e Eulerian if
254 254
  ///and only if it is connected and the number of incoming and outgoing
255 255
  ///arcs are the same for each node.
256 256
  ///Similarly, an undirected graph is called \e Eulerian if
257 257
  ///and only if it is connected and the number of incident edges is even
258 258
  ///for each node.
259 259
  ///
260 260
  ///\note There are (di)graphs that are not Eulerian, but still have an
261 261
  /// Euler tour, since they may contain isolated nodes.
262 262
  ///
263 263
  ///\sa DiEulerIt, EulerIt
264 264
  template<typename GR>
265 265
#ifdef DOXYGEN
266 266
  bool
267 267
#else
268 268
  typename enable_if<UndirectedTagIndicator<GR>,bool>::type
269 269
  eulerian(const GR &g)
270 270
  {
271 271
    for(typename GR::NodeIt n(g);n!=INVALID;++n)
272 272
      if(countIncEdges(g,n)%2) return false;
273 273
    return connected(g);
274 274
  }
275 275
  template<class GR>
276 276
  typename disable_if<UndirectedTagIndicator<GR>,bool>::type
277 277
#endif
278 278
  eulerian(const GR &g)
279 279
  {
280 280
    for(typename GR::NodeIt n(g);n!=INVALID;++n)
281 281
      if(countInArcs(g,n)!=countOutArcs(g,n)) return false;
282 282
    return connected(undirector(g));
283 283
  }
284 284

	
285 285
}
286 286

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

	
19 19
#ifndef LEMON_GLPK_H
20 20
#define LEMON_GLPK_H
21 21

	
22 22
///\file
23 23
///\brief Header of the LEMON-GLPK lp solver interface.
24 24
///\ingroup lp_group
25 25

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

	
28 28
// forward declaration
29
#ifndef _GLP_PROB
29
#if !defined _GLP_PROB && !defined GLP_PROB
30 30
#define _GLP_PROB
31
typedef struct { double _prob; } glp_prob;
31
#define GLP_PROB
32
typedef struct { double _opaque_prob; } glp_prob;
32 33
/* LP/MIP problem object */
33 34
#endif
34 35

	
35 36
namespace lemon {
36 37

	
37 38

	
38 39
  /// \brief Base interface for the GLPK LP and MIP solver
39 40
  ///
40 41
  /// This class implements the common interface of the GLPK LP and MIP solver.
41 42
  /// \ingroup lp_group
42 43
  class GlpkBase : virtual public LpBase {
43 44
  protected:
44 45

	
45 46
    typedef glp_prob LPX;
46 47
    glp_prob* lp;
47 48

	
48 49
    GlpkBase();
49 50
    GlpkBase(const GlpkBase&);
50 51
    virtual ~GlpkBase();
51 52

	
52 53
  protected:
53 54

	
54 55
    virtual int _addCol();
55 56
    virtual int _addRow();
56 57

	
57 58
    virtual void _eraseCol(int i);
58 59
    virtual void _eraseRow(int i);
59 60

	
60 61
    virtual void _eraseColId(int i);
61 62
    virtual void _eraseRowId(int i);
62 63

	
63 64
    virtual void _getColName(int col, std::string& name) const;
64 65
    virtual void _setColName(int col, const std::string& name);
65 66
    virtual int _colByName(const std::string& name) const;
66 67

	
67 68
    virtual void _getRowName(int row, std::string& name) const;
68 69
    virtual void _setRowName(int row, const std::string& name);
69 70
    virtual int _rowByName(const std::string& name) const;
70 71

	
71 72
    virtual void _setRowCoeffs(int i, ExprIterator b, ExprIterator e);
72 73
    virtual void _getRowCoeffs(int i, InsertIterator b) const;
73 74

	
74 75
    virtual void _setColCoeffs(int i, ExprIterator b, ExprIterator e);
75 76
    virtual void _getColCoeffs(int i, InsertIterator b) const;
76 77

	
77 78
    virtual void _setCoeff(int row, int col, Value value);
78 79
    virtual Value _getCoeff(int row, int col) const;
79 80

	
80 81
    virtual void _setColLowerBound(int i, Value value);
81 82
    virtual Value _getColLowerBound(int i) const;
82 83

	
83 84
    virtual void _setColUpperBound(int i, Value value);
84 85
    virtual Value _getColUpperBound(int i) const;
85 86

	
86 87
    virtual void _setRowLowerBound(int i, Value value);
87 88
    virtual Value _getRowLowerBound(int i) const;
88 89

	
89 90
    virtual void _setRowUpperBound(int i, Value value);
90 91
    virtual Value _getRowUpperBound(int i) const;
91 92

	
92 93
    virtual void _setObjCoeffs(ExprIterator b, ExprIterator e);
93 94
    virtual void _getObjCoeffs(InsertIterator b) const;
94 95

	
95 96
    virtual void _setObjCoeff(int i, Value obj_coef);
96 97
    virtual Value _getObjCoeff(int i) const;
97 98

	
98 99
    virtual void _setSense(Sense);
99 100
    virtual Sense _getSense() const;
100 101

	
101 102
    virtual void _clear();
102 103

	
103 104
    virtual void _messageLevel(MessageLevel level);
104 105

	
105 106
  private:
106 107

	
107 108
    static void freeEnv();
108 109

	
109 110
    struct FreeEnvHelper {
110 111
      ~FreeEnvHelper() {
111 112
        freeEnv();
112 113
      }
113 114
    };
114 115
    
115 116
    static FreeEnvHelper freeEnvHelper;
116 117

	
117 118
  protected:
118 119
    
119 120
    int _message_level;
120 121
    
121 122
  public:
122 123

	
123 124
    ///Pointer to the underlying GLPK data structure.
124 125
    LPX *lpx() {return lp;}
125 126
    ///Const pointer to the underlying GLPK data structure.
126 127
    const LPX *lpx() const {return lp;}
127 128

	
128 129
    ///Returns the constraint identifier understood by GLPK.
129 130
    int lpxRow(Row r) const { return rows(id(r)); }
130 131

	
131 132
    ///Returns the variable identifier understood by GLPK.
132 133
    int lpxCol(Col c) const { return cols(id(c)); }
133 134

	
134 135
  };
135 136

	
136 137
  /// \brief Interface for the GLPK LP solver
137 138
  ///
138 139
  /// This class implements an interface for the GLPK LP solver.
139 140
  ///\ingroup lp_group
140 141
  class GlpkLp : public LpSolver, public GlpkBase {
141 142
  public:
142 143

	
143 144
    ///\e
144 145
    GlpkLp();
145 146
    ///\e
146 147
    GlpkLp(const GlpkLp&);
147 148

	
148 149
    ///\e
149 150
    virtual GlpkLp* cloneSolver() const;
150 151
    ///\e
151 152
    virtual GlpkLp* newSolver() const;
152 153

	
153 154
  private:
154 155

	
155 156
    mutable std::vector<double> _primal_ray;
156 157
    mutable std::vector<double> _dual_ray;
157 158

	
158 159
    void _clear_temporals();
159 160

	
160 161
  protected:
161 162

	
162 163
    virtual const char* _solverName() const;
163 164

	
164 165
    virtual SolveExitStatus _solve();
165 166
    virtual Value _getPrimal(int i) const;
166 167
    virtual Value _getDual(int i) const;
167 168

	
168 169
    virtual Value _getPrimalValue() const;
169 170

	
170 171
    virtual VarStatus _getColStatus(int i) const;
171 172
    virtual VarStatus _getRowStatus(int i) const;
172 173

	
173 174
    virtual Value _getPrimalRay(int i) const;
174 175
    virtual Value _getDualRay(int i) const;
175 176

	
176 177
    virtual ProblemType _getPrimalType() const;
177 178
    virtual ProblemType _getDualType() const;
178 179

	
179 180
  public:
180 181

	
181 182
    ///Solve with primal simplex
182 183
    SolveExitStatus solvePrimal();
183 184

	
184 185
    ///Solve with dual simplex
185 186
    SolveExitStatus solveDual();
186 187

	
187 188
  private:
188 189

	
189 190
    bool _presolve;
190 191

	
191 192
  public:
192 193

	
193 194
    ///Turns on or off the presolver
194 195

	
195 196
    ///Turns on (\c b is \c true) or off (\c b is \c false) the presolver
196 197
    ///
197 198
    ///The presolver is off by default.
198 199
    void presolver(bool presolve);
199 200

	
200 201
  };
201 202

	
202 203
  /// \brief Interface for the GLPK MIP solver
203 204
  ///
204 205
  /// This class implements an interface for the GLPK MIP solver.
205 206
  ///\ingroup lp_group
206 207
  class GlpkMip : public MipSolver, public GlpkBase {
207 208
  public:
208 209

	
209 210
    ///\e
210 211
    GlpkMip();
211 212
    ///\e
212 213
    GlpkMip(const GlpkMip&);
213 214

	
214 215
    virtual GlpkMip* cloneSolver() const;
215 216
    virtual GlpkMip* newSolver() const;
216 217

	
217 218
  protected:
218 219

	
219 220
    virtual const char* _solverName() const;
220 221

	
221 222
    virtual ColTypes _getColType(int col) const;
222 223
    virtual void _setColType(int col, ColTypes col_type);
223 224

	
224 225
    virtual SolveExitStatus _solve();
225 226
    virtual ProblemType _getType() const;
226 227
    virtual Value _getSol(int i) const;
227 228
    virtual Value _getSolValue() const;
228 229

	
229 230
  };
230 231

	
231 232

	
232 233
} //END OF NAMESPACE LEMON
233 234

	
234 235
#endif //LEMON_GLPK_H
235 236

	
Ignore white space 6 line context
1 1
prefix=@prefix@
2 2
exec_prefix=@exec_prefix@
3 3
libdir=@libdir@
4 4
includedir=@includedir@
5 5

	
6 6
Name: @PACKAGE_NAME@
7
Description: Library of Efficient Models and Optimization in Networks
7
Description: Library for Efficient Modeling and Optimization in Networks
8 8
Version: @PACKAGE_VERSION@
9 9
Libs: -L${libdir} -lemon @GLPK_LIBS@ @CPLEX_LIBS@ @SOPLEX_LIBS@ @CLP_LIBS@ @CBC_LIBS@
10 10
Cflags: -I${includedir}
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_MAX_MATCHING_H
20 20
#define LEMON_MAX_MATCHING_H
21 21

	
22 22
#include <vector>
23 23
#include <queue>
24 24
#include <set>
25 25
#include <limits>
26 26

	
27 27
#include <lemon/core.h>
28 28
#include <lemon/unionfind.h>
29 29
#include <lemon/bin_heap.h>
30 30
#include <lemon/maps.h>
31 31

	
32 32
///\ingroup matching
33 33
///\file
34 34
///\brief Maximum matching algorithms in general graphs.
35 35

	
36 36
namespace lemon {
37 37

	
38 38
  /// \ingroup matching
39 39
  ///
40 40
  /// \brief Maximum cardinality matching in general graphs
41 41
  ///
42 42
  /// This class implements Edmonds' alternating forest matching algorithm
43 43
  /// for finding a maximum cardinality matching in a general undirected graph.
44 44
  /// It can be started from an arbitrary initial matching 
45 45
  /// (the default is the empty one).
46 46
  ///
47 47
  /// The dual solution of the problem is a map of the nodes to
48 48
  /// \ref MaxMatching::Status "Status", having values \c EVEN (or \c D),
49 49
  /// \c ODD (or \c A) and \c MATCHED (or \c C) defining the Gallai-Edmonds
50 50
  /// decomposition of the graph. The nodes in \c EVEN/D induce a subgraph
51 51
  /// with factor-critical components, the nodes in \c ODD/A form the
52 52
  /// canonical barrier, and the nodes in \c MATCHED/C induce a graph having
53 53
  /// a perfect matching. The number of the factor-critical components
54 54
  /// minus the number of barrier nodes is a lower bound on the
55 55
  /// unmatched nodes, and the matching is optimal if and only if this bound is
56 56
  /// tight. This decomposition can be obtained using \ref status() or
57 57
  /// \ref statusMap() after running the algorithm.
58 58
  ///
59 59
  /// \tparam GR The undirected graph type the algorithm runs on.
60 60
  template <typename GR>
61 61
  class MaxMatching {
62 62
  public:
63 63

	
64 64
    /// The graph type of the algorithm
65 65
    typedef GR Graph;
66 66
    /// The type of the matching map
67 67
    typedef typename Graph::template NodeMap<typename Graph::Arc>
68 68
    MatchingMap;
69 69

	
70 70
    ///\brief Status constants for Gallai-Edmonds decomposition.
71 71
    ///
72 72
    ///These constants are used for indicating the Gallai-Edmonds 
73 73
    ///decomposition of a graph. The nodes with status \c EVEN (or \c D)
74 74
    ///induce a subgraph with factor-critical components, the nodes with
75 75
    ///status \c ODD (or \c A) form the canonical barrier, and the nodes
76 76
    ///with status \c MATCHED (or \c C) induce a subgraph having a 
77 77
    ///perfect matching.
78 78
    enum Status {
79 79
      EVEN = 1,       ///< = 1. (\c D is an alias for \c EVEN.)
80 80
      D = 1,
81 81
      MATCHED = 0,    ///< = 0. (\c C is an alias for \c MATCHED.)
82 82
      C = 0,
83 83
      ODD = -1,       ///< = -1. (\c A is an alias for \c ODD.)
84 84
      A = -1,
85 85
      UNMATCHED = -2  ///< = -2.
86 86
    };
87 87

	
88 88
    /// The type of the status map
89 89
    typedef typename Graph::template NodeMap<Status> StatusMap;
90 90

	
91 91
  private:
92 92

	
93 93
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
94 94

	
95 95
    typedef UnionFindEnum<IntNodeMap> BlossomSet;
96 96
    typedef ExtendFindEnum<IntNodeMap> TreeSet;
97 97
    typedef RangeMap<Node> NodeIntMap;
98 98
    typedef MatchingMap EarMap;
99 99
    typedef std::vector<Node> NodeQueue;
100 100

	
101 101
    const Graph& _graph;
102 102
    MatchingMap* _matching;
103 103
    StatusMap* _status;
104 104

	
105 105
    EarMap* _ear;
106 106

	
107 107
    IntNodeMap* _blossom_set_index;
108 108
    BlossomSet* _blossom_set;
109 109
    NodeIntMap* _blossom_rep;
110 110

	
111 111
    IntNodeMap* _tree_set_index;
112 112
    TreeSet* _tree_set;
113 113

	
114 114
    NodeQueue _node_queue;
115 115
    int _process, _postpone, _last;
116 116

	
117 117
    int _node_num;
118 118

	
119 119
  private:
120 120

	
121 121
    void createStructures() {
122 122
      _node_num = countNodes(_graph);
123 123
      if (!_matching) {
124 124
        _matching = new MatchingMap(_graph);
125 125
      }
126 126
      if (!_status) {
127 127
        _status = new StatusMap(_graph);
128 128
      }
129 129
      if (!_ear) {
130 130
        _ear = new EarMap(_graph);
131 131
      }
132 132
      if (!_blossom_set) {
133 133
        _blossom_set_index = new IntNodeMap(_graph);
134 134
        _blossom_set = new BlossomSet(*_blossom_set_index);
135 135
      }
136 136
      if (!_blossom_rep) {
137 137
        _blossom_rep = new NodeIntMap(_node_num);
138 138
      }
139 139
      if (!_tree_set) {
140 140
        _tree_set_index = new IntNodeMap(_graph);
141 141
        _tree_set = new TreeSet(*_tree_set_index);
142 142
      }
143 143
      _node_queue.resize(_node_num);
144 144
    }
145 145

	
146 146
    void destroyStructures() {
147 147
      if (_matching) {
148 148
        delete _matching;
149 149
      }
150 150
      if (_status) {
151 151
        delete _status;
152 152
      }
153 153
      if (_ear) {
154 154
        delete _ear;
155 155
      }
156 156
      if (_blossom_set) {
157 157
        delete _blossom_set;
158 158
        delete _blossom_set_index;
159 159
      }
160 160
      if (_blossom_rep) {
161 161
        delete _blossom_rep;
162 162
      }
163 163
      if (_tree_set) {
164 164
        delete _tree_set_index;
165 165
        delete _tree_set;
166 166
      }
167 167
    }
168 168

	
169 169
    void processDense(const Node& n) {
170 170
      _process = _postpone = _last = 0;
171 171
      _node_queue[_last++] = n;
172 172

	
173 173
      while (_process != _last) {
174 174
        Node u = _node_queue[_process++];
175 175
        for (OutArcIt a(_graph, u); a != INVALID; ++a) {
176 176
          Node v = _graph.target(a);
177 177
          if ((*_status)[v] == MATCHED) {
178 178
            extendOnArc(a);
179 179
          } else if ((*_status)[v] == UNMATCHED) {
180 180
            augmentOnArc(a);
181 181
            return;
182 182
          }
183 183
        }
184 184
      }
185 185

	
186 186
      while (_postpone != _last) {
187 187
        Node u = _node_queue[_postpone++];
188 188

	
189 189
        for (OutArcIt a(_graph, u); a != INVALID ; ++a) {
190 190
          Node v = _graph.target(a);
191 191

	
192 192
          if ((*_status)[v] == EVEN) {
193 193
            if (_blossom_set->find(u) != _blossom_set->find(v)) {
194 194
              shrinkOnEdge(a);
195 195
            }
196 196
          }
197 197

	
198 198
          while (_process != _last) {
199 199
            Node w = _node_queue[_process++];
200 200
            for (OutArcIt b(_graph, w); b != INVALID; ++b) {
201 201
              Node x = _graph.target(b);
202 202
              if ((*_status)[x] == MATCHED) {
203 203
                extendOnArc(b);
204 204
              } else if ((*_status)[x] == UNMATCHED) {
205 205
                augmentOnArc(b);
206 206
                return;
207 207
              }
208 208
            }
209 209
          }
210 210
        }
211 211
      }
212 212
    }
213 213

	
214 214
    void processSparse(const Node& n) {
215 215
      _process = _last = 0;
216 216
      _node_queue[_last++] = n;
217 217
      while (_process != _last) {
218 218
        Node u = _node_queue[_process++];
219 219
        for (OutArcIt a(_graph, u); a != INVALID; ++a) {
220 220
          Node v = _graph.target(a);
221 221

	
222 222
          if ((*_status)[v] == EVEN) {
223 223
            if (_blossom_set->find(u) != _blossom_set->find(v)) {
224 224
              shrinkOnEdge(a);
225 225
            }
226 226
          } else if ((*_status)[v] == MATCHED) {
227 227
            extendOnArc(a);
228 228
          } else if ((*_status)[v] == UNMATCHED) {
229 229
            augmentOnArc(a);
230 230
            return;
231 231
          }
232 232
        }
233 233
      }
234 234
    }
235 235

	
236 236
    void shrinkOnEdge(const Edge& e) {
237 237
      Node nca = INVALID;
238 238

	
239 239
      {
240 240
        std::set<Node> left_set, right_set;
241 241

	
242 242
        Node left = (*_blossom_rep)[_blossom_set->find(_graph.u(e))];
243 243
        left_set.insert(left);
244 244

	
245 245
        Node right = (*_blossom_rep)[_blossom_set->find(_graph.v(e))];
246 246
        right_set.insert(right);
247 247

	
248 248
        while (true) {
249 249
          if ((*_matching)[left] == INVALID) break;
250 250
          left = _graph.target((*_matching)[left]);
251 251
          left = (*_blossom_rep)[_blossom_set->
252 252
                                 find(_graph.target((*_ear)[left]))];
253 253
          if (right_set.find(left) != right_set.end()) {
254 254
            nca = left;
255 255
            break;
256 256
          }
257 257
          left_set.insert(left);
258 258

	
259 259
          if ((*_matching)[right] == INVALID) break;
260 260
          right = _graph.target((*_matching)[right]);
261 261
          right = (*_blossom_rep)[_blossom_set->
262 262
                                  find(_graph.target((*_ear)[right]))];
263 263
          if (left_set.find(right) != left_set.end()) {
264 264
            nca = right;
265 265
            break;
266 266
          }
267 267
          right_set.insert(right);
268 268
        }
269 269

	
270 270
        if (nca == INVALID) {
271 271
          if ((*_matching)[left] == INVALID) {
272 272
            nca = right;
273 273
            while (left_set.find(nca) == left_set.end()) {
274 274
              nca = _graph.target((*_matching)[nca]);
275 275
              nca =(*_blossom_rep)[_blossom_set->
276 276
                                   find(_graph.target((*_ear)[nca]))];
277 277
            }
278 278
          } else {
279 279
            nca = left;
280 280
            while (right_set.find(nca) == right_set.end()) {
281 281
              nca = _graph.target((*_matching)[nca]);
282 282
              nca = (*_blossom_rep)[_blossom_set->
283 283
                                   find(_graph.target((*_ear)[nca]))];
284 284
            }
285 285
          }
286 286
        }
287 287
      }
288 288

	
289 289
      {
290 290

	
291 291
        Node node = _graph.u(e);
292 292
        Arc arc = _graph.direct(e, true);
293 293
        Node base = (*_blossom_rep)[_blossom_set->find(node)];
294 294

	
295 295
        while (base != nca) {
296 296
          (*_ear)[node] = arc;
297 297

	
298 298
          Node n = node;
299 299
          while (n != base) {
300 300
            n = _graph.target((*_matching)[n]);
301 301
            Arc a = (*_ear)[n];
302 302
            n = _graph.target(a);
303 303
            (*_ear)[n] = _graph.oppositeArc(a);
304 304
          }
305 305
          node = _graph.target((*_matching)[base]);
306 306
          _tree_set->erase(base);
307 307
          _tree_set->erase(node);
308 308
          _blossom_set->insert(node, _blossom_set->find(base));
309 309
          (*_status)[node] = EVEN;
310 310
          _node_queue[_last++] = node;
311 311
          arc = _graph.oppositeArc((*_ear)[node]);
312 312
          node = _graph.target((*_ear)[node]);
313 313
          base = (*_blossom_rep)[_blossom_set->find(node)];
314 314
          _blossom_set->join(_graph.target(arc), base);
315 315
        }
316 316
      }
317 317

	
318 318
      (*_blossom_rep)[_blossom_set->find(nca)] = nca;
319 319

	
320 320
      {
321 321

	
322 322
        Node node = _graph.v(e);
323 323
        Arc arc = _graph.direct(e, false);
324 324
        Node base = (*_blossom_rep)[_blossom_set->find(node)];
325 325

	
326 326
        while (base != nca) {
327 327
          (*_ear)[node] = arc;
328 328

	
329 329
          Node n = node;
330 330
          while (n != base) {
331 331
            n = _graph.target((*_matching)[n]);
332 332
            Arc a = (*_ear)[n];
333 333
            n = _graph.target(a);
334 334
            (*_ear)[n] = _graph.oppositeArc(a);
335 335
          }
336 336
          node = _graph.target((*_matching)[base]);
337 337
          _tree_set->erase(base);
338 338
          _tree_set->erase(node);
339 339
          _blossom_set->insert(node, _blossom_set->find(base));
340 340
          (*_status)[node] = EVEN;
341 341
          _node_queue[_last++] = node;
342 342
          arc = _graph.oppositeArc((*_ear)[node]);
343 343
          node = _graph.target((*_ear)[node]);
344 344
          base = (*_blossom_rep)[_blossom_set->find(node)];
345 345
          _blossom_set->join(_graph.target(arc), base);
346 346
        }
347 347
      }
348 348

	
349 349
      (*_blossom_rep)[_blossom_set->find(nca)] = nca;
350 350
    }
351 351

	
352 352
    void extendOnArc(const Arc& a) {
353 353
      Node base = _graph.source(a);
354 354
      Node odd = _graph.target(a);
355 355

	
356 356
      (*_ear)[odd] = _graph.oppositeArc(a);
357 357
      Node even = _graph.target((*_matching)[odd]);
358 358
      (*_blossom_rep)[_blossom_set->insert(even)] = even;
359 359
      (*_status)[odd] = ODD;
360 360
      (*_status)[even] = EVEN;
361 361
      int tree = _tree_set->find((*_blossom_rep)[_blossom_set->find(base)]);
362 362
      _tree_set->insert(odd, tree);
363 363
      _tree_set->insert(even, tree);
364 364
      _node_queue[_last++] = even;
365 365

	
366 366
    }
367 367

	
368 368
    void augmentOnArc(const Arc& a) {
369 369
      Node even = _graph.source(a);
370 370
      Node odd = _graph.target(a);
371 371

	
372 372
      int tree = _tree_set->find((*_blossom_rep)[_blossom_set->find(even)]);
373 373

	
374 374
      (*_matching)[odd] = _graph.oppositeArc(a);
375 375
      (*_status)[odd] = MATCHED;
376 376

	
377 377
      Arc arc = (*_matching)[even];
378 378
      (*_matching)[even] = a;
379 379

	
380 380
      while (arc != INVALID) {
381 381
        odd = _graph.target(arc);
382 382
        arc = (*_ear)[odd];
383 383
        even = _graph.target(arc);
384 384
        (*_matching)[odd] = arc;
385 385
        arc = (*_matching)[even];
386 386
        (*_matching)[even] = _graph.oppositeArc((*_matching)[odd]);
387 387
      }
388 388

	
389 389
      for (typename TreeSet::ItemIt it(*_tree_set, tree);
390 390
           it != INVALID; ++it) {
391 391
        if ((*_status)[it] == ODD) {
392 392
          (*_status)[it] = MATCHED;
393 393
        } else {
394 394
          int blossom = _blossom_set->find(it);
395 395
          for (typename BlossomSet::ItemIt jt(*_blossom_set, blossom);
396 396
               jt != INVALID; ++jt) {
397 397
            (*_status)[jt] = MATCHED;
398 398
          }
399 399
          _blossom_set->eraseClass(blossom);
400 400
        }
401 401
      }
402 402
      _tree_set->eraseClass(tree);
403 403

	
404 404
    }
405 405

	
406 406
  public:
407 407

	
408 408
    /// \brief Constructor
409 409
    ///
410 410
    /// Constructor.
411 411
    MaxMatching(const Graph& graph)
412 412
      : _graph(graph), _matching(0), _status(0), _ear(0),
413 413
        _blossom_set_index(0), _blossom_set(0), _blossom_rep(0),
414 414
        _tree_set_index(0), _tree_set(0) {}
415 415

	
416 416
    ~MaxMatching() {
417 417
      destroyStructures();
418 418
    }
419 419

	
420 420
    /// \name Execution Control
421 421
    /// The simplest way to execute the algorithm is to use the
422 422
    /// \c run() member function.\n
423 423
    /// If you need better control on the execution, you have to call
424 424
    /// one of the functions \ref init(), \ref greedyInit() or
425 425
    /// \ref matchingInit() first, then you can start the algorithm with
426 426
    /// \ref startSparse() or \ref startDense().
427 427

	
428 428
    ///@{
429 429

	
430 430
    /// \brief Set the initial matching to the empty matching.
431 431
    ///
432 432
    /// This function sets the initial matching to the empty matching.
433 433
    void init() {
434 434
      createStructures();
435 435
      for(NodeIt n(_graph); n != INVALID; ++n) {
436 436
        (*_matching)[n] = INVALID;
437 437
        (*_status)[n] = UNMATCHED;
438 438
      }
439 439
    }
440 440

	
441 441
    /// \brief Find an initial matching in a greedy way.
442 442
    ///
443 443
    /// This function finds an initial matching in a greedy way.
444 444
    void greedyInit() {
445 445
      createStructures();
446 446
      for (NodeIt n(_graph); n != INVALID; ++n) {
447 447
        (*_matching)[n] = INVALID;
448 448
        (*_status)[n] = UNMATCHED;
449 449
      }
450 450
      for (NodeIt n(_graph); n != INVALID; ++n) {
451 451
        if ((*_matching)[n] == INVALID) {
452 452
          for (OutArcIt a(_graph, n); a != INVALID ; ++a) {
453 453
            Node v = _graph.target(a);
454 454
            if ((*_matching)[v] == INVALID && v != n) {
455 455
              (*_matching)[n] = a;
456 456
              (*_status)[n] = MATCHED;
457 457
              (*_matching)[v] = _graph.oppositeArc(a);
458 458
              (*_status)[v] = MATCHED;
459 459
              break;
460 460
            }
461 461
          }
462 462
        }
463 463
      }
464 464
    }
465 465

	
466 466

	
467 467
    /// \brief Initialize the matching from a map.
468 468
    ///
469 469
    /// This function initializes the matching from a \c bool valued edge
470 470
    /// map. This map should have the property that there are no two incident
471 471
    /// edges with \c true value, i.e. it really contains a matching.
472 472
    /// \return \c true if the map contains a matching.
473 473
    template <typename MatchingMap>
474 474
    bool matchingInit(const MatchingMap& matching) {
475 475
      createStructures();
476 476

	
477 477
      for (NodeIt n(_graph); n != INVALID; ++n) {
478 478
        (*_matching)[n] = INVALID;
479 479
        (*_status)[n] = UNMATCHED;
480 480
      }
481 481
      for(EdgeIt e(_graph); e!=INVALID; ++e) {
482 482
        if (matching[e]) {
483 483

	
484 484
          Node u = _graph.u(e);
485 485
          if ((*_matching)[u] != INVALID) return false;
486 486
          (*_matching)[u] = _graph.direct(e, true);
487 487
          (*_status)[u] = MATCHED;
488 488

	
489 489
          Node v = _graph.v(e);
490 490
          if ((*_matching)[v] != INVALID) return false;
491 491
          (*_matching)[v] = _graph.direct(e, false);
492 492
          (*_status)[v] = MATCHED;
493 493
        }
494 494
      }
495 495
      return true;
496 496
    }
497 497

	
498 498
    /// \brief Start Edmonds' algorithm
499 499
    ///
500 500
    /// This function runs the original Edmonds' algorithm.
501 501
    ///
502
    /// \pre \ref Init(), \ref greedyInit() or \ref matchingInit() must be
502
    /// \pre \ref init(), \ref greedyInit() or \ref matchingInit() must be
503 503
    /// called before using this function.
504 504
    void startSparse() {
505 505
      for(NodeIt n(_graph); n != INVALID; ++n) {
506 506
        if ((*_status)[n] == UNMATCHED) {
507 507
          (*_blossom_rep)[_blossom_set->insert(n)] = n;
508 508
          _tree_set->insert(n);
509 509
          (*_status)[n] = EVEN;
510 510
          processSparse(n);
511 511
        }
512 512
      }
513 513
    }
514 514

	
515 515
    /// \brief Start Edmonds' algorithm with a heuristic improvement 
516 516
    /// for dense graphs
517 517
    ///
518 518
    /// This function runs Edmonds' algorithm with a heuristic of postponing
519 519
    /// shrinks, therefore resulting in a faster algorithm for dense graphs.
520 520
    ///
521
    /// \pre \ref Init(), \ref greedyInit() or \ref matchingInit() must be
521
    /// \pre \ref init(), \ref greedyInit() or \ref matchingInit() must be
522 522
    /// called before using this function.
523 523
    void startDense() {
524 524
      for(NodeIt n(_graph); n != INVALID; ++n) {
525 525
        if ((*_status)[n] == UNMATCHED) {
526 526
          (*_blossom_rep)[_blossom_set->insert(n)] = n;
527 527
          _tree_set->insert(n);
528 528
          (*_status)[n] = EVEN;
529 529
          processDense(n);
530 530
        }
531 531
      }
532 532
    }
533 533

	
534 534

	
535 535
    /// \brief Run Edmonds' algorithm
536 536
    ///
537 537
    /// This function runs Edmonds' algorithm. An additional heuristic of 
538 538
    /// postponing shrinks is used for relatively dense graphs 
539 539
    /// (for which <tt>m>=2*n</tt> holds).
540 540
    void run() {
541 541
      if (countEdges(_graph) < 2 * countNodes(_graph)) {
542 542
        greedyInit();
543 543
        startSparse();
544 544
      } else {
545 545
        init();
546 546
        startDense();
547 547
      }
548 548
    }
549 549

	
550 550
    /// @}
551 551

	
552 552
    /// \name Primal Solution
553 553
    /// Functions to get the primal solution, i.e. the maximum matching.
554 554

	
555 555
    /// @{
556 556

	
557 557
    /// \brief Return the size (cardinality) of the matching.
558 558
    ///
559 559
    /// This function returns the size (cardinality) of the current matching. 
560 560
    /// After run() it returns the size of the maximum matching in the graph.
561 561
    int matchingSize() const {
562 562
      int size = 0;
563 563
      for (NodeIt n(_graph); n != INVALID; ++n) {
564 564
        if ((*_matching)[n] != INVALID) {
565 565
          ++size;
566 566
        }
567 567
      }
568 568
      return size / 2;
569 569
    }
570 570

	
571 571
    /// \brief Return \c true if the given edge is in the matching.
572 572
    ///
573 573
    /// This function returns \c true if the given edge is in the current 
574 574
    /// matching.
575 575
    bool matching(const Edge& edge) const {
576 576
      return edge == (*_matching)[_graph.u(edge)];
577 577
    }
578 578

	
579 579
    /// \brief Return the matching arc (or edge) incident to the given node.
580 580
    ///
581 581
    /// This function returns the matching arc (or edge) incident to the
582 582
    /// given node in the current matching or \c INVALID if the node is 
583 583
    /// not covered by the matching.
584 584
    Arc matching(const Node& n) const {
585 585
      return (*_matching)[n];
586 586
    }
587 587

	
588 588
    /// \brief Return a const reference to the matching map.
589 589
    ///
590 590
    /// This function returns a const reference to a node map that stores
591 591
    /// the matching arc (or edge) incident to each node.
592 592
    const MatchingMap& matchingMap() const {
593 593
      return *_matching;
594 594
    }
595 595

	
596 596
    /// \brief Return the mate of the given node.
597 597
    ///
598 598
    /// This function returns the mate of the given node in the current 
599 599
    /// matching or \c INVALID if the node is not covered by the matching.
600 600
    Node mate(const Node& n) const {
601 601
      return (*_matching)[n] != INVALID ?
602 602
        _graph.target((*_matching)[n]) : INVALID;
603 603
    }
604 604

	
605 605
    /// @}
606 606

	
607 607
    /// \name Dual Solution
608 608
    /// Functions to get the dual solution, i.e. the Gallai-Edmonds 
609 609
    /// decomposition.
610 610

	
611 611
    /// @{
612 612

	
613 613
    /// \brief Return the status of the given node in the Edmonds-Gallai
614 614
    /// decomposition.
615 615
    ///
616 616
    /// This function returns the \ref Status "status" of the given node
617 617
    /// in the Edmonds-Gallai decomposition.
618 618
    Status status(const Node& n) const {
619 619
      return (*_status)[n];
620 620
    }
621 621

	
622 622
    /// \brief Return a const reference to the status map, which stores
623 623
    /// the Edmonds-Gallai decomposition.
624 624
    ///
625 625
    /// This function returns a const reference to a node map that stores the
626 626
    /// \ref Status "status" of each node in the Edmonds-Gallai decomposition.
627 627
    const StatusMap& statusMap() const {
628 628
      return *_status;
629 629
    }
630 630

	
631 631
    /// \brief Return \c true if the given node is in the barrier.
632 632
    ///
633 633
    /// This function returns \c true if the given node is in the barrier.
634 634
    bool barrier(const Node& n) const {
635 635
      return (*_status)[n] == ODD;
636 636
    }
637 637

	
638 638
    /// @}
639 639

	
640 640
  };
641 641

	
642 642
  /// \ingroup matching
643 643
  ///
644 644
  /// \brief Weighted matching in general graphs
645 645
  ///
646 646
  /// This class provides an efficient implementation of Edmond's
647 647
  /// maximum weighted matching algorithm. The implementation is based
648 648
  /// on extensive use of priority queues and provides
649 649
  /// \f$O(nm\log n)\f$ time complexity.
650 650
  ///
651 651
  /// The maximum weighted matching problem is to find a subset of the 
652 652
  /// edges in an undirected graph with maximum overall weight for which 
653 653
  /// each node has at most one incident edge.
654 654
  /// It can be formulated with the following linear program.
655 655
  /// \f[ \sum_{e \in \delta(u)}x_e \le 1 \quad \forall u\in V\f]
656 656
  /** \f[ \sum_{e \in \gamma(B)}x_e \le \frac{\vert B \vert - 1}{2}
657 657
      \quad \forall B\in\mathcal{O}\f] */
658 658
  /// \f[x_e \ge 0\quad \forall e\in E\f]
659 659
  /// \f[\max \sum_{e\in E}x_ew_e\f]
660 660
  /// where \f$\delta(X)\f$ is the set of edges incident to a node in
661 661
  /// \f$X\f$, \f$\gamma(X)\f$ is the set of edges with both ends in
662 662
  /// \f$X\f$ and \f$\mathcal{O}\f$ is the set of odd cardinality
663 663
  /// subsets of the nodes.
664 664
  ///
665 665
  /// The algorithm calculates an optimal matching and a proof of the
666 666
  /// optimality. The solution of the dual problem can be used to check
667 667
  /// the result of the algorithm. The dual linear problem is the
668 668
  /// following.
669 669
  /** \f[ y_u + y_v + \sum_{B \in \mathcal{O}, uv \in \gamma(B)}
670 670
      z_B \ge w_{uv} \quad \forall uv\in E\f] */
671 671
  /// \f[y_u \ge 0 \quad \forall u \in V\f]
672 672
  /// \f[z_B \ge 0 \quad \forall B \in \mathcal{O}\f]
673 673
  /** \f[\min \sum_{u \in V}y_u + \sum_{B \in \mathcal{O}}
674 674
      \frac{\vert B \vert - 1}{2}z_B\f] */
675 675
  ///
676 676
  /// The algorithm can be executed with the run() function. 
677 677
  /// After it the matching (the primal solution) and the dual solution
678 678
  /// can be obtained using the query functions and the 
679 679
  /// \ref MaxWeightedMatching::BlossomIt "BlossomIt" nested class, 
680 680
  /// which is able to iterate on the nodes of a blossom. 
681 681
  /// If the value type is integer, then the dual solution is multiplied
682 682
  /// by \ref MaxWeightedMatching::dualScale "4".
683 683
  ///
684 684
  /// \tparam GR The undirected graph type the algorithm runs on.
685 685
  /// \tparam WM The type edge weight map. The default type is 
686 686
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<int>".
687 687
#ifdef DOXYGEN
688 688
  template <typename GR, typename WM>
689 689
#else
690 690
  template <typename GR,
691 691
            typename WM = typename GR::template EdgeMap<int> >
692 692
#endif
693 693
  class MaxWeightedMatching {
694 694
  public:
695 695

	
696 696
    /// The graph type of the algorithm
697 697
    typedef GR Graph;
698 698
    /// The type of the edge weight map
699 699
    typedef WM WeightMap;
700 700
    /// The value type of the edge weights
701 701
    typedef typename WeightMap::Value Value;
702 702

	
703 703
    /// The type of the matching map
704 704
    typedef typename Graph::template NodeMap<typename Graph::Arc>
705 705
    MatchingMap;
706 706

	
707 707
    /// \brief Scaling factor for dual solution
708 708
    ///
709 709
    /// Scaling factor for dual solution. It is equal to 4 or 1
710 710
    /// according to the value type.
711 711
    static const int dualScale =
712 712
      std::numeric_limits<Value>::is_integer ? 4 : 1;
713 713

	
714 714
  private:
715 715

	
716 716
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
717 717

	
718 718
    typedef typename Graph::template NodeMap<Value> NodePotential;
719 719
    typedef std::vector<Node> BlossomNodeList;
720 720

	
721 721
    struct BlossomVariable {
722 722
      int begin, end;
723 723
      Value value;
724 724

	
725 725
      BlossomVariable(int _begin, int _end, Value _value)
726 726
        : begin(_begin), end(_end), value(_value) {}
727 727

	
728 728
    };
729 729

	
730 730
    typedef std::vector<BlossomVariable> BlossomPotential;
731 731

	
732 732
    const Graph& _graph;
733 733
    const WeightMap& _weight;
734 734

	
735 735
    MatchingMap* _matching;
736 736

	
737 737
    NodePotential* _node_potential;
738 738

	
739 739
    BlossomPotential _blossom_potential;
740 740
    BlossomNodeList _blossom_node_list;
741 741

	
742 742
    int _node_num;
743 743
    int _blossom_num;
744 744

	
745 745
    typedef RangeMap<int> IntIntMap;
746 746

	
747 747
    enum Status {
748 748
      EVEN = -1, MATCHED = 0, ODD = 1, UNMATCHED = -2
749 749
    };
750 750

	
751 751
    typedef HeapUnionFind<Value, IntNodeMap> BlossomSet;
752 752
    struct BlossomData {
753 753
      int tree;
754 754
      Status status;
755 755
      Arc pred, next;
756 756
      Value pot, offset;
757 757
      Node base;
758 758
    };
759 759

	
760 760
    IntNodeMap *_blossom_index;
761 761
    BlossomSet *_blossom_set;
762 762
    RangeMap<BlossomData>* _blossom_data;
763 763

	
764 764
    IntNodeMap *_node_index;
765 765
    IntArcMap *_node_heap_index;
766 766

	
767 767
    struct NodeData {
768 768

	
769 769
      NodeData(IntArcMap& node_heap_index)
770 770
        : heap(node_heap_index) {}
771 771

	
772 772
      int blossom;
773 773
      Value pot;
774 774
      BinHeap<Value, IntArcMap> heap;
775 775
      std::map<int, Arc> heap_index;
776 776

	
777 777
      int tree;
778 778
    };
779 779

	
780 780
    RangeMap<NodeData>* _node_data;
781 781

	
782 782
    typedef ExtendFindEnum<IntIntMap> TreeSet;
783 783

	
784 784
    IntIntMap *_tree_set_index;
785 785
    TreeSet *_tree_set;
786 786

	
787 787
    IntNodeMap *_delta1_index;
788 788
    BinHeap<Value, IntNodeMap> *_delta1;
789 789

	
790 790
    IntIntMap *_delta2_index;
791 791
    BinHeap<Value, IntIntMap> *_delta2;
792 792

	
793 793
    IntEdgeMap *_delta3_index;
794 794
    BinHeap<Value, IntEdgeMap> *_delta3;
795 795

	
796 796
    IntIntMap *_delta4_index;
797 797
    BinHeap<Value, IntIntMap> *_delta4;
798 798

	
799 799
    Value _delta_sum;
800 800

	
801 801
    void createStructures() {
802 802
      _node_num = countNodes(_graph);
803 803
      _blossom_num = _node_num * 3 / 2;
804 804

	
805 805
      if (!_matching) {
806 806
        _matching = new MatchingMap(_graph);
807 807
      }
808 808
      if (!_node_potential) {
809 809
        _node_potential = new NodePotential(_graph);
810 810
      }
811 811
      if (!_blossom_set) {
812 812
        _blossom_index = new IntNodeMap(_graph);
813 813
        _blossom_set = new BlossomSet(*_blossom_index);
814 814
        _blossom_data = new RangeMap<BlossomData>(_blossom_num);
815 815
      }
816 816

	
817 817
      if (!_node_index) {
818 818
        _node_index = new IntNodeMap(_graph);
819 819
        _node_heap_index = new IntArcMap(_graph);
820 820
        _node_data = new RangeMap<NodeData>(_node_num,
821 821
                                              NodeData(*_node_heap_index));
822 822
      }
823 823

	
824 824
      if (!_tree_set) {
825 825
        _tree_set_index = new IntIntMap(_blossom_num);
826 826
        _tree_set = new TreeSet(*_tree_set_index);
827 827
      }
828 828
      if (!_delta1) {
829 829
        _delta1_index = new IntNodeMap(_graph);
830 830
        _delta1 = new BinHeap<Value, IntNodeMap>(*_delta1_index);
831 831
      }
832 832
      if (!_delta2) {
833 833
        _delta2_index = new IntIntMap(_blossom_num);
834 834
        _delta2 = new BinHeap<Value, IntIntMap>(*_delta2_index);
835 835
      }
836 836
      if (!_delta3) {
837 837
        _delta3_index = new IntEdgeMap(_graph);
838 838
        _delta3 = new BinHeap<Value, IntEdgeMap>(*_delta3_index);
839 839
      }
840 840
      if (!_delta4) {
841 841
        _delta4_index = new IntIntMap(_blossom_num);
842 842
        _delta4 = new BinHeap<Value, IntIntMap>(*_delta4_index);
843 843
      }
844 844
    }
845 845

	
846 846
    void destroyStructures() {
847 847
      _node_num = countNodes(_graph);
848 848
      _blossom_num = _node_num * 3 / 2;
849 849

	
850 850
      if (_matching) {
851 851
        delete _matching;
852 852
      }
853 853
      if (_node_potential) {
854 854
        delete _node_potential;
855 855
      }
856 856
      if (_blossom_set) {
857 857
        delete _blossom_index;
858 858
        delete _blossom_set;
859 859
        delete _blossom_data;
860 860
      }
861 861

	
862 862
      if (_node_index) {
863 863
        delete _node_index;
864 864
        delete _node_heap_index;
865 865
        delete _node_data;
866 866
      }
867 867

	
868 868
      if (_tree_set) {
869 869
        delete _tree_set_index;
870 870
        delete _tree_set;
871 871
      }
872 872
      if (_delta1) {
873 873
        delete _delta1_index;
874 874
        delete _delta1;
875 875
      }
876 876
      if (_delta2) {
877 877
        delete _delta2_index;
878 878
        delete _delta2;
879 879
      }
880 880
      if (_delta3) {
881 881
        delete _delta3_index;
882 882
        delete _delta3;
883 883
      }
884 884
      if (_delta4) {
885 885
        delete _delta4_index;
886 886
        delete _delta4;
887 887
      }
888 888
    }
889 889

	
890 890
    void matchedToEven(int blossom, int tree) {
891 891
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
892 892
        _delta2->erase(blossom);
893 893
      }
894 894

	
895 895
      if (!_blossom_set->trivial(blossom)) {
896 896
        (*_blossom_data)[blossom].pot -=
897 897
          2 * (_delta_sum - (*_blossom_data)[blossom].offset);
898 898
      }
899 899

	
900 900
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
901 901
           n != INVALID; ++n) {
902 902

	
903 903
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
904 904
        int ni = (*_node_index)[n];
905 905

	
906 906
        (*_node_data)[ni].heap.clear();
907 907
        (*_node_data)[ni].heap_index.clear();
908 908

	
909 909
        (*_node_data)[ni].pot += _delta_sum - (*_blossom_data)[blossom].offset;
910 910

	
911 911
        _delta1->push(n, (*_node_data)[ni].pot);
912 912

	
913 913
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
914 914
          Node v = _graph.source(e);
915 915
          int vb = _blossom_set->find(v);
916 916
          int vi = (*_node_index)[v];
917 917

	
918 918
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
919 919
            dualScale * _weight[e];
920 920

	
921 921
          if ((*_blossom_data)[vb].status == EVEN) {
922 922
            if (_delta3->state(e) != _delta3->IN_HEAP && blossom != vb) {
923 923
              _delta3->push(e, rw / 2);
924 924
            }
925 925
          } else if ((*_blossom_data)[vb].status == UNMATCHED) {
926 926
            if (_delta3->state(e) != _delta3->IN_HEAP) {
927 927
              _delta3->push(e, rw);
928 928
            }
929 929
          } else {
930 930
            typename std::map<int, Arc>::iterator it =
931 931
              (*_node_data)[vi].heap_index.find(tree);
932 932

	
933 933
            if (it != (*_node_data)[vi].heap_index.end()) {
934 934
              if ((*_node_data)[vi].heap[it->second] > rw) {
935 935
                (*_node_data)[vi].heap.replace(it->second, e);
936 936
                (*_node_data)[vi].heap.decrease(e, rw);
937 937
                it->second = e;
938 938
              }
939 939
            } else {
940 940
              (*_node_data)[vi].heap.push(e, rw);
941 941
              (*_node_data)[vi].heap_index.insert(std::make_pair(tree, e));
942 942
            }
943 943

	
944 944
            if ((*_blossom_set)[v] > (*_node_data)[vi].heap.prio()) {
945 945
              _blossom_set->decrease(v, (*_node_data)[vi].heap.prio());
946 946

	
947 947
              if ((*_blossom_data)[vb].status == MATCHED) {
948 948
                if (_delta2->state(vb) != _delta2->IN_HEAP) {
949 949
                  _delta2->push(vb, _blossom_set->classPrio(vb) -
950 950
                               (*_blossom_data)[vb].offset);
951 951
                } else if ((*_delta2)[vb] > _blossom_set->classPrio(vb) -
952 952
                           (*_blossom_data)[vb].offset){
953 953
                  _delta2->decrease(vb, _blossom_set->classPrio(vb) -
954 954
                                   (*_blossom_data)[vb].offset);
955 955
                }
956 956
              }
957 957
            }
958 958
          }
959 959
        }
960 960
      }
961 961
      (*_blossom_data)[blossom].offset = 0;
962 962
    }
963 963

	
964 964
    void matchedToOdd(int blossom) {
965 965
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
966 966
        _delta2->erase(blossom);
967 967
      }
968 968
      (*_blossom_data)[blossom].offset += _delta_sum;
969 969
      if (!_blossom_set->trivial(blossom)) {
970 970
        _delta4->push(blossom, (*_blossom_data)[blossom].pot / 2 +
971 971
                     (*_blossom_data)[blossom].offset);
972 972
      }
973 973
    }
974 974

	
975 975
    void evenToMatched(int blossom, int tree) {
976 976
      if (!_blossom_set->trivial(blossom)) {
977 977
        (*_blossom_data)[blossom].pot += 2 * _delta_sum;
978 978
      }
979 979

	
980 980
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
981 981
           n != INVALID; ++n) {
982 982
        int ni = (*_node_index)[n];
983 983
        (*_node_data)[ni].pot -= _delta_sum;
984 984

	
985 985
        _delta1->erase(n);
986 986

	
987 987
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
988 988
          Node v = _graph.source(e);
989 989
          int vb = _blossom_set->find(v);
990 990
          int vi = (*_node_index)[v];
991 991

	
992 992
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
993 993
            dualScale * _weight[e];
994 994

	
995 995
          if (vb == blossom) {
996 996
            if (_delta3->state(e) == _delta3->IN_HEAP) {
997 997
              _delta3->erase(e);
998 998
            }
999 999
          } else if ((*_blossom_data)[vb].status == EVEN) {
1000 1000

	
1001 1001
            if (_delta3->state(e) == _delta3->IN_HEAP) {
1002 1002
              _delta3->erase(e);
1003 1003
            }
1004 1004

	
1005 1005
            int vt = _tree_set->find(vb);
1006 1006

	
1007 1007
            if (vt != tree) {
1008 1008

	
1009 1009
              Arc r = _graph.oppositeArc(e);
1010 1010

	
1011 1011
              typename std::map<int, Arc>::iterator it =
1012 1012
                (*_node_data)[ni].heap_index.find(vt);
1013 1013

	
1014 1014
              if (it != (*_node_data)[ni].heap_index.end()) {
1015 1015
                if ((*_node_data)[ni].heap[it->second] > rw) {
1016 1016
                  (*_node_data)[ni].heap.replace(it->second, r);
1017 1017
                  (*_node_data)[ni].heap.decrease(r, rw);
1018 1018
                  it->second = r;
1019 1019
                }
1020 1020
              } else {
1021 1021
                (*_node_data)[ni].heap.push(r, rw);
1022 1022
                (*_node_data)[ni].heap_index.insert(std::make_pair(vt, r));
1023 1023
              }
1024 1024

	
1025 1025
              if ((*_blossom_set)[n] > (*_node_data)[ni].heap.prio()) {
1026 1026
                _blossom_set->decrease(n, (*_node_data)[ni].heap.prio());
1027 1027

	
1028 1028
                if (_delta2->state(blossom) != _delta2->IN_HEAP) {
1029 1029
                  _delta2->push(blossom, _blossom_set->classPrio(blossom) -
1030 1030
                               (*_blossom_data)[blossom].offset);
1031 1031
                } else if ((*_delta2)[blossom] >
1032 1032
                           _blossom_set->classPrio(blossom) -
1033 1033
                           (*_blossom_data)[blossom].offset){
1034 1034
                  _delta2->decrease(blossom, _blossom_set->classPrio(blossom) -
1035 1035
                                   (*_blossom_data)[blossom].offset);
1036 1036
                }
1037 1037
              }
1038 1038
            }
1039 1039

	
1040 1040
          } else if ((*_blossom_data)[vb].status == UNMATCHED) {
1041 1041
            if (_delta3->state(e) == _delta3->IN_HEAP) {
1042 1042
              _delta3->erase(e);
1043 1043
            }
1044 1044
          } else {
1045 1045

	
1046 1046
            typename std::map<int, Arc>::iterator it =
1047 1047
              (*_node_data)[vi].heap_index.find(tree);
1048 1048

	
1049 1049
            if (it != (*_node_data)[vi].heap_index.end()) {
1050 1050
              (*_node_data)[vi].heap.erase(it->second);
1051 1051
              (*_node_data)[vi].heap_index.erase(it);
1052 1052
              if ((*_node_data)[vi].heap.empty()) {
1053 1053
                _blossom_set->increase(v, std::numeric_limits<Value>::max());
1054 1054
              } else if ((*_blossom_set)[v] < (*_node_data)[vi].heap.prio()) {
1055 1055
                _blossom_set->increase(v, (*_node_data)[vi].heap.prio());
1056 1056
              }
1057 1057

	
1058 1058
              if ((*_blossom_data)[vb].status == MATCHED) {
1059 1059
                if (_blossom_set->classPrio(vb) ==
1060 1060
                    std::numeric_limits<Value>::max()) {
1061 1061
                  _delta2->erase(vb);
1062 1062
                } else if ((*_delta2)[vb] < _blossom_set->classPrio(vb) -
1063 1063
                           (*_blossom_data)[vb].offset) {
1064 1064
                  _delta2->increase(vb, _blossom_set->classPrio(vb) -
1065 1065
                                   (*_blossom_data)[vb].offset);
1066 1066
                }
1067 1067
              }
1068 1068
            }
1069 1069
          }
1070 1070
        }
1071 1071
      }
1072 1072
    }
1073 1073

	
1074 1074
    void oddToMatched(int blossom) {
1075 1075
      (*_blossom_data)[blossom].offset -= _delta_sum;
1076 1076

	
1077 1077
      if (_blossom_set->classPrio(blossom) !=
1078 1078
          std::numeric_limits<Value>::max()) {
1079 1079
        _delta2->push(blossom, _blossom_set->classPrio(blossom) -
1080 1080
                       (*_blossom_data)[blossom].offset);
1081 1081
      }
1082 1082

	
1083 1083
      if (!_blossom_set->trivial(blossom)) {
1084 1084
        _delta4->erase(blossom);
1085 1085
      }
1086 1086
    }
1087 1087

	
1088 1088
    void oddToEven(int blossom, int tree) {
1089 1089
      if (!_blossom_set->trivial(blossom)) {
1090 1090
        _delta4->erase(blossom);
1091 1091
        (*_blossom_data)[blossom].pot -=
1092 1092
          2 * (2 * _delta_sum - (*_blossom_data)[blossom].offset);
1093 1093
      }
1094 1094

	
1095 1095
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
1096 1096
           n != INVALID; ++n) {
1097 1097
        int ni = (*_node_index)[n];
1098 1098

	
1099 1099
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
1100 1100

	
1101 1101
        (*_node_data)[ni].heap.clear();
1102 1102
        (*_node_data)[ni].heap_index.clear();
1103 1103
        (*_node_data)[ni].pot +=
1104 1104
          2 * _delta_sum - (*_blossom_data)[blossom].offset;
1105 1105

	
1106 1106
        _delta1->push(n, (*_node_data)[ni].pot);
1107 1107

	
1108 1108
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
1109 1109
          Node v = _graph.source(e);
1110 1110
          int vb = _blossom_set->find(v);
1111 1111
          int vi = (*_node_index)[v];
1112 1112

	
1113 1113
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
1114 1114
            dualScale * _weight[e];
1115 1115

	
1116 1116
          if ((*_blossom_data)[vb].status == EVEN) {
1117 1117
            if (_delta3->state(e) != _delta3->IN_HEAP && blossom != vb) {
1118 1118
              _delta3->push(e, rw / 2);
1119 1119
            }
1120 1120
          } else if ((*_blossom_data)[vb].status == UNMATCHED) {
1121 1121
            if (_delta3->state(e) != _delta3->IN_HEAP) {
1122 1122
              _delta3->push(e, rw);
1123 1123
            }
1124 1124
          } else {
1125 1125

	
1126 1126
            typename std::map<int, Arc>::iterator it =
1127 1127
              (*_node_data)[vi].heap_index.find(tree);
1128 1128

	
1129 1129
            if (it != (*_node_data)[vi].heap_index.end()) {
1130 1130
              if ((*_node_data)[vi].heap[it->second] > rw) {
1131 1131
                (*_node_data)[vi].heap.replace(it->second, e);
1132 1132
                (*_node_data)[vi].heap.decrease(e, rw);
1133 1133
                it->second = e;
1134 1134
              }
1135 1135
            } else {
1136 1136
              (*_node_data)[vi].heap.push(e, rw);
1137 1137
              (*_node_data)[vi].heap_index.insert(std::make_pair(tree, e));
1138 1138
            }
1139 1139

	
1140 1140
            if ((*_blossom_set)[v] > (*_node_data)[vi].heap.prio()) {
1141 1141
              _blossom_set->decrease(v, (*_node_data)[vi].heap.prio());
1142 1142

	
1143 1143
              if ((*_blossom_data)[vb].status == MATCHED) {
1144 1144
                if (_delta2->state(vb) != _delta2->IN_HEAP) {
1145 1145
                  _delta2->push(vb, _blossom_set->classPrio(vb) -
1146 1146
                               (*_blossom_data)[vb].offset);
1147 1147
                } else if ((*_delta2)[vb] > _blossom_set->classPrio(vb) -
1148 1148
                           (*_blossom_data)[vb].offset) {
1149 1149
                  _delta2->decrease(vb, _blossom_set->classPrio(vb) -
1150 1150
                                   (*_blossom_data)[vb].offset);
1151 1151
                }
1152 1152
              }
1153 1153
            }
1154 1154
          }
1155 1155
        }
1156 1156
      }
1157 1157
      (*_blossom_data)[blossom].offset = 0;
1158 1158
    }
1159 1159

	
1160 1160

	
1161 1161
    void matchedToUnmatched(int blossom) {
1162 1162
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
1163 1163
        _delta2->erase(blossom);
1164 1164
      }
1165 1165

	
1166 1166
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
1167 1167
           n != INVALID; ++n) {
1168 1168
        int ni = (*_node_index)[n];
1169 1169

	
1170 1170
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
1171 1171

	
1172 1172
        (*_node_data)[ni].heap.clear();
1173 1173
        (*_node_data)[ni].heap_index.clear();
1174 1174

	
1175 1175
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
1176 1176
          Node v = _graph.target(e);
1177 1177
          int vb = _blossom_set->find(v);
1178 1178
          int vi = (*_node_index)[v];
1179 1179

	
1180 1180
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
1181 1181
            dualScale * _weight[e];
1182 1182

	
1183 1183
          if ((*_blossom_data)[vb].status == EVEN) {
1184 1184
            if (_delta3->state(e) != _delta3->IN_HEAP) {
1185 1185
              _delta3->push(e, rw);
1186 1186
            }
1187 1187
          }
1188 1188
        }
1189 1189
      }
1190 1190
    }
1191 1191

	
1192 1192
    void unmatchedToMatched(int blossom) {
1193 1193
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
1194 1194
           n != INVALID; ++n) {
1195 1195
        int ni = (*_node_index)[n];
1196 1196

	
1197 1197
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
1198 1198
          Node v = _graph.source(e);
1199 1199
          int vb = _blossom_set->find(v);
1200 1200
          int vi = (*_node_index)[v];
1201 1201

	
1202 1202
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
1203 1203
            dualScale * _weight[e];
1204 1204

	
1205 1205
          if (vb == blossom) {
1206 1206
            if (_delta3->state(e) == _delta3->IN_HEAP) {
1207 1207
              _delta3->erase(e);
1208 1208
            }
1209 1209
          } else if ((*_blossom_data)[vb].status == EVEN) {
1210 1210

	
1211 1211
            if (_delta3->state(e) == _delta3->IN_HEAP) {
1212 1212
              _delta3->erase(e);
1213 1213
            }
1214 1214

	
1215 1215
            int vt = _tree_set->find(vb);
1216 1216

	
1217 1217
            Arc r = _graph.oppositeArc(e);
1218 1218

	
1219 1219
            typename std::map<int, Arc>::iterator it =
1220 1220
              (*_node_data)[ni].heap_index.find(vt);
1221 1221

	
1222 1222
            if (it != (*_node_data)[ni].heap_index.end()) {
1223 1223
              if ((*_node_data)[ni].heap[it->second] > rw) {
1224 1224
                (*_node_data)[ni].heap.replace(it->second, r);
1225 1225
                (*_node_data)[ni].heap.decrease(r, rw);
1226 1226
                it->second = r;
1227 1227
              }
1228 1228
            } else {
1229 1229
              (*_node_data)[ni].heap.push(r, rw);
1230 1230
              (*_node_data)[ni].heap_index.insert(std::make_pair(vt, r));
1231 1231
            }
1232 1232

	
1233 1233
            if ((*_blossom_set)[n] > (*_node_data)[ni].heap.prio()) {
1234 1234
              _blossom_set->decrease(n, (*_node_data)[ni].heap.prio());
1235 1235

	
1236 1236
              if (_delta2->state(blossom) != _delta2->IN_HEAP) {
1237 1237
                _delta2->push(blossom, _blossom_set->classPrio(blossom) -
1238 1238
                             (*_blossom_data)[blossom].offset);
1239 1239
              } else if ((*_delta2)[blossom] > _blossom_set->classPrio(blossom)-
1240 1240
                         (*_blossom_data)[blossom].offset){
1241 1241
                _delta2->decrease(blossom, _blossom_set->classPrio(blossom) -
1242 1242
                                 (*_blossom_data)[blossom].offset);
1243 1243
              }
1244 1244
            }
1245 1245

	
1246 1246
          } else if ((*_blossom_data)[vb].status == UNMATCHED) {
1247 1247
            if (_delta3->state(e) == _delta3->IN_HEAP) {
1248 1248
              _delta3->erase(e);
1249 1249
            }
1250 1250
          }
1251 1251
        }
1252 1252
      }
1253 1253
    }
1254 1254

	
1255 1255
    void alternatePath(int even, int tree) {
1256 1256
      int odd;
1257 1257

	
1258 1258
      evenToMatched(even, tree);
1259 1259
      (*_blossom_data)[even].status = MATCHED;
1260 1260

	
1261 1261
      while ((*_blossom_data)[even].pred != INVALID) {
1262 1262
        odd = _blossom_set->find(_graph.target((*_blossom_data)[even].pred));
1263 1263
        (*_blossom_data)[odd].status = MATCHED;
1264 1264
        oddToMatched(odd);
1265 1265
        (*_blossom_data)[odd].next = (*_blossom_data)[odd].pred;
1266 1266

	
1267 1267
        even = _blossom_set->find(_graph.target((*_blossom_data)[odd].pred));
1268 1268
        (*_blossom_data)[even].status = MATCHED;
1269 1269
        evenToMatched(even, tree);
1270 1270
        (*_blossom_data)[even].next =
1271 1271
          _graph.oppositeArc((*_blossom_data)[odd].pred);
1272 1272
      }
1273 1273

	
1274 1274
    }
1275 1275

	
1276 1276
    void destroyTree(int tree) {
1277 1277
      for (TreeSet::ItemIt b(*_tree_set, tree); b != INVALID; ++b) {
1278 1278
        if ((*_blossom_data)[b].status == EVEN) {
1279 1279
          (*_blossom_data)[b].status = MATCHED;
1280 1280
          evenToMatched(b, tree);
1281 1281
        } else if ((*_blossom_data)[b].status == ODD) {
1282 1282
          (*_blossom_data)[b].status = MATCHED;
1283 1283
          oddToMatched(b);
1284 1284
        }
1285 1285
      }
1286 1286
      _tree_set->eraseClass(tree);
1287 1287
    }
1288 1288

	
1289 1289

	
1290 1290
    void unmatchNode(const Node& node) {
1291 1291
      int blossom = _blossom_set->find(node);
1292 1292
      int tree = _tree_set->find(blossom);
1293 1293

	
1294 1294
      alternatePath(blossom, tree);
1295 1295
      destroyTree(tree);
1296 1296

	
1297 1297
      (*_blossom_data)[blossom].status = UNMATCHED;
1298 1298
      (*_blossom_data)[blossom].base = node;
1299 1299
      matchedToUnmatched(blossom);
1300 1300
    }
1301 1301

	
1302 1302

	
1303 1303
    void augmentOnEdge(const Edge& edge) {
1304 1304

	
1305 1305
      int left = _blossom_set->find(_graph.u(edge));
1306 1306
      int right = _blossom_set->find(_graph.v(edge));
1307 1307

	
1308 1308
      if ((*_blossom_data)[left].status == EVEN) {
1309 1309
        int left_tree = _tree_set->find(left);
1310 1310
        alternatePath(left, left_tree);
1311 1311
        destroyTree(left_tree);
1312 1312
      } else {
1313 1313
        (*_blossom_data)[left].status = MATCHED;
1314 1314
        unmatchedToMatched(left);
1315 1315
      }
1316 1316

	
1317 1317
      if ((*_blossom_data)[right].status == EVEN) {
1318 1318
        int right_tree = _tree_set->find(right);
1319 1319
        alternatePath(right, right_tree);
1320 1320
        destroyTree(right_tree);
1321 1321
      } else {
1322 1322
        (*_blossom_data)[right].status = MATCHED;
1323 1323
        unmatchedToMatched(right);
1324 1324
      }
1325 1325

	
1326 1326
      (*_blossom_data)[left].next = _graph.direct(edge, true);
1327 1327
      (*_blossom_data)[right].next = _graph.direct(edge, false);
1328 1328
    }
1329 1329

	
1330 1330
    void extendOnArc(const Arc& arc) {
1331 1331
      int base = _blossom_set->find(_graph.target(arc));
1332 1332
      int tree = _tree_set->find(base);
1333 1333

	
1334 1334
      int odd = _blossom_set->find(_graph.source(arc));
1335 1335
      _tree_set->insert(odd, tree);
1336 1336
      (*_blossom_data)[odd].status = ODD;
1337 1337
      matchedToOdd(odd);
1338 1338
      (*_blossom_data)[odd].pred = arc;
1339 1339

	
1340 1340
      int even = _blossom_set->find(_graph.target((*_blossom_data)[odd].next));
1341 1341
      (*_blossom_data)[even].pred = (*_blossom_data)[even].next;
1342 1342
      _tree_set->insert(even, tree);
1343 1343
      (*_blossom_data)[even].status = EVEN;
1344 1344
      matchedToEven(even, tree);
1345 1345
    }
1346 1346

	
1347 1347
    void shrinkOnEdge(const Edge& edge, int tree) {
1348 1348
      int nca = -1;
1349 1349
      std::vector<int> left_path, right_path;
1350 1350

	
1351 1351
      {
1352 1352
        std::set<int> left_set, right_set;
1353 1353
        int left = _blossom_set->find(_graph.u(edge));
1354 1354
        left_path.push_back(left);
1355 1355
        left_set.insert(left);
1356 1356

	
1357 1357
        int right = _blossom_set->find(_graph.v(edge));
1358 1358
        right_path.push_back(right);
1359 1359
        right_set.insert(right);
1360 1360

	
1361 1361
        while (true) {
1362 1362

	
1363 1363
          if ((*_blossom_data)[left].pred == INVALID) break;
1364 1364

	
1365 1365
          left =
1366 1366
            _blossom_set->find(_graph.target((*_blossom_data)[left].pred));
1367 1367
          left_path.push_back(left);
1368 1368
          left =
1369 1369
            _blossom_set->find(_graph.target((*_blossom_data)[left].pred));
1370 1370
          left_path.push_back(left);
1371 1371

	
1372 1372
          left_set.insert(left);
1373 1373

	
1374 1374
          if (right_set.find(left) != right_set.end()) {
1375 1375
            nca = left;
1376 1376
            break;
1377 1377
          }
1378 1378

	
1379 1379
          if ((*_blossom_data)[right].pred == INVALID) break;
1380 1380

	
1381 1381
          right =
1382 1382
            _blossom_set->find(_graph.target((*_blossom_data)[right].pred));
1383 1383
          right_path.push_back(right);
1384 1384
          right =
1385 1385
            _blossom_set->find(_graph.target((*_blossom_data)[right].pred));
1386 1386
          right_path.push_back(right);
1387 1387

	
1388 1388
          right_set.insert(right);
1389 1389

	
1390 1390
          if (left_set.find(right) != left_set.end()) {
1391 1391
            nca = right;
1392 1392
            break;
1393 1393
          }
1394 1394

	
1395 1395
        }
1396 1396

	
1397 1397
        if (nca == -1) {
1398 1398
          if ((*_blossom_data)[left].pred == INVALID) {
1399 1399
            nca = right;
1400 1400
            while (left_set.find(nca) == left_set.end()) {
1401 1401
              nca =
1402 1402
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
1403 1403
              right_path.push_back(nca);
1404 1404
              nca =
1405 1405
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
1406 1406
              right_path.push_back(nca);
1407 1407
            }
1408 1408
          } else {
1409 1409
            nca = left;
1410 1410
            while (right_set.find(nca) == right_set.end()) {
1411 1411
              nca =
1412 1412
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
1413 1413
              left_path.push_back(nca);
1414 1414
              nca =
1415 1415
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
1416 1416
              left_path.push_back(nca);
1417 1417
            }
1418 1418
          }
1419 1419
        }
1420 1420
      }
1421 1421

	
1422 1422
      std::vector<int> subblossoms;
1423 1423
      Arc prev;
1424 1424

	
1425 1425
      prev = _graph.direct(edge, true);
1426 1426
      for (int i = 0; left_path[i] != nca; i += 2) {
1427 1427
        subblossoms.push_back(left_path[i]);
1428 1428
        (*_blossom_data)[left_path[i]].next = prev;
1429 1429
        _tree_set->erase(left_path[i]);
1430 1430

	
1431 1431
        subblossoms.push_back(left_path[i + 1]);
1432 1432
        (*_blossom_data)[left_path[i + 1]].status = EVEN;
1433 1433
        oddToEven(left_path[i + 1], tree);
1434 1434
        _tree_set->erase(left_path[i + 1]);
1435 1435
        prev = _graph.oppositeArc((*_blossom_data)[left_path[i + 1]].pred);
1436 1436
      }
1437 1437

	
1438 1438
      int k = 0;
1439 1439
      while (right_path[k] != nca) ++k;
1440 1440

	
1441 1441
      subblossoms.push_back(nca);
1442 1442
      (*_blossom_data)[nca].next = prev;
1443 1443

	
1444 1444
      for (int i = k - 2; i >= 0; i -= 2) {
1445 1445
        subblossoms.push_back(right_path[i + 1]);
1446 1446
        (*_blossom_data)[right_path[i + 1]].status = EVEN;
1447 1447
        oddToEven(right_path[i + 1], tree);
1448 1448
        _tree_set->erase(right_path[i + 1]);
1449 1449

	
1450 1450
        (*_blossom_data)[right_path[i + 1]].next =
1451 1451
          (*_blossom_data)[right_path[i + 1]].pred;
1452 1452

	
1453 1453
        subblossoms.push_back(right_path[i]);
1454 1454
        _tree_set->erase(right_path[i]);
1455 1455
      }
1456 1456

	
1457 1457
      int surface =
1458 1458
        _blossom_set->join(subblossoms.begin(), subblossoms.end());
1459 1459

	
1460 1460
      for (int i = 0; i < int(subblossoms.size()); ++i) {
1461 1461
        if (!_blossom_set->trivial(subblossoms[i])) {
1462 1462
          (*_blossom_data)[subblossoms[i]].pot += 2 * _delta_sum;
1463 1463
        }
1464 1464
        (*_blossom_data)[subblossoms[i]].status = MATCHED;
1465 1465
      }
1466 1466

	
1467 1467
      (*_blossom_data)[surface].pot = -2 * _delta_sum;
1468 1468
      (*_blossom_data)[surface].offset = 0;
1469 1469
      (*_blossom_data)[surface].status = EVEN;
1470 1470
      (*_blossom_data)[surface].pred = (*_blossom_data)[nca].pred;
1471 1471
      (*_blossom_data)[surface].next = (*_blossom_data)[nca].pred;
1472 1472

	
1473 1473
      _tree_set->insert(surface, tree);
1474 1474
      _tree_set->erase(nca);
1475 1475
    }
1476 1476

	
1477 1477
    void splitBlossom(int blossom) {
1478 1478
      Arc next = (*_blossom_data)[blossom].next;
1479 1479
      Arc pred = (*_blossom_data)[blossom].pred;
1480 1480

	
1481 1481
      int tree = _tree_set->find(blossom);
1482 1482

	
1483 1483
      (*_blossom_data)[blossom].status = MATCHED;
1484 1484
      oddToMatched(blossom);
1485 1485
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
1486 1486
        _delta2->erase(blossom);
1487 1487
      }
1488 1488

	
1489 1489
      std::vector<int> subblossoms;
1490 1490
      _blossom_set->split(blossom, std::back_inserter(subblossoms));
1491 1491

	
1492 1492
      Value offset = (*_blossom_data)[blossom].offset;
1493 1493
      int b = _blossom_set->find(_graph.source(pred));
1494 1494
      int d = _blossom_set->find(_graph.source(next));
1495 1495

	
1496 1496
      int ib = -1, id = -1;
1497 1497
      for (int i = 0; i < int(subblossoms.size()); ++i) {
1498 1498
        if (subblossoms[i] == b) ib = i;
1499 1499
        if (subblossoms[i] == d) id = i;
1500 1500

	
1501 1501
        (*_blossom_data)[subblossoms[i]].offset = offset;
1502 1502
        if (!_blossom_set->trivial(subblossoms[i])) {
1503 1503
          (*_blossom_data)[subblossoms[i]].pot -= 2 * offset;
1504 1504
        }
1505 1505
        if (_blossom_set->classPrio(subblossoms[i]) !=
1506 1506
            std::numeric_limits<Value>::max()) {
1507 1507
          _delta2->push(subblossoms[i],
1508 1508
                        _blossom_set->classPrio(subblossoms[i]) -
1509 1509
                        (*_blossom_data)[subblossoms[i]].offset);
1510 1510
        }
1511 1511
      }
1512 1512

	
1513 1513
      if (id > ib ? ((id - ib) % 2 == 0) : ((ib - id) % 2 == 1)) {
1514 1514
        for (int i = (id + 1) % subblossoms.size();
1515 1515
             i != ib; i = (i + 2) % subblossoms.size()) {
1516 1516
          int sb = subblossoms[i];
1517 1517
          int tb = subblossoms[(i + 1) % subblossoms.size()];
1518 1518
          (*_blossom_data)[sb].next =
1519 1519
            _graph.oppositeArc((*_blossom_data)[tb].next);
1520 1520
        }
1521 1521

	
1522 1522
        for (int i = ib; i != id; i = (i + 2) % subblossoms.size()) {
1523 1523
          int sb = subblossoms[i];
1524 1524
          int tb = subblossoms[(i + 1) % subblossoms.size()];
1525 1525
          int ub = subblossoms[(i + 2) % subblossoms.size()];
1526 1526

	
1527 1527
          (*_blossom_data)[sb].status = ODD;
1528 1528
          matchedToOdd(sb);
1529 1529
          _tree_set->insert(sb, tree);
1530 1530
          (*_blossom_data)[sb].pred = pred;
1531 1531
          (*_blossom_data)[sb].next =
1532 1532
                           _graph.oppositeArc((*_blossom_data)[tb].next);
1533 1533

	
1534 1534
          pred = (*_blossom_data)[ub].next;
1535 1535

	
1536 1536
          (*_blossom_data)[tb].status = EVEN;
1537 1537
          matchedToEven(tb, tree);
1538 1538
          _tree_set->insert(tb, tree);
1539 1539
          (*_blossom_data)[tb].pred = (*_blossom_data)[tb].next;
1540 1540
        }
1541 1541

	
1542 1542
        (*_blossom_data)[subblossoms[id]].status = ODD;
1543 1543
        matchedToOdd(subblossoms[id]);
1544 1544
        _tree_set->insert(subblossoms[id], tree);
1545 1545
        (*_blossom_data)[subblossoms[id]].next = next;
1546 1546
        (*_blossom_data)[subblossoms[id]].pred = pred;
1547 1547

	
1548 1548
      } else {
1549 1549

	
1550 1550
        for (int i = (ib + 1) % subblossoms.size();
1551 1551
             i != id; i = (i + 2) % subblossoms.size()) {
1552 1552
          int sb = subblossoms[i];
1553 1553
          int tb = subblossoms[(i + 1) % subblossoms.size()];
1554 1554
          (*_blossom_data)[sb].next =
1555 1555
            _graph.oppositeArc((*_blossom_data)[tb].next);
1556 1556
        }
1557 1557

	
1558 1558
        for (int i = id; i != ib; i = (i + 2) % subblossoms.size()) {
1559 1559
          int sb = subblossoms[i];
1560 1560
          int tb = subblossoms[(i + 1) % subblossoms.size()];
1561 1561
          int ub = subblossoms[(i + 2) % subblossoms.size()];
1562 1562

	
1563 1563
          (*_blossom_data)[sb].status = ODD;
1564 1564
          matchedToOdd(sb);
1565 1565
          _tree_set->insert(sb, tree);
1566 1566
          (*_blossom_data)[sb].next = next;
1567 1567
          (*_blossom_data)[sb].pred =
1568 1568
            _graph.oppositeArc((*_blossom_data)[tb].next);
1569 1569

	
1570 1570
          (*_blossom_data)[tb].status = EVEN;
1571 1571
          matchedToEven(tb, tree);
1572 1572
          _tree_set->insert(tb, tree);
1573 1573
          (*_blossom_data)[tb].pred =
1574 1574
            (*_blossom_data)[tb].next =
1575 1575
            _graph.oppositeArc((*_blossom_data)[ub].next);
1576 1576
          next = (*_blossom_data)[ub].next;
1577 1577
        }
1578 1578

	
1579 1579
        (*_blossom_data)[subblossoms[ib]].status = ODD;
1580 1580
        matchedToOdd(subblossoms[ib]);
1581 1581
        _tree_set->insert(subblossoms[ib], tree);
1582 1582
        (*_blossom_data)[subblossoms[ib]].next = next;
1583 1583
        (*_blossom_data)[subblossoms[ib]].pred = pred;
1584 1584
      }
1585 1585
      _tree_set->erase(blossom);
1586 1586
    }
1587 1587

	
1588 1588
    void extractBlossom(int blossom, const Node& base, const Arc& matching) {
1589 1589
      if (_blossom_set->trivial(blossom)) {
1590 1590
        int bi = (*_node_index)[base];
1591 1591
        Value pot = (*_node_data)[bi].pot;
1592 1592

	
1593 1593
        (*_matching)[base] = matching;
1594 1594
        _blossom_node_list.push_back(base);
1595 1595
        (*_node_potential)[base] = pot;
1596 1596
      } else {
1597 1597

	
1598 1598
        Value pot = (*_blossom_data)[blossom].pot;
1599 1599
        int bn = _blossom_node_list.size();
1600 1600

	
1601 1601
        std::vector<int> subblossoms;
1602 1602
        _blossom_set->split(blossom, std::back_inserter(subblossoms));
1603 1603
        int b = _blossom_set->find(base);
1604 1604
        int ib = -1;
1605 1605
        for (int i = 0; i < int(subblossoms.size()); ++i) {
1606 1606
          if (subblossoms[i] == b) { ib = i; break; }
1607 1607
        }
1608 1608

	
1609 1609
        for (int i = 1; i < int(subblossoms.size()); i += 2) {
1610 1610
          int sb = subblossoms[(ib + i) % subblossoms.size()];
1611 1611
          int tb = subblossoms[(ib + i + 1) % subblossoms.size()];
1612 1612

	
1613 1613
          Arc m = (*_blossom_data)[tb].next;
1614 1614
          extractBlossom(sb, _graph.target(m), _graph.oppositeArc(m));
1615 1615
          extractBlossom(tb, _graph.source(m), m);
1616 1616
        }
1617 1617
        extractBlossom(subblossoms[ib], base, matching);
1618 1618

	
1619 1619
        int en = _blossom_node_list.size();
1620 1620

	
1621 1621
        _blossom_potential.push_back(BlossomVariable(bn, en, pot));
1622 1622
      }
1623 1623
    }
1624 1624

	
1625 1625
    void extractMatching() {
1626 1626
      std::vector<int> blossoms;
1627 1627
      for (typename BlossomSet::ClassIt c(*_blossom_set); c != INVALID; ++c) {
1628 1628
        blossoms.push_back(c);
1629 1629
      }
1630 1630

	
1631 1631
      for (int i = 0; i < int(blossoms.size()); ++i) {
1632 1632
        if ((*_blossom_data)[blossoms[i]].status == MATCHED) {
1633 1633

	
1634 1634
          Value offset = (*_blossom_data)[blossoms[i]].offset;
1635 1635
          (*_blossom_data)[blossoms[i]].pot += 2 * offset;
1636 1636
          for (typename BlossomSet::ItemIt n(*_blossom_set, blossoms[i]);
1637 1637
               n != INVALID; ++n) {
1638 1638
            (*_node_data)[(*_node_index)[n]].pot -= offset;
1639 1639
          }
1640 1640

	
1641 1641
          Arc matching = (*_blossom_data)[blossoms[i]].next;
1642 1642
          Node base = _graph.source(matching);
1643 1643
          extractBlossom(blossoms[i], base, matching);
1644 1644
        } else {
1645 1645
          Node base = (*_blossom_data)[blossoms[i]].base;
1646 1646
          extractBlossom(blossoms[i], base, INVALID);
1647 1647
        }
1648 1648
      }
1649 1649
    }
1650 1650

	
1651 1651
  public:
1652 1652

	
1653 1653
    /// \brief Constructor
1654 1654
    ///
1655 1655
    /// Constructor.
1656 1656
    MaxWeightedMatching(const Graph& graph, const WeightMap& weight)
1657 1657
      : _graph(graph), _weight(weight), _matching(0),
1658 1658
        _node_potential(0), _blossom_potential(), _blossom_node_list(),
1659 1659
        _node_num(0), _blossom_num(0),
1660 1660

	
1661 1661
        _blossom_index(0), _blossom_set(0), _blossom_data(0),
1662 1662
        _node_index(0), _node_heap_index(0), _node_data(0),
1663 1663
        _tree_set_index(0), _tree_set(0),
1664 1664

	
1665 1665
        _delta1_index(0), _delta1(0),
1666 1666
        _delta2_index(0), _delta2(0),
1667 1667
        _delta3_index(0), _delta3(0),
1668 1668
        _delta4_index(0), _delta4(0),
1669 1669

	
1670 1670
        _delta_sum() {}
1671 1671

	
1672 1672
    ~MaxWeightedMatching() {
1673 1673
      destroyStructures();
1674 1674
    }
1675 1675

	
1676 1676
    /// \name Execution Control
1677 1677
    /// The simplest way to execute the algorithm is to use the
1678 1678
    /// \ref run() member function.
1679 1679

	
1680 1680
    ///@{
1681 1681

	
1682 1682
    /// \brief Initialize the algorithm
1683 1683
    ///
1684 1684
    /// This function initializes the algorithm.
1685 1685
    void init() {
1686 1686
      createStructures();
1687 1687

	
1688 1688
      for (ArcIt e(_graph); e != INVALID; ++e) {
1689 1689
        (*_node_heap_index)[e] = BinHeap<Value, IntArcMap>::PRE_HEAP;
1690 1690
      }
1691 1691
      for (NodeIt n(_graph); n != INVALID; ++n) {
1692 1692
        (*_delta1_index)[n] = _delta1->PRE_HEAP;
1693 1693
      }
1694 1694
      for (EdgeIt e(_graph); e != INVALID; ++e) {
1695 1695
        (*_delta3_index)[e] = _delta3->PRE_HEAP;
1696 1696
      }
1697 1697
      for (int i = 0; i < _blossom_num; ++i) {
1698 1698
        (*_delta2_index)[i] = _delta2->PRE_HEAP;
1699 1699
        (*_delta4_index)[i] = _delta4->PRE_HEAP;
1700 1700
      }
1701 1701

	
1702 1702
      int index = 0;
1703 1703
      for (NodeIt n(_graph); n != INVALID; ++n) {
1704 1704
        Value max = 0;
1705 1705
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
1706 1706
          if (_graph.target(e) == n) continue;
1707 1707
          if ((dualScale * _weight[e]) / 2 > max) {
1708 1708
            max = (dualScale * _weight[e]) / 2;
1709 1709
          }
1710 1710
        }
1711 1711
        (*_node_index)[n] = index;
1712 1712
        (*_node_data)[index].pot = max;
1713 1713
        _delta1->push(n, max);
1714 1714
        int blossom =
1715 1715
          _blossom_set->insert(n, std::numeric_limits<Value>::max());
1716 1716

	
1717 1717
        _tree_set->insert(blossom);
1718 1718

	
1719 1719
        (*_blossom_data)[blossom].status = EVEN;
1720 1720
        (*_blossom_data)[blossom].pred = INVALID;
1721 1721
        (*_blossom_data)[blossom].next = INVALID;
1722 1722
        (*_blossom_data)[blossom].pot = 0;
1723 1723
        (*_blossom_data)[blossom].offset = 0;
1724 1724
        ++index;
1725 1725
      }
1726 1726
      for (EdgeIt e(_graph); e != INVALID; ++e) {
1727 1727
        int si = (*_node_index)[_graph.u(e)];
1728 1728
        int ti = (*_node_index)[_graph.v(e)];
1729 1729
        if (_graph.u(e) != _graph.v(e)) {
1730 1730
          _delta3->push(e, ((*_node_data)[si].pot + (*_node_data)[ti].pot -
1731 1731
                            dualScale * _weight[e]) / 2);
1732 1732
        }
1733 1733
      }
1734 1734
    }
1735 1735

	
1736 1736
    /// \brief Start the algorithm
1737 1737
    ///
1738 1738
    /// This function starts the algorithm.
1739 1739
    ///
1740 1740
    /// \pre \ref init() must be called before using this function.
1741 1741
    void start() {
1742 1742
      enum OpType {
1743 1743
        D1, D2, D3, D4
1744 1744
      };
1745 1745

	
1746 1746
      int unmatched = _node_num;
1747 1747
      while (unmatched > 0) {
1748 1748
        Value d1 = !_delta1->empty() ?
1749 1749
          _delta1->prio() : std::numeric_limits<Value>::max();
1750 1750

	
1751 1751
        Value d2 = !_delta2->empty() ?
1752 1752
          _delta2->prio() : std::numeric_limits<Value>::max();
1753 1753

	
1754 1754
        Value d3 = !_delta3->empty() ?
1755 1755
          _delta3->prio() : std::numeric_limits<Value>::max();
1756 1756

	
1757 1757
        Value d4 = !_delta4->empty() ?
1758 1758
          _delta4->prio() : std::numeric_limits<Value>::max();
1759 1759

	
1760 1760
        _delta_sum = d1; OpType ot = D1;
1761 1761
        if (d2 < _delta_sum) { _delta_sum = d2; ot = D2; }
1762 1762
        if (d3 < _delta_sum) { _delta_sum = d3; ot = D3; }
1763 1763
        if (d4 < _delta_sum) { _delta_sum = d4; ot = D4; }
1764 1764

	
1765 1765

	
1766 1766
        switch (ot) {
1767 1767
        case D1:
1768 1768
          {
1769 1769
            Node n = _delta1->top();
1770 1770
            unmatchNode(n);
1771 1771
            --unmatched;
1772 1772
          }
1773 1773
          break;
1774 1774
        case D2:
1775 1775
          {
1776 1776
            int blossom = _delta2->top();
1777 1777
            Node n = _blossom_set->classTop(blossom);
1778 1778
            Arc e = (*_node_data)[(*_node_index)[n]].heap.top();
1779 1779
            extendOnArc(e);
1780 1780
          }
1781 1781
          break;
1782 1782
        case D3:
1783 1783
          {
1784 1784
            Edge e = _delta3->top();
1785 1785

	
1786 1786
            int left_blossom = _blossom_set->find(_graph.u(e));
1787 1787
            int right_blossom = _blossom_set->find(_graph.v(e));
1788 1788

	
1789 1789
            if (left_blossom == right_blossom) {
1790 1790
              _delta3->pop();
1791 1791
            } else {
1792 1792
              int left_tree;
1793 1793
              if ((*_blossom_data)[left_blossom].status == EVEN) {
1794 1794
                left_tree = _tree_set->find(left_blossom);
1795 1795
              } else {
1796 1796
                left_tree = -1;
1797 1797
                ++unmatched;
1798 1798
              }
1799 1799
              int right_tree;
1800 1800
              if ((*_blossom_data)[right_blossom].status == EVEN) {
1801 1801
                right_tree = _tree_set->find(right_blossom);
1802 1802
              } else {
1803 1803
                right_tree = -1;
1804 1804
                ++unmatched;
1805 1805
              }
1806 1806

	
1807 1807
              if (left_tree == right_tree) {
1808 1808
                shrinkOnEdge(e, left_tree);
1809 1809
              } else {
1810 1810
                augmentOnEdge(e);
1811 1811
                unmatched -= 2;
1812 1812
              }
1813 1813
            }
1814 1814
          } break;
1815 1815
        case D4:
1816 1816
          splitBlossom(_delta4->top());
1817 1817
          break;
1818 1818
        }
1819 1819
      }
1820 1820
      extractMatching();
1821 1821
    }
1822 1822

	
1823 1823
    /// \brief Run the algorithm.
1824 1824
    ///
1825 1825
    /// This method runs the \c %MaxWeightedMatching algorithm.
1826 1826
    ///
1827 1827
    /// \note mwm.run() is just a shortcut of the following code.
1828 1828
    /// \code
1829 1829
    ///   mwm.init();
1830 1830
    ///   mwm.start();
1831 1831
    /// \endcode
1832 1832
    void run() {
1833 1833
      init();
1834 1834
      start();
1835 1835
    }
1836 1836

	
1837 1837
    /// @}
1838 1838

	
1839 1839
    /// \name Primal Solution
1840 1840
    /// Functions to get the primal solution, i.e. the maximum weighted 
1841 1841
    /// matching.\n
1842 1842
    /// Either \ref run() or \ref start() function should be called before
1843 1843
    /// using them.
1844 1844

	
1845 1845
    /// @{
1846 1846

	
1847 1847
    /// \brief Return the weight of the matching.
1848 1848
    ///
1849 1849
    /// This function returns the weight of the found matching.
1850 1850
    ///
1851 1851
    /// \pre Either run() or start() must be called before using this function.
1852 1852
    Value matchingWeight() const {
1853 1853
      Value sum = 0;
1854 1854
      for (NodeIt n(_graph); n != INVALID; ++n) {
1855 1855
        if ((*_matching)[n] != INVALID) {
1856 1856
          sum += _weight[(*_matching)[n]];
1857 1857
        }
1858 1858
      }
1859 1859
      return sum /= 2;
1860 1860
    }
1861 1861

	
1862 1862
    /// \brief Return the size (cardinality) of the matching.
1863 1863
    ///
1864 1864
    /// This function returns the size (cardinality) of the found matching.
1865 1865
    ///
1866 1866
    /// \pre Either run() or start() must be called before using this function.
1867 1867
    int matchingSize() const {
1868 1868
      int num = 0;
1869 1869
      for (NodeIt n(_graph); n != INVALID; ++n) {
1870 1870
        if ((*_matching)[n] != INVALID) {
1871 1871
          ++num;
1872 1872
        }
1873 1873
      }
1874 1874
      return num /= 2;
1875 1875
    }
1876 1876

	
1877 1877
    /// \brief Return \c true if the given edge is in the matching.
1878 1878
    ///
1879 1879
    /// This function returns \c true if the given edge is in the found 
1880 1880
    /// matching.
1881 1881
    ///
1882 1882
    /// \pre Either run() or start() must be called before using this function.
1883 1883
    bool matching(const Edge& edge) const {
1884 1884
      return edge == (*_matching)[_graph.u(edge)];
1885 1885
    }
1886 1886

	
1887 1887
    /// \brief Return the matching arc (or edge) incident to the given node.
1888 1888
    ///
1889 1889
    /// This function returns the matching arc (or edge) incident to the
1890 1890
    /// given node in the found matching or \c INVALID if the node is 
1891 1891
    /// not covered by the matching.
1892 1892
    ///
1893 1893
    /// \pre Either run() or start() must be called before using this function.
1894 1894
    Arc matching(const Node& node) const {
1895 1895
      return (*_matching)[node];
1896 1896
    }
1897 1897

	
1898 1898
    /// \brief Return a const reference to the matching map.
1899 1899
    ///
1900 1900
    /// This function returns a const reference to a node map that stores
1901 1901
    /// the matching arc (or edge) incident to each node.
1902 1902
    const MatchingMap& matchingMap() const {
1903 1903
      return *_matching;
1904 1904
    }
1905 1905

	
1906 1906
    /// \brief Return the mate of the given node.
1907 1907
    ///
1908 1908
    /// This function returns the mate of the given node in the found 
1909 1909
    /// matching or \c INVALID if the node is not covered by the matching.
1910 1910
    ///
1911 1911
    /// \pre Either run() or start() must be called before using this function.
1912 1912
    Node mate(const Node& node) const {
1913 1913
      return (*_matching)[node] != INVALID ?
1914 1914
        _graph.target((*_matching)[node]) : INVALID;
1915 1915
    }
1916 1916

	
1917 1917
    /// @}
1918 1918

	
1919 1919
    /// \name Dual Solution
1920 1920
    /// Functions to get the dual solution.\n
1921 1921
    /// Either \ref run() or \ref start() function should be called before
1922 1922
    /// using them.
1923 1923

	
1924 1924
    /// @{
1925 1925

	
1926 1926
    /// \brief Return the value of the dual solution.
1927 1927
    ///
1928 1928
    /// This function returns the value of the dual solution. 
1929 1929
    /// It should be equal to the primal value scaled by \ref dualScale 
1930 1930
    /// "dual scale".
1931 1931
    ///
1932 1932
    /// \pre Either run() or start() must be called before using this function.
1933 1933
    Value dualValue() const {
1934 1934
      Value sum = 0;
1935 1935
      for (NodeIt n(_graph); n != INVALID; ++n) {
1936 1936
        sum += nodeValue(n);
1937 1937
      }
1938 1938
      for (int i = 0; i < blossomNum(); ++i) {
1939 1939
        sum += blossomValue(i) * (blossomSize(i) / 2);
1940 1940
      }
1941 1941
      return sum;
1942 1942
    }
1943 1943

	
1944 1944
    /// \brief Return the dual value (potential) of the given node.
1945 1945
    ///
1946 1946
    /// This function returns the dual value (potential) of the given node.
1947 1947
    ///
1948 1948
    /// \pre Either run() or start() must be called before using this function.
1949 1949
    Value nodeValue(const Node& n) const {
1950 1950
      return (*_node_potential)[n];
1951 1951
    }
1952 1952

	
1953 1953
    /// \brief Return the number of the blossoms in the basis.
1954 1954
    ///
1955 1955
    /// This function returns the number of the blossoms in the basis.
1956 1956
    ///
1957 1957
    /// \pre Either run() or start() must be called before using this function.
1958 1958
    /// \see BlossomIt
1959 1959
    int blossomNum() const {
1960 1960
      return _blossom_potential.size();
1961 1961
    }
1962 1962

	
1963 1963
    /// \brief Return the number of the nodes in the given blossom.
1964 1964
    ///
1965 1965
    /// This function returns the number of the nodes in the given blossom.
1966 1966
    ///
1967 1967
    /// \pre Either run() or start() must be called before using this function.
1968 1968
    /// \see BlossomIt
1969 1969
    int blossomSize(int k) const {
1970 1970
      return _blossom_potential[k].end - _blossom_potential[k].begin;
1971 1971
    }
1972 1972

	
1973 1973
    /// \brief Return the dual value (ptential) of the given blossom.
1974 1974
    ///
1975 1975
    /// This function returns the dual value (ptential) of the given blossom.
1976 1976
    ///
1977 1977
    /// \pre Either run() or start() must be called before using this function.
1978 1978
    Value blossomValue(int k) const {
1979 1979
      return _blossom_potential[k].value;
1980 1980
    }
1981 1981

	
1982 1982
    /// \brief Iterator for obtaining the nodes of a blossom.
1983 1983
    ///
1984 1984
    /// This class provides an iterator for obtaining the nodes of the 
1985 1985
    /// given blossom. It lists a subset of the nodes.
1986 1986
    /// Before using this iterator, you must allocate a 
1987 1987
    /// MaxWeightedMatching class and execute it.
1988 1988
    class BlossomIt {
1989 1989
    public:
1990 1990

	
1991 1991
      /// \brief Constructor.
1992 1992
      ///
1993 1993
      /// Constructor to get the nodes of the given variable.
1994 1994
      ///
1995 1995
      /// \pre Either \ref MaxWeightedMatching::run() "algorithm.run()" or 
1996 1996
      /// \ref MaxWeightedMatching::start() "algorithm.start()" must be 
1997 1997
      /// called before initializing this iterator.
1998 1998
      BlossomIt(const MaxWeightedMatching& algorithm, int variable)
1999 1999
        : _algorithm(&algorithm)
2000 2000
      {
2001 2001
        _index = _algorithm->_blossom_potential[variable].begin;
2002 2002
        _last = _algorithm->_blossom_potential[variable].end;
2003 2003
      }
2004 2004

	
2005 2005
      /// \brief Conversion to \c Node.
2006 2006
      ///
2007 2007
      /// Conversion to \c Node.
2008 2008
      operator Node() const {
2009 2009
        return _algorithm->_blossom_node_list[_index];
2010 2010
      }
2011 2011

	
2012 2012
      /// \brief Increment operator.
2013 2013
      ///
2014 2014
      /// Increment operator.
2015 2015
      BlossomIt& operator++() {
2016 2016
        ++_index;
2017 2017
        return *this;
2018 2018
      }
2019 2019

	
2020 2020
      /// \brief Validity checking
2021 2021
      ///
2022 2022
      /// Checks whether the iterator is invalid.
2023 2023
      bool operator==(Invalid) const { return _index == _last; }
2024 2024

	
2025 2025
      /// \brief Validity checking
2026 2026
      ///
2027 2027
      /// Checks whether the iterator is valid.
2028 2028
      bool operator!=(Invalid) const { return _index != _last; }
2029 2029

	
2030 2030
    private:
2031 2031
      const MaxWeightedMatching* _algorithm;
2032 2032
      int _last;
2033 2033
      int _index;
2034 2034
    };
2035 2035

	
2036 2036
    /// @}
2037 2037

	
2038 2038
  };
2039 2039

	
2040 2040
  /// \ingroup matching
2041 2041
  ///
2042 2042
  /// \brief Weighted perfect matching in general graphs
2043 2043
  ///
2044 2044
  /// This class provides an efficient implementation of Edmond's
2045 2045
  /// maximum weighted perfect matching algorithm. The implementation
2046 2046
  /// is based on extensive use of priority queues and provides
2047 2047
  /// \f$O(nm\log n)\f$ time complexity.
2048 2048
  ///
2049 2049
  /// The maximum weighted perfect matching problem is to find a subset of 
2050 2050
  /// the edges in an undirected graph with maximum overall weight for which 
2051 2051
  /// each node has exactly one incident edge.
2052 2052
  /// It can be formulated with the following linear program.
2053 2053
  /// \f[ \sum_{e \in \delta(u)}x_e = 1 \quad \forall u\in V\f]
2054 2054
  /** \f[ \sum_{e \in \gamma(B)}x_e \le \frac{\vert B \vert - 1}{2}
2055 2055
      \quad \forall B\in\mathcal{O}\f] */
2056 2056
  /// \f[x_e \ge 0\quad \forall e\in E\f]
2057 2057
  /// \f[\max \sum_{e\in E}x_ew_e\f]
2058 2058
  /// where \f$\delta(X)\f$ is the set of edges incident to a node in
2059 2059
  /// \f$X\f$, \f$\gamma(X)\f$ is the set of edges with both ends in
2060 2060
  /// \f$X\f$ and \f$\mathcal{O}\f$ is the set of odd cardinality
2061 2061
  /// subsets of the nodes.
2062 2062
  ///
2063 2063
  /// The algorithm calculates an optimal matching and a proof of the
2064 2064
  /// optimality. The solution of the dual problem can be used to check
2065 2065
  /// the result of the algorithm. The dual linear problem is the
2066 2066
  /// following.
2067 2067
  /** \f[ y_u + y_v + \sum_{B \in \mathcal{O}, uv \in \gamma(B)}z_B \ge
2068 2068
      w_{uv} \quad \forall uv\in E\f] */
2069 2069
  /// \f[z_B \ge 0 \quad \forall B \in \mathcal{O}\f]
2070 2070
  /** \f[\min \sum_{u \in V}y_u + \sum_{B \in \mathcal{O}}
2071 2071
      \frac{\vert B \vert - 1}{2}z_B\f] */
2072 2072
  ///
2073 2073
  /// The algorithm can be executed with the run() function. 
2074 2074
  /// After it the matching (the primal solution) and the dual solution
2075 2075
  /// can be obtained using the query functions and the 
2076 2076
  /// \ref MaxWeightedPerfectMatching::BlossomIt "BlossomIt" nested class, 
2077 2077
  /// which is able to iterate on the nodes of a blossom. 
2078 2078
  /// If the value type is integer, then the dual solution is multiplied
2079 2079
  /// by \ref MaxWeightedMatching::dualScale "4".
2080 2080
  ///
2081 2081
  /// \tparam GR The undirected graph type the algorithm runs on.
2082 2082
  /// \tparam WM The type edge weight map. The default type is 
2083 2083
  /// \ref concepts::Graph::EdgeMap "GR::EdgeMap<int>".
2084 2084
#ifdef DOXYGEN
2085 2085
  template <typename GR, typename WM>
2086 2086
#else
2087 2087
  template <typename GR,
2088 2088
            typename WM = typename GR::template EdgeMap<int> >
2089 2089
#endif
2090 2090
  class MaxWeightedPerfectMatching {
2091 2091
  public:
2092 2092

	
2093 2093
    /// The graph type of the algorithm
2094 2094
    typedef GR Graph;
2095 2095
    /// The type of the edge weight map
2096 2096
    typedef WM WeightMap;
2097 2097
    /// The value type of the edge weights
2098 2098
    typedef typename WeightMap::Value Value;
2099 2099

	
2100 2100
    /// \brief Scaling factor for dual solution
2101 2101
    ///
2102 2102
    /// Scaling factor for dual solution, it is equal to 4 or 1
2103 2103
    /// according to the value type.
2104 2104
    static const int dualScale =
2105 2105
      std::numeric_limits<Value>::is_integer ? 4 : 1;
2106 2106

	
2107 2107
    /// The type of the matching map
2108 2108
    typedef typename Graph::template NodeMap<typename Graph::Arc>
2109 2109
    MatchingMap;
2110 2110

	
2111 2111
  private:
2112 2112

	
2113 2113
    TEMPLATE_GRAPH_TYPEDEFS(Graph);
2114 2114

	
2115 2115
    typedef typename Graph::template NodeMap<Value> NodePotential;
2116 2116
    typedef std::vector<Node> BlossomNodeList;
2117 2117

	
2118 2118
    struct BlossomVariable {
2119 2119
      int begin, end;
2120 2120
      Value value;
2121 2121

	
2122 2122
      BlossomVariable(int _begin, int _end, Value _value)
2123 2123
        : begin(_begin), end(_end), value(_value) {}
2124 2124

	
2125 2125
    };
2126 2126

	
2127 2127
    typedef std::vector<BlossomVariable> BlossomPotential;
2128 2128

	
2129 2129
    const Graph& _graph;
2130 2130
    const WeightMap& _weight;
2131 2131

	
2132 2132
    MatchingMap* _matching;
2133 2133

	
2134 2134
    NodePotential* _node_potential;
2135 2135

	
2136 2136
    BlossomPotential _blossom_potential;
2137 2137
    BlossomNodeList _blossom_node_list;
2138 2138

	
2139 2139
    int _node_num;
2140 2140
    int _blossom_num;
2141 2141

	
2142 2142
    typedef RangeMap<int> IntIntMap;
2143 2143

	
2144 2144
    enum Status {
2145 2145
      EVEN = -1, MATCHED = 0, ODD = 1
2146 2146
    };
2147 2147

	
2148 2148
    typedef HeapUnionFind<Value, IntNodeMap> BlossomSet;
2149 2149
    struct BlossomData {
2150 2150
      int tree;
2151 2151
      Status status;
2152 2152
      Arc pred, next;
2153 2153
      Value pot, offset;
2154 2154
    };
2155 2155

	
2156 2156
    IntNodeMap *_blossom_index;
2157 2157
    BlossomSet *_blossom_set;
2158 2158
    RangeMap<BlossomData>* _blossom_data;
2159 2159

	
2160 2160
    IntNodeMap *_node_index;
2161 2161
    IntArcMap *_node_heap_index;
2162 2162

	
2163 2163
    struct NodeData {
2164 2164

	
2165 2165
      NodeData(IntArcMap& node_heap_index)
2166 2166
        : heap(node_heap_index) {}
2167 2167

	
2168 2168
      int blossom;
2169 2169
      Value pot;
2170 2170
      BinHeap<Value, IntArcMap> heap;
2171 2171
      std::map<int, Arc> heap_index;
2172 2172

	
2173 2173
      int tree;
2174 2174
    };
2175 2175

	
2176 2176
    RangeMap<NodeData>* _node_data;
2177 2177

	
2178 2178
    typedef ExtendFindEnum<IntIntMap> TreeSet;
2179 2179

	
2180 2180
    IntIntMap *_tree_set_index;
2181 2181
    TreeSet *_tree_set;
2182 2182

	
2183 2183
    IntIntMap *_delta2_index;
2184 2184
    BinHeap<Value, IntIntMap> *_delta2;
2185 2185

	
2186 2186
    IntEdgeMap *_delta3_index;
2187 2187
    BinHeap<Value, IntEdgeMap> *_delta3;
2188 2188

	
2189 2189
    IntIntMap *_delta4_index;
2190 2190
    BinHeap<Value, IntIntMap> *_delta4;
2191 2191

	
2192 2192
    Value _delta_sum;
2193 2193

	
2194 2194
    void createStructures() {
2195 2195
      _node_num = countNodes(_graph);
2196 2196
      _blossom_num = _node_num * 3 / 2;
2197 2197

	
2198 2198
      if (!_matching) {
2199 2199
        _matching = new MatchingMap(_graph);
2200 2200
      }
2201 2201
      if (!_node_potential) {
2202 2202
        _node_potential = new NodePotential(_graph);
2203 2203
      }
2204 2204
      if (!_blossom_set) {
2205 2205
        _blossom_index = new IntNodeMap(_graph);
2206 2206
        _blossom_set = new BlossomSet(*_blossom_index);
2207 2207
        _blossom_data = new RangeMap<BlossomData>(_blossom_num);
2208 2208
      }
2209 2209

	
2210 2210
      if (!_node_index) {
2211 2211
        _node_index = new IntNodeMap(_graph);
2212 2212
        _node_heap_index = new IntArcMap(_graph);
2213 2213
        _node_data = new RangeMap<NodeData>(_node_num,
2214 2214
                                            NodeData(*_node_heap_index));
2215 2215
      }
2216 2216

	
2217 2217
      if (!_tree_set) {
2218 2218
        _tree_set_index = new IntIntMap(_blossom_num);
2219 2219
        _tree_set = new TreeSet(*_tree_set_index);
2220 2220
      }
2221 2221
      if (!_delta2) {
2222 2222
        _delta2_index = new IntIntMap(_blossom_num);
2223 2223
        _delta2 = new BinHeap<Value, IntIntMap>(*_delta2_index);
2224 2224
      }
2225 2225
      if (!_delta3) {
2226 2226
        _delta3_index = new IntEdgeMap(_graph);
2227 2227
        _delta3 = new BinHeap<Value, IntEdgeMap>(*_delta3_index);
2228 2228
      }
2229 2229
      if (!_delta4) {
2230 2230
        _delta4_index = new IntIntMap(_blossom_num);
2231 2231
        _delta4 = new BinHeap<Value, IntIntMap>(*_delta4_index);
2232 2232
      }
2233 2233
    }
2234 2234

	
2235 2235
    void destroyStructures() {
2236 2236
      _node_num = countNodes(_graph);
2237 2237
      _blossom_num = _node_num * 3 / 2;
2238 2238

	
2239 2239
      if (_matching) {
2240 2240
        delete _matching;
2241 2241
      }
2242 2242
      if (_node_potential) {
2243 2243
        delete _node_potential;
2244 2244
      }
2245 2245
      if (_blossom_set) {
2246 2246
        delete _blossom_index;
2247 2247
        delete _blossom_set;
2248 2248
        delete _blossom_data;
2249 2249
      }
2250 2250

	
2251 2251
      if (_node_index) {
2252 2252
        delete _node_index;
2253 2253
        delete _node_heap_index;
2254 2254
        delete _node_data;
2255 2255
      }
2256 2256

	
2257 2257
      if (_tree_set) {
2258 2258
        delete _tree_set_index;
2259 2259
        delete _tree_set;
2260 2260
      }
2261 2261
      if (_delta2) {
2262 2262
        delete _delta2_index;
2263 2263
        delete _delta2;
2264 2264
      }
2265 2265
      if (_delta3) {
2266 2266
        delete _delta3_index;
2267 2267
        delete _delta3;
2268 2268
      }
2269 2269
      if (_delta4) {
2270 2270
        delete _delta4_index;
2271 2271
        delete _delta4;
2272 2272
      }
2273 2273
    }
2274 2274

	
2275 2275
    void matchedToEven(int blossom, int tree) {
2276 2276
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
2277 2277
        _delta2->erase(blossom);
2278 2278
      }
2279 2279

	
2280 2280
      if (!_blossom_set->trivial(blossom)) {
2281 2281
        (*_blossom_data)[blossom].pot -=
2282 2282
          2 * (_delta_sum - (*_blossom_data)[blossom].offset);
2283 2283
      }
2284 2284

	
2285 2285
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
2286 2286
           n != INVALID; ++n) {
2287 2287

	
2288 2288
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
2289 2289
        int ni = (*_node_index)[n];
2290 2290

	
2291 2291
        (*_node_data)[ni].heap.clear();
2292 2292
        (*_node_data)[ni].heap_index.clear();
2293 2293

	
2294 2294
        (*_node_data)[ni].pot += _delta_sum - (*_blossom_data)[blossom].offset;
2295 2295

	
2296 2296
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
2297 2297
          Node v = _graph.source(e);
2298 2298
          int vb = _blossom_set->find(v);
2299 2299
          int vi = (*_node_index)[v];
2300 2300

	
2301 2301
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
2302 2302
            dualScale * _weight[e];
2303 2303

	
2304 2304
          if ((*_blossom_data)[vb].status == EVEN) {
2305 2305
            if (_delta3->state(e) != _delta3->IN_HEAP && blossom != vb) {
2306 2306
              _delta3->push(e, rw / 2);
2307 2307
            }
2308 2308
          } else {
2309 2309
            typename std::map<int, Arc>::iterator it =
2310 2310
              (*_node_data)[vi].heap_index.find(tree);
2311 2311

	
2312 2312
            if (it != (*_node_data)[vi].heap_index.end()) {
2313 2313
              if ((*_node_data)[vi].heap[it->second] > rw) {
2314 2314
                (*_node_data)[vi].heap.replace(it->second, e);
2315 2315
                (*_node_data)[vi].heap.decrease(e, rw);
2316 2316
                it->second = e;
2317 2317
              }
2318 2318
            } else {
2319 2319
              (*_node_data)[vi].heap.push(e, rw);
2320 2320
              (*_node_data)[vi].heap_index.insert(std::make_pair(tree, e));
2321 2321
            }
2322 2322

	
2323 2323
            if ((*_blossom_set)[v] > (*_node_data)[vi].heap.prio()) {
2324 2324
              _blossom_set->decrease(v, (*_node_data)[vi].heap.prio());
2325 2325

	
2326 2326
              if ((*_blossom_data)[vb].status == MATCHED) {
2327 2327
                if (_delta2->state(vb) != _delta2->IN_HEAP) {
2328 2328
                  _delta2->push(vb, _blossom_set->classPrio(vb) -
2329 2329
                               (*_blossom_data)[vb].offset);
2330 2330
                } else if ((*_delta2)[vb] > _blossom_set->classPrio(vb) -
2331 2331
                           (*_blossom_data)[vb].offset){
2332 2332
                  _delta2->decrease(vb, _blossom_set->classPrio(vb) -
2333 2333
                                   (*_blossom_data)[vb].offset);
2334 2334
                }
2335 2335
              }
2336 2336
            }
2337 2337
          }
2338 2338
        }
2339 2339
      }
2340 2340
      (*_blossom_data)[blossom].offset = 0;
2341 2341
    }
2342 2342

	
2343 2343
    void matchedToOdd(int blossom) {
2344 2344
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
2345 2345
        _delta2->erase(blossom);
2346 2346
      }
2347 2347
      (*_blossom_data)[blossom].offset += _delta_sum;
2348 2348
      if (!_blossom_set->trivial(blossom)) {
2349 2349
        _delta4->push(blossom, (*_blossom_data)[blossom].pot / 2 +
2350 2350
                     (*_blossom_data)[blossom].offset);
2351 2351
      }
2352 2352
    }
2353 2353

	
2354 2354
    void evenToMatched(int blossom, int tree) {
2355 2355
      if (!_blossom_set->trivial(blossom)) {
2356 2356
        (*_blossom_data)[blossom].pot += 2 * _delta_sum;
2357 2357
      }
2358 2358

	
2359 2359
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
2360 2360
           n != INVALID; ++n) {
2361 2361
        int ni = (*_node_index)[n];
2362 2362
        (*_node_data)[ni].pot -= _delta_sum;
2363 2363

	
2364 2364
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
2365 2365
          Node v = _graph.source(e);
2366 2366
          int vb = _blossom_set->find(v);
2367 2367
          int vi = (*_node_index)[v];
2368 2368

	
2369 2369
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
2370 2370
            dualScale * _weight[e];
2371 2371

	
2372 2372
          if (vb == blossom) {
2373 2373
            if (_delta3->state(e) == _delta3->IN_HEAP) {
2374 2374
              _delta3->erase(e);
2375 2375
            }
2376 2376
          } else if ((*_blossom_data)[vb].status == EVEN) {
2377 2377

	
2378 2378
            if (_delta3->state(e) == _delta3->IN_HEAP) {
2379 2379
              _delta3->erase(e);
2380 2380
            }
2381 2381

	
2382 2382
            int vt = _tree_set->find(vb);
2383 2383

	
2384 2384
            if (vt != tree) {
2385 2385

	
2386 2386
              Arc r = _graph.oppositeArc(e);
2387 2387

	
2388 2388
              typename std::map<int, Arc>::iterator it =
2389 2389
                (*_node_data)[ni].heap_index.find(vt);
2390 2390

	
2391 2391
              if (it != (*_node_data)[ni].heap_index.end()) {
2392 2392
                if ((*_node_data)[ni].heap[it->second] > rw) {
2393 2393
                  (*_node_data)[ni].heap.replace(it->second, r);
2394 2394
                  (*_node_data)[ni].heap.decrease(r, rw);
2395 2395
                  it->second = r;
2396 2396
                }
2397 2397
              } else {
2398 2398
                (*_node_data)[ni].heap.push(r, rw);
2399 2399
                (*_node_data)[ni].heap_index.insert(std::make_pair(vt, r));
2400 2400
              }
2401 2401

	
2402 2402
              if ((*_blossom_set)[n] > (*_node_data)[ni].heap.prio()) {
2403 2403
                _blossom_set->decrease(n, (*_node_data)[ni].heap.prio());
2404 2404

	
2405 2405
                if (_delta2->state(blossom) != _delta2->IN_HEAP) {
2406 2406
                  _delta2->push(blossom, _blossom_set->classPrio(blossom) -
2407 2407
                               (*_blossom_data)[blossom].offset);
2408 2408
                } else if ((*_delta2)[blossom] >
2409 2409
                           _blossom_set->classPrio(blossom) -
2410 2410
                           (*_blossom_data)[blossom].offset){
2411 2411
                  _delta2->decrease(blossom, _blossom_set->classPrio(blossom) -
2412 2412
                                   (*_blossom_data)[blossom].offset);
2413 2413
                }
2414 2414
              }
2415 2415
            }
2416 2416
          } else {
2417 2417

	
2418 2418
            typename std::map<int, Arc>::iterator it =
2419 2419
              (*_node_data)[vi].heap_index.find(tree);
2420 2420

	
2421 2421
            if (it != (*_node_data)[vi].heap_index.end()) {
2422 2422
              (*_node_data)[vi].heap.erase(it->second);
2423 2423
              (*_node_data)[vi].heap_index.erase(it);
2424 2424
              if ((*_node_data)[vi].heap.empty()) {
2425 2425
                _blossom_set->increase(v, std::numeric_limits<Value>::max());
2426 2426
              } else if ((*_blossom_set)[v] < (*_node_data)[vi].heap.prio()) {
2427 2427
                _blossom_set->increase(v, (*_node_data)[vi].heap.prio());
2428 2428
              }
2429 2429

	
2430 2430
              if ((*_blossom_data)[vb].status == MATCHED) {
2431 2431
                if (_blossom_set->classPrio(vb) ==
2432 2432
                    std::numeric_limits<Value>::max()) {
2433 2433
                  _delta2->erase(vb);
2434 2434
                } else if ((*_delta2)[vb] < _blossom_set->classPrio(vb) -
2435 2435
                           (*_blossom_data)[vb].offset) {
2436 2436
                  _delta2->increase(vb, _blossom_set->classPrio(vb) -
2437 2437
                                   (*_blossom_data)[vb].offset);
2438 2438
                }
2439 2439
              }
2440 2440
            }
2441 2441
          }
2442 2442
        }
2443 2443
      }
2444 2444
    }
2445 2445

	
2446 2446
    void oddToMatched(int blossom) {
2447 2447
      (*_blossom_data)[blossom].offset -= _delta_sum;
2448 2448

	
2449 2449
      if (_blossom_set->classPrio(blossom) !=
2450 2450
          std::numeric_limits<Value>::max()) {
2451 2451
        _delta2->push(blossom, _blossom_set->classPrio(blossom) -
2452 2452
                       (*_blossom_data)[blossom].offset);
2453 2453
      }
2454 2454

	
2455 2455
      if (!_blossom_set->trivial(blossom)) {
2456 2456
        _delta4->erase(blossom);
2457 2457
      }
2458 2458
    }
2459 2459

	
2460 2460
    void oddToEven(int blossom, int tree) {
2461 2461
      if (!_blossom_set->trivial(blossom)) {
2462 2462
        _delta4->erase(blossom);
2463 2463
        (*_blossom_data)[blossom].pot -=
2464 2464
          2 * (2 * _delta_sum - (*_blossom_data)[blossom].offset);
2465 2465
      }
2466 2466

	
2467 2467
      for (typename BlossomSet::ItemIt n(*_blossom_set, blossom);
2468 2468
           n != INVALID; ++n) {
2469 2469
        int ni = (*_node_index)[n];
2470 2470

	
2471 2471
        _blossom_set->increase(n, std::numeric_limits<Value>::max());
2472 2472

	
2473 2473
        (*_node_data)[ni].heap.clear();
2474 2474
        (*_node_data)[ni].heap_index.clear();
2475 2475
        (*_node_data)[ni].pot +=
2476 2476
          2 * _delta_sum - (*_blossom_data)[blossom].offset;
2477 2477

	
2478 2478
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
2479 2479
          Node v = _graph.source(e);
2480 2480
          int vb = _blossom_set->find(v);
2481 2481
          int vi = (*_node_index)[v];
2482 2482

	
2483 2483
          Value rw = (*_node_data)[ni].pot + (*_node_data)[vi].pot -
2484 2484
            dualScale * _weight[e];
2485 2485

	
2486 2486
          if ((*_blossom_data)[vb].status == EVEN) {
2487 2487
            if (_delta3->state(e) != _delta3->IN_HEAP && blossom != vb) {
2488 2488
              _delta3->push(e, rw / 2);
2489 2489
            }
2490 2490
          } else {
2491 2491

	
2492 2492
            typename std::map<int, Arc>::iterator it =
2493 2493
              (*_node_data)[vi].heap_index.find(tree);
2494 2494

	
2495 2495
            if (it != (*_node_data)[vi].heap_index.end()) {
2496 2496
              if ((*_node_data)[vi].heap[it->second] > rw) {
2497 2497
                (*_node_data)[vi].heap.replace(it->second, e);
2498 2498
                (*_node_data)[vi].heap.decrease(e, rw);
2499 2499
                it->second = e;
2500 2500
              }
2501 2501
            } else {
2502 2502
              (*_node_data)[vi].heap.push(e, rw);
2503 2503
              (*_node_data)[vi].heap_index.insert(std::make_pair(tree, e));
2504 2504
            }
2505 2505

	
2506 2506
            if ((*_blossom_set)[v] > (*_node_data)[vi].heap.prio()) {
2507 2507
              _blossom_set->decrease(v, (*_node_data)[vi].heap.prio());
2508 2508

	
2509 2509
              if ((*_blossom_data)[vb].status == MATCHED) {
2510 2510
                if (_delta2->state(vb) != _delta2->IN_HEAP) {
2511 2511
                  _delta2->push(vb, _blossom_set->classPrio(vb) -
2512 2512
                               (*_blossom_data)[vb].offset);
2513 2513
                } else if ((*_delta2)[vb] > _blossom_set->classPrio(vb) -
2514 2514
                           (*_blossom_data)[vb].offset) {
2515 2515
                  _delta2->decrease(vb, _blossom_set->classPrio(vb) -
2516 2516
                                   (*_blossom_data)[vb].offset);
2517 2517
                }
2518 2518
              }
2519 2519
            }
2520 2520
          }
2521 2521
        }
2522 2522
      }
2523 2523
      (*_blossom_data)[blossom].offset = 0;
2524 2524
    }
2525 2525

	
2526 2526
    void alternatePath(int even, int tree) {
2527 2527
      int odd;
2528 2528

	
2529 2529
      evenToMatched(even, tree);
2530 2530
      (*_blossom_data)[even].status = MATCHED;
2531 2531

	
2532 2532
      while ((*_blossom_data)[even].pred != INVALID) {
2533 2533
        odd = _blossom_set->find(_graph.target((*_blossom_data)[even].pred));
2534 2534
        (*_blossom_data)[odd].status = MATCHED;
2535 2535
        oddToMatched(odd);
2536 2536
        (*_blossom_data)[odd].next = (*_blossom_data)[odd].pred;
2537 2537

	
2538 2538
        even = _blossom_set->find(_graph.target((*_blossom_data)[odd].pred));
2539 2539
        (*_blossom_data)[even].status = MATCHED;
2540 2540
        evenToMatched(even, tree);
2541 2541
        (*_blossom_data)[even].next =
2542 2542
          _graph.oppositeArc((*_blossom_data)[odd].pred);
2543 2543
      }
2544 2544

	
2545 2545
    }
2546 2546

	
2547 2547
    void destroyTree(int tree) {
2548 2548
      for (TreeSet::ItemIt b(*_tree_set, tree); b != INVALID; ++b) {
2549 2549
        if ((*_blossom_data)[b].status == EVEN) {
2550 2550
          (*_blossom_data)[b].status = MATCHED;
2551 2551
          evenToMatched(b, tree);
2552 2552
        } else if ((*_blossom_data)[b].status == ODD) {
2553 2553
          (*_blossom_data)[b].status = MATCHED;
2554 2554
          oddToMatched(b);
2555 2555
        }
2556 2556
      }
2557 2557
      _tree_set->eraseClass(tree);
2558 2558
    }
2559 2559

	
2560 2560
    void augmentOnEdge(const Edge& edge) {
2561 2561

	
2562 2562
      int left = _blossom_set->find(_graph.u(edge));
2563 2563
      int right = _blossom_set->find(_graph.v(edge));
2564 2564

	
2565 2565
      int left_tree = _tree_set->find(left);
2566 2566
      alternatePath(left, left_tree);
2567 2567
      destroyTree(left_tree);
2568 2568

	
2569 2569
      int right_tree = _tree_set->find(right);
2570 2570
      alternatePath(right, right_tree);
2571 2571
      destroyTree(right_tree);
2572 2572

	
2573 2573
      (*_blossom_data)[left].next = _graph.direct(edge, true);
2574 2574
      (*_blossom_data)[right].next = _graph.direct(edge, false);
2575 2575
    }
2576 2576

	
2577 2577
    void extendOnArc(const Arc& arc) {
2578 2578
      int base = _blossom_set->find(_graph.target(arc));
2579 2579
      int tree = _tree_set->find(base);
2580 2580

	
2581 2581
      int odd = _blossom_set->find(_graph.source(arc));
2582 2582
      _tree_set->insert(odd, tree);
2583 2583
      (*_blossom_data)[odd].status = ODD;
2584 2584
      matchedToOdd(odd);
2585 2585
      (*_blossom_data)[odd].pred = arc;
2586 2586

	
2587 2587
      int even = _blossom_set->find(_graph.target((*_blossom_data)[odd].next));
2588 2588
      (*_blossom_data)[even].pred = (*_blossom_data)[even].next;
2589 2589
      _tree_set->insert(even, tree);
2590 2590
      (*_blossom_data)[even].status = EVEN;
2591 2591
      matchedToEven(even, tree);
2592 2592
    }
2593 2593

	
2594 2594
    void shrinkOnEdge(const Edge& edge, int tree) {
2595 2595
      int nca = -1;
2596 2596
      std::vector<int> left_path, right_path;
2597 2597

	
2598 2598
      {
2599 2599
        std::set<int> left_set, right_set;
2600 2600
        int left = _blossom_set->find(_graph.u(edge));
2601 2601
        left_path.push_back(left);
2602 2602
        left_set.insert(left);
2603 2603

	
2604 2604
        int right = _blossom_set->find(_graph.v(edge));
2605 2605
        right_path.push_back(right);
2606 2606
        right_set.insert(right);
2607 2607

	
2608 2608
        while (true) {
2609 2609

	
2610 2610
          if ((*_blossom_data)[left].pred == INVALID) break;
2611 2611

	
2612 2612
          left =
2613 2613
            _blossom_set->find(_graph.target((*_blossom_data)[left].pred));
2614 2614
          left_path.push_back(left);
2615 2615
          left =
2616 2616
            _blossom_set->find(_graph.target((*_blossom_data)[left].pred));
2617 2617
          left_path.push_back(left);
2618 2618

	
2619 2619
          left_set.insert(left);
2620 2620

	
2621 2621
          if (right_set.find(left) != right_set.end()) {
2622 2622
            nca = left;
2623 2623
            break;
2624 2624
          }
2625 2625

	
2626 2626
          if ((*_blossom_data)[right].pred == INVALID) break;
2627 2627

	
2628 2628
          right =
2629 2629
            _blossom_set->find(_graph.target((*_blossom_data)[right].pred));
2630 2630
          right_path.push_back(right);
2631 2631
          right =
2632 2632
            _blossom_set->find(_graph.target((*_blossom_data)[right].pred));
2633 2633
          right_path.push_back(right);
2634 2634

	
2635 2635
          right_set.insert(right);
2636 2636

	
2637 2637
          if (left_set.find(right) != left_set.end()) {
2638 2638
            nca = right;
2639 2639
            break;
2640 2640
          }
2641 2641

	
2642 2642
        }
2643 2643

	
2644 2644
        if (nca == -1) {
2645 2645
          if ((*_blossom_data)[left].pred == INVALID) {
2646 2646
            nca = right;
2647 2647
            while (left_set.find(nca) == left_set.end()) {
2648 2648
              nca =
2649 2649
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
2650 2650
              right_path.push_back(nca);
2651 2651
              nca =
2652 2652
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
2653 2653
              right_path.push_back(nca);
2654 2654
            }
2655 2655
          } else {
2656 2656
            nca = left;
2657 2657
            while (right_set.find(nca) == right_set.end()) {
2658 2658
              nca =
2659 2659
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
2660 2660
              left_path.push_back(nca);
2661 2661
              nca =
2662 2662
                _blossom_set->find(_graph.target((*_blossom_data)[nca].pred));
2663 2663
              left_path.push_back(nca);
2664 2664
            }
2665 2665
          }
2666 2666
        }
2667 2667
      }
2668 2668

	
2669 2669
      std::vector<int> subblossoms;
2670 2670
      Arc prev;
2671 2671

	
2672 2672
      prev = _graph.direct(edge, true);
2673 2673
      for (int i = 0; left_path[i] != nca; i += 2) {
2674 2674
        subblossoms.push_back(left_path[i]);
2675 2675
        (*_blossom_data)[left_path[i]].next = prev;
2676 2676
        _tree_set->erase(left_path[i]);
2677 2677

	
2678 2678
        subblossoms.push_back(left_path[i + 1]);
2679 2679
        (*_blossom_data)[left_path[i + 1]].status = EVEN;
2680 2680
        oddToEven(left_path[i + 1], tree);
2681 2681
        _tree_set->erase(left_path[i + 1]);
2682 2682
        prev = _graph.oppositeArc((*_blossom_data)[left_path[i + 1]].pred);
2683 2683
      }
2684 2684

	
2685 2685
      int k = 0;
2686 2686
      while (right_path[k] != nca) ++k;
2687 2687

	
2688 2688
      subblossoms.push_back(nca);
2689 2689
      (*_blossom_data)[nca].next = prev;
2690 2690

	
2691 2691
      for (int i = k - 2; i >= 0; i -= 2) {
2692 2692
        subblossoms.push_back(right_path[i + 1]);
2693 2693
        (*_blossom_data)[right_path[i + 1]].status = EVEN;
2694 2694
        oddToEven(right_path[i + 1], tree);
2695 2695
        _tree_set->erase(right_path[i + 1]);
2696 2696

	
2697 2697
        (*_blossom_data)[right_path[i + 1]].next =
2698 2698
          (*_blossom_data)[right_path[i + 1]].pred;
2699 2699

	
2700 2700
        subblossoms.push_back(right_path[i]);
2701 2701
        _tree_set->erase(right_path[i]);
2702 2702
      }
2703 2703

	
2704 2704
      int surface =
2705 2705
        _blossom_set->join(subblossoms.begin(), subblossoms.end());
2706 2706

	
2707 2707
      for (int i = 0; i < int(subblossoms.size()); ++i) {
2708 2708
        if (!_blossom_set->trivial(subblossoms[i])) {
2709 2709
          (*_blossom_data)[subblossoms[i]].pot += 2 * _delta_sum;
2710 2710
        }
2711 2711
        (*_blossom_data)[subblossoms[i]].status = MATCHED;
2712 2712
      }
2713 2713

	
2714 2714
      (*_blossom_data)[surface].pot = -2 * _delta_sum;
2715 2715
      (*_blossom_data)[surface].offset = 0;
2716 2716
      (*_blossom_data)[surface].status = EVEN;
2717 2717
      (*_blossom_data)[surface].pred = (*_blossom_data)[nca].pred;
2718 2718
      (*_blossom_data)[surface].next = (*_blossom_data)[nca].pred;
2719 2719

	
2720 2720
      _tree_set->insert(surface, tree);
2721 2721
      _tree_set->erase(nca);
2722 2722
    }
2723 2723

	
2724 2724
    void splitBlossom(int blossom) {
2725 2725
      Arc next = (*_blossom_data)[blossom].next;
2726 2726
      Arc pred = (*_blossom_data)[blossom].pred;
2727 2727

	
2728 2728
      int tree = _tree_set->find(blossom);
2729 2729

	
2730 2730
      (*_blossom_data)[blossom].status = MATCHED;
2731 2731
      oddToMatched(blossom);
2732 2732
      if (_delta2->state(blossom) == _delta2->IN_HEAP) {
2733 2733
        _delta2->erase(blossom);
2734 2734
      }
2735 2735

	
2736 2736
      std::vector<int> subblossoms;
2737 2737
      _blossom_set->split(blossom, std::back_inserter(subblossoms));
2738 2738

	
2739 2739
      Value offset = (*_blossom_data)[blossom].offset;
2740 2740
      int b = _blossom_set->find(_graph.source(pred));
2741 2741
      int d = _blossom_set->find(_graph.source(next));
2742 2742

	
2743 2743
      int ib = -1, id = -1;
2744 2744
      for (int i = 0; i < int(subblossoms.size()); ++i) {
2745 2745
        if (subblossoms[i] == b) ib = i;
2746 2746
        if (subblossoms[i] == d) id = i;
2747 2747

	
2748 2748
        (*_blossom_data)[subblossoms[i]].offset = offset;
2749 2749
        if (!_blossom_set->trivial(subblossoms[i])) {
2750 2750
          (*_blossom_data)[subblossoms[i]].pot -= 2 * offset;
2751 2751
        }
2752 2752
        if (_blossom_set->classPrio(subblossoms[i]) !=
2753 2753
            std::numeric_limits<Value>::max()) {
2754 2754
          _delta2->push(subblossoms[i],
2755 2755
                        _blossom_set->classPrio(subblossoms[i]) -
2756 2756
                        (*_blossom_data)[subblossoms[i]].offset);
2757 2757
        }
2758 2758
      }
2759 2759

	
2760 2760
      if (id > ib ? ((id - ib) % 2 == 0) : ((ib - id) % 2 == 1)) {
2761 2761
        for (int i = (id + 1) % subblossoms.size();
2762 2762
             i != ib; i = (i + 2) % subblossoms.size()) {
2763 2763
          int sb = subblossoms[i];
2764 2764
          int tb = subblossoms[(i + 1) % subblossoms.size()];
2765 2765
          (*_blossom_data)[sb].next =
2766 2766
            _graph.oppositeArc((*_blossom_data)[tb].next);
2767 2767
        }
2768 2768

	
2769 2769
        for (int i = ib; i != id; i = (i + 2) % subblossoms.size()) {
2770 2770
          int sb = subblossoms[i];
2771 2771
          int tb = subblossoms[(i + 1) % subblossoms.size()];
2772 2772
          int ub = subblossoms[(i + 2) % subblossoms.size()];
2773 2773

	
2774 2774
          (*_blossom_data)[sb].status = ODD;
2775 2775
          matchedToOdd(sb);
2776 2776
          _tree_set->insert(sb, tree);
2777 2777
          (*_blossom_data)[sb].pred = pred;
2778 2778
          (*_blossom_data)[sb].next =
2779 2779
                           _graph.oppositeArc((*_blossom_data)[tb].next);
2780 2780

	
2781 2781
          pred = (*_blossom_data)[ub].next;
2782 2782

	
2783 2783
          (*_blossom_data)[tb].status = EVEN;
2784 2784
          matchedToEven(tb, tree);
2785 2785
          _tree_set->insert(tb, tree);
2786 2786
          (*_blossom_data)[tb].pred = (*_blossom_data)[tb].next;
2787 2787
        }
2788 2788

	
2789 2789
        (*_blossom_data)[subblossoms[id]].status = ODD;
2790 2790
        matchedToOdd(subblossoms[id]);
2791 2791
        _tree_set->insert(subblossoms[id], tree);
2792 2792
        (*_blossom_data)[subblossoms[id]].next = next;
2793 2793
        (*_blossom_data)[subblossoms[id]].pred = pred;
2794 2794

	
2795 2795
      } else {
2796 2796

	
2797 2797
        for (int i = (ib + 1) % subblossoms.size();
2798 2798
             i != id; i = (i + 2) % subblossoms.size()) {
2799 2799
          int sb = subblossoms[i];
2800 2800
          int tb = subblossoms[(i + 1) % subblossoms.size()];
2801 2801
          (*_blossom_data)[sb].next =
2802 2802
            _graph.oppositeArc((*_blossom_data)[tb].next);
2803 2803
        }
2804 2804

	
2805 2805
        for (int i = id; i != ib; i = (i + 2) % subblossoms.size()) {
2806 2806
          int sb = subblossoms[i];
2807 2807
          int tb = subblossoms[(i + 1) % subblossoms.size()];
2808 2808
          int ub = subblossoms[(i + 2) % subblossoms.size()];
2809 2809

	
2810 2810
          (*_blossom_data)[sb].status = ODD;
2811 2811
          matchedToOdd(sb);
2812 2812
          _tree_set->insert(sb, tree);
2813 2813
          (*_blossom_data)[sb].next = next;
2814 2814
          (*_blossom_data)[sb].pred =
2815 2815
            _graph.oppositeArc((*_blossom_data)[tb].next);
2816 2816

	
2817 2817
          (*_blossom_data)[tb].status = EVEN;
2818 2818
          matchedToEven(tb, tree);
2819 2819
          _tree_set->insert(tb, tree);
2820 2820
          (*_blossom_data)[tb].pred =
2821 2821
            (*_blossom_data)[tb].next =
2822 2822
            _graph.oppositeArc((*_blossom_data)[ub].next);
2823 2823
          next = (*_blossom_data)[ub].next;
2824 2824
        }
2825 2825

	
2826 2826
        (*_blossom_data)[subblossoms[ib]].status = ODD;
2827 2827
        matchedToOdd(subblossoms[ib]);
2828 2828
        _tree_set->insert(subblossoms[ib], tree);
2829 2829
        (*_blossom_data)[subblossoms[ib]].next = next;
2830 2830
        (*_blossom_data)[subblossoms[ib]].pred = pred;
2831 2831
      }
2832 2832
      _tree_set->erase(blossom);
2833 2833
    }
2834 2834

	
2835 2835
    void extractBlossom(int blossom, const Node& base, const Arc& matching) {
2836 2836
      if (_blossom_set->trivial(blossom)) {
2837 2837
        int bi = (*_node_index)[base];
2838 2838
        Value pot = (*_node_data)[bi].pot;
2839 2839

	
2840 2840
        (*_matching)[base] = matching;
2841 2841
        _blossom_node_list.push_back(base);
2842 2842
        (*_node_potential)[base] = pot;
2843 2843
      } else {
2844 2844

	
2845 2845
        Value pot = (*_blossom_data)[blossom].pot;
2846 2846
        int bn = _blossom_node_list.size();
2847 2847

	
2848 2848
        std::vector<int> subblossoms;
2849 2849
        _blossom_set->split(blossom, std::back_inserter(subblossoms));
2850 2850
        int b = _blossom_set->find(base);
2851 2851
        int ib = -1;
2852 2852
        for (int i = 0; i < int(subblossoms.size()); ++i) {
2853 2853
          if (subblossoms[i] == b) { ib = i; break; }
2854 2854
        }
2855 2855

	
2856 2856
        for (int i = 1; i < int(subblossoms.size()); i += 2) {
2857 2857
          int sb = subblossoms[(ib + i) % subblossoms.size()];
2858 2858
          int tb = subblossoms[(ib + i + 1) % subblossoms.size()];
2859 2859

	
2860 2860
          Arc m = (*_blossom_data)[tb].next;
2861 2861
          extractBlossom(sb, _graph.target(m), _graph.oppositeArc(m));
2862 2862
          extractBlossom(tb, _graph.source(m), m);
2863 2863
        }
2864 2864
        extractBlossom(subblossoms[ib], base, matching);
2865 2865

	
2866 2866
        int en = _blossom_node_list.size();
2867 2867

	
2868 2868
        _blossom_potential.push_back(BlossomVariable(bn, en, pot));
2869 2869
      }
2870 2870
    }
2871 2871

	
2872 2872
    void extractMatching() {
2873 2873
      std::vector<int> blossoms;
2874 2874
      for (typename BlossomSet::ClassIt c(*_blossom_set); c != INVALID; ++c) {
2875 2875
        blossoms.push_back(c);
2876 2876
      }
2877 2877

	
2878 2878
      for (int i = 0; i < int(blossoms.size()); ++i) {
2879 2879

	
2880 2880
        Value offset = (*_blossom_data)[blossoms[i]].offset;
2881 2881
        (*_blossom_data)[blossoms[i]].pot += 2 * offset;
2882 2882
        for (typename BlossomSet::ItemIt n(*_blossom_set, blossoms[i]);
2883 2883
             n != INVALID; ++n) {
2884 2884
          (*_node_data)[(*_node_index)[n]].pot -= offset;
2885 2885
        }
2886 2886

	
2887 2887
        Arc matching = (*_blossom_data)[blossoms[i]].next;
2888 2888
        Node base = _graph.source(matching);
2889 2889
        extractBlossom(blossoms[i], base, matching);
2890 2890
      }
2891 2891
    }
2892 2892

	
2893 2893
  public:
2894 2894

	
2895 2895
    /// \brief Constructor
2896 2896
    ///
2897 2897
    /// Constructor.
2898 2898
    MaxWeightedPerfectMatching(const Graph& graph, const WeightMap& weight)
2899 2899
      : _graph(graph), _weight(weight), _matching(0),
2900 2900
        _node_potential(0), _blossom_potential(), _blossom_node_list(),
2901 2901
        _node_num(0), _blossom_num(0),
2902 2902

	
2903 2903
        _blossom_index(0), _blossom_set(0), _blossom_data(0),
2904 2904
        _node_index(0), _node_heap_index(0), _node_data(0),
2905 2905
        _tree_set_index(0), _tree_set(0),
2906 2906

	
2907 2907
        _delta2_index(0), _delta2(0),
2908 2908
        _delta3_index(0), _delta3(0),
2909 2909
        _delta4_index(0), _delta4(0),
2910 2910

	
2911 2911
        _delta_sum() {}
2912 2912

	
2913 2913
    ~MaxWeightedPerfectMatching() {
2914 2914
      destroyStructures();
2915 2915
    }
2916 2916

	
2917 2917
    /// \name Execution Control
2918 2918
    /// The simplest way to execute the algorithm is to use the
2919 2919
    /// \ref run() member function.
2920 2920

	
2921 2921
    ///@{
2922 2922

	
2923 2923
    /// \brief Initialize the algorithm
2924 2924
    ///
2925 2925
    /// This function initializes the algorithm.
2926 2926
    void init() {
2927 2927
      createStructures();
2928 2928

	
2929 2929
      for (ArcIt e(_graph); e != INVALID; ++e) {
2930 2930
        (*_node_heap_index)[e] = BinHeap<Value, IntArcMap>::PRE_HEAP;
2931 2931
      }
2932 2932
      for (EdgeIt e(_graph); e != INVALID; ++e) {
2933 2933
        (*_delta3_index)[e] = _delta3->PRE_HEAP;
2934 2934
      }
2935 2935
      for (int i = 0; i < _blossom_num; ++i) {
2936 2936
        (*_delta2_index)[i] = _delta2->PRE_HEAP;
2937 2937
        (*_delta4_index)[i] = _delta4->PRE_HEAP;
2938 2938
      }
2939 2939

	
2940 2940
      int index = 0;
2941 2941
      for (NodeIt n(_graph); n != INVALID; ++n) {
2942 2942
        Value max = - std::numeric_limits<Value>::max();
2943 2943
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
2944 2944
          if (_graph.target(e) == n) continue;
2945 2945
          if ((dualScale * _weight[e]) / 2 > max) {
2946 2946
            max = (dualScale * _weight[e]) / 2;
2947 2947
          }
2948 2948
        }
2949 2949
        (*_node_index)[n] = index;
2950 2950
        (*_node_data)[index].pot = max;
2951 2951
        int blossom =
2952 2952
          _blossom_set->insert(n, std::numeric_limits<Value>::max());
2953 2953

	
2954 2954
        _tree_set->insert(blossom);
2955 2955

	
2956 2956
        (*_blossom_data)[blossom].status = EVEN;
2957 2957
        (*_blossom_data)[blossom].pred = INVALID;
2958 2958
        (*_blossom_data)[blossom].next = INVALID;
2959 2959
        (*_blossom_data)[blossom].pot = 0;
2960 2960
        (*_blossom_data)[blossom].offset = 0;
2961 2961
        ++index;
2962 2962
      }
2963 2963
      for (EdgeIt e(_graph); e != INVALID; ++e) {
2964 2964
        int si = (*_node_index)[_graph.u(e)];
2965 2965
        int ti = (*_node_index)[_graph.v(e)];
2966 2966
        if (_graph.u(e) != _graph.v(e)) {
2967 2967
          _delta3->push(e, ((*_node_data)[si].pot + (*_node_data)[ti].pot -
2968 2968
                            dualScale * _weight[e]) / 2);
2969 2969
        }
2970 2970
      }
2971 2971
    }
2972 2972

	
2973 2973
    /// \brief Start the algorithm
2974 2974
    ///
2975 2975
    /// This function starts the algorithm.
2976 2976
    ///
2977 2977
    /// \pre \ref init() must be called before using this function.
2978 2978
    bool start() {
2979 2979
      enum OpType {
2980 2980
        D2, D3, D4
2981 2981
      };
2982 2982

	
2983 2983
      int unmatched = _node_num;
2984 2984
      while (unmatched > 0) {
2985 2985
        Value d2 = !_delta2->empty() ?
2986 2986
          _delta2->prio() : std::numeric_limits<Value>::max();
2987 2987

	
2988 2988
        Value d3 = !_delta3->empty() ?
2989 2989
          _delta3->prio() : std::numeric_limits<Value>::max();
2990 2990

	
2991 2991
        Value d4 = !_delta4->empty() ?
2992 2992
          _delta4->prio() : std::numeric_limits<Value>::max();
2993 2993

	
2994 2994
        _delta_sum = d2; OpType ot = D2;
2995 2995
        if (d3 < _delta_sum) { _delta_sum = d3; ot = D3; }
2996 2996
        if (d4 < _delta_sum) { _delta_sum = d4; ot = D4; }
2997 2997

	
2998 2998
        if (_delta_sum == std::numeric_limits<Value>::max()) {
2999 2999
          return false;
3000 3000
        }
3001 3001

	
3002 3002
        switch (ot) {
3003 3003
        case D2:
3004 3004
          {
3005 3005
            int blossom = _delta2->top();
3006 3006
            Node n = _blossom_set->classTop(blossom);
3007 3007
            Arc e = (*_node_data)[(*_node_index)[n]].heap.top();
3008 3008
            extendOnArc(e);
3009 3009
          }
3010 3010
          break;
3011 3011
        case D3:
3012 3012
          {
3013 3013
            Edge e = _delta3->top();
3014 3014

	
3015 3015
            int left_blossom = _blossom_set->find(_graph.u(e));
3016 3016
            int right_blossom = _blossom_set->find(_graph.v(e));
3017 3017

	
3018 3018
            if (left_blossom == right_blossom) {
3019 3019
              _delta3->pop();
3020 3020
            } else {
3021 3021
              int left_tree = _tree_set->find(left_blossom);
3022 3022
              int right_tree = _tree_set->find(right_blossom);
3023 3023

	
3024 3024
              if (left_tree == right_tree) {
3025 3025
                shrinkOnEdge(e, left_tree);
3026 3026
              } else {
3027 3027
                augmentOnEdge(e);
3028 3028
                unmatched -= 2;
3029 3029
              }
3030 3030
            }
3031 3031
          } break;
3032 3032
        case D4:
3033 3033
          splitBlossom(_delta4->top());
3034 3034
          break;
3035 3035
        }
3036 3036
      }
3037 3037
      extractMatching();
3038 3038
      return true;
3039 3039
    }
3040 3040

	
3041 3041
    /// \brief Run the algorithm.
3042 3042
    ///
3043 3043
    /// This method runs the \c %MaxWeightedPerfectMatching algorithm.
3044 3044
    ///
3045 3045
    /// \note mwpm.run() is just a shortcut of the following code.
3046 3046
    /// \code
3047 3047
    ///   mwpm.init();
3048 3048
    ///   mwpm.start();
3049 3049
    /// \endcode
3050 3050
    bool run() {
3051 3051
      init();
3052 3052
      return start();
3053 3053
    }
3054 3054

	
3055 3055
    /// @}
3056 3056

	
3057 3057
    /// \name Primal Solution
3058 3058
    /// Functions to get the primal solution, i.e. the maximum weighted 
3059 3059
    /// perfect matching.\n
3060 3060
    /// Either \ref run() or \ref start() function should be called before
3061 3061
    /// using them.
3062 3062

	
3063 3063
    /// @{
3064 3064

	
3065 3065
    /// \brief Return the weight of the matching.
3066 3066
    ///
3067 3067
    /// This function returns the weight of the found matching.
3068 3068
    ///
3069 3069
    /// \pre Either run() or start() must be called before using this function.
3070 3070
    Value matchingWeight() const {
3071 3071
      Value sum = 0;
3072 3072
      for (NodeIt n(_graph); n != INVALID; ++n) {
3073 3073
        if ((*_matching)[n] != INVALID) {
3074 3074
          sum += _weight[(*_matching)[n]];
3075 3075
        }
3076 3076
      }
3077 3077
      return sum /= 2;
3078 3078
    }
3079 3079

	
3080 3080
    /// \brief Return \c true if the given edge is in the matching.
3081 3081
    ///
3082 3082
    /// This function returns \c true if the given edge is in the found 
3083 3083
    /// matching.
3084 3084
    ///
3085 3085
    /// \pre Either run() or start() must be called before using this function.
3086 3086
    bool matching(const Edge& edge) const {
3087 3087
      return static_cast<const Edge&>((*_matching)[_graph.u(edge)]) == edge;
3088 3088
    }
3089 3089

	
3090 3090
    /// \brief Return the matching arc (or edge) incident to the given node.
3091 3091
    ///
3092 3092
    /// This function returns the matching arc (or edge) incident to the
3093 3093
    /// given node in the found matching or \c INVALID if the node is 
3094 3094
    /// not covered by the matching.
3095 3095
    ///
3096 3096
    /// \pre Either run() or start() must be called before using this function.
3097 3097
    Arc matching(const Node& node) const {
3098 3098
      return (*_matching)[node];
3099 3099
    }
3100 3100

	
3101 3101
    /// \brief Return a const reference to the matching map.
3102 3102
    ///
3103 3103
    /// This function returns a const reference to a node map that stores
3104 3104
    /// the matching arc (or edge) incident to each node.
3105 3105
    const MatchingMap& matchingMap() const {
3106 3106
      return *_matching;
3107 3107
    }
3108 3108

	
3109 3109
    /// \brief Return the mate of the given node.
3110 3110
    ///
3111 3111
    /// This function returns the mate of the given node in the found 
3112 3112
    /// matching or \c INVALID if the node is not covered by the matching.
3113 3113
    ///
3114 3114
    /// \pre Either run() or start() must be called before using this function.
3115 3115
    Node mate(const Node& node) const {
3116 3116
      return _graph.target((*_matching)[node]);
3117 3117
    }
3118 3118

	
3119 3119
    /// @}
3120 3120

	
3121 3121
    /// \name Dual Solution
3122 3122
    /// Functions to get the dual solution.\n
3123 3123
    /// Either \ref run() or \ref start() function should be called before
3124 3124
    /// using them.
3125 3125

	
3126 3126
    /// @{
3127 3127

	
3128 3128
    /// \brief Return the value of the dual solution.
3129 3129
    ///
3130 3130
    /// This function returns the value of the dual solution. 
3131 3131
    /// It should be equal to the primal value scaled by \ref dualScale 
3132 3132
    /// "dual scale".
3133 3133
    ///
3134 3134
    /// \pre Either run() or start() must be called before using this function.
3135 3135
    Value dualValue() const {
3136 3136
      Value sum = 0;
3137 3137
      for (NodeIt n(_graph); n != INVALID; ++n) {
3138 3138
        sum += nodeValue(n);
3139 3139
      }
3140 3140
      for (int i = 0; i < blossomNum(); ++i) {
3141 3141
        sum += blossomValue(i) * (blossomSize(i) / 2);
3142 3142
      }
3143 3143
      return sum;
3144 3144
    }
3145 3145

	
3146 3146
    /// \brief Return the dual value (potential) of the given node.
3147 3147
    ///
3148 3148
    /// This function returns the dual value (potential) of the given node.
3149 3149
    ///
3150 3150
    /// \pre Either run() or start() must be called before using this function.
3151 3151
    Value nodeValue(const Node& n) const {
3152 3152
      return (*_node_potential)[n];
3153 3153
    }
3154 3154

	
3155 3155
    /// \brief Return the number of the blossoms in the basis.
3156 3156
    ///
3157 3157
    /// This function returns the number of the blossoms in the basis.
3158 3158
    ///
3159 3159
    /// \pre Either run() or start() must be called before using this function.
3160 3160
    /// \see BlossomIt
3161 3161
    int blossomNum() const {
3162 3162
      return _blossom_potential.size();
3163 3163
    }
3164 3164

	
3165 3165
    /// \brief Return the number of the nodes in the given blossom.
3166 3166
    ///
3167 3167
    /// This function returns the number of the nodes in the given blossom.
3168 3168
    ///
3169 3169
    /// \pre Either run() or start() must be called before using this function.
3170 3170
    /// \see BlossomIt
3171 3171
    int blossomSize(int k) const {
3172 3172
      return _blossom_potential[k].end - _blossom_potential[k].begin;
3173 3173
    }
3174 3174

	
3175 3175
    /// \brief Return the dual value (ptential) of the given blossom.
3176 3176
    ///
3177 3177
    /// This function returns the dual value (ptential) of the given blossom.
3178 3178
    ///
3179 3179
    /// \pre Either run() or start() must be called before using this function.
3180 3180
    Value blossomValue(int k) const {
3181 3181
      return _blossom_potential[k].value;
3182 3182
    }
3183 3183

	
3184 3184
    /// \brief Iterator for obtaining the nodes of a blossom.
3185 3185
    ///
3186 3186
    /// This class provides an iterator for obtaining the nodes of the 
3187 3187
    /// given blossom. It lists a subset of the nodes.
3188 3188
    /// Before using this iterator, you must allocate a 
3189 3189
    /// MaxWeightedPerfectMatching class and execute it.
3190 3190
    class BlossomIt {
3191 3191
    public:
3192 3192

	
3193 3193
      /// \brief Constructor.
3194 3194
      ///
3195 3195
      /// Constructor to get the nodes of the given variable.
3196 3196
      ///
3197 3197
      /// \pre Either \ref MaxWeightedPerfectMatching::run() "algorithm.run()" 
3198 3198
      /// or \ref MaxWeightedPerfectMatching::start() "algorithm.start()" 
3199 3199
      /// must be called before initializing this iterator.
3200 3200
      BlossomIt(const MaxWeightedPerfectMatching& algorithm, int variable)
3201 3201
        : _algorithm(&algorithm)
3202 3202
      {
3203 3203
        _index = _algorithm->_blossom_potential[variable].begin;
3204 3204
        _last = _algorithm->_blossom_potential[variable].end;
3205 3205
      }
3206 3206

	
3207 3207
      /// \brief Conversion to \c Node.
3208 3208
      ///
3209 3209
      /// Conversion to \c Node.
3210 3210
      operator Node() const {
3211 3211
        return _algorithm->_blossom_node_list[_index];
3212 3212
      }
3213 3213

	
3214 3214
      /// \brief Increment operator.
3215 3215
      ///
3216 3216
      /// Increment operator.
3217 3217
      BlossomIt& operator++() {
3218 3218
        ++_index;
3219 3219
        return *this;
3220 3220
      }
3221 3221

	
3222 3222
      /// \brief Validity checking
3223 3223
      ///
3224 3224
      /// This function checks whether the iterator is invalid.
3225 3225
      bool operator==(Invalid) const { return _index == _last; }
3226 3226

	
3227 3227
      /// \brief Validity checking
3228 3228
      ///
3229 3229
      /// This function checks whether the iterator is valid.
3230 3230
      bool operator!=(Invalid) const { return _index != _last; }
3231 3231

	
3232 3232
    private:
3233 3233
      const MaxWeightedPerfectMatching* _algorithm;
3234 3234
      int _last;
3235 3235
      int _index;
3236 3236
    };
3237 3237

	
3238 3238
    /// @}
3239 3239

	
3240 3240
  };
3241 3241

	
3242 3242
} //END OF NAMESPACE LEMON
3243 3243

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

	
19 19
#ifndef LEMON_NETWORK_SIMPLEX_H
20 20
#define LEMON_NETWORK_SIMPLEX_H
21 21

	
22
/// \ingroup min_cost_flow
22
/// \ingroup min_cost_flow_algs
23 23
///
24 24
/// \file
25 25
/// \brief Network Simplex algorithm for finding a minimum cost flow.
26 26

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <algorithm>
30 30

	
31 31
#include <lemon/core.h>
32 32
#include <lemon/math.h>
33 33

	
34 34
namespace lemon {
35 35

	
36
  /// \addtogroup min_cost_flow
36
  /// \addtogroup min_cost_flow_algs
37 37
  /// @{
38 38

	
39 39
  /// \brief Implementation of the primal Network Simplex algorithm
40 40
  /// for finding a \ref min_cost_flow "minimum cost flow".
41 41
  ///
42 42
  /// \ref NetworkSimplex implements the primal Network Simplex algorithm
43 43
  /// for finding a \ref min_cost_flow "minimum cost flow".
44 44
  /// This algorithm is a specialized version of the linear programming
45 45
  /// simplex method directly for the minimum cost flow problem.
46 46
  /// It is one of the most efficient solution methods.
47 47
  ///
48 48
  /// In general this class is the fastest implementation available
49 49
  /// in LEMON for the minimum cost flow problem.
50 50
  /// Moreover it supports both directions of the supply/demand inequality
51 51
  /// constraints. For more information see \ref SupplyType.
52 52
  ///
53 53
  /// Most of the parameters of the problem (except for the digraph)
54 54
  /// can be given using separate functions, and the algorithm can be
55 55
  /// executed using the \ref run() function. If some parameters are not
56 56
  /// specified, then default values will be used.
57 57
  ///
58 58
  /// \tparam GR The digraph type the algorithm runs on.
59 59
  /// \tparam V The value type used for flow amounts, capacity bounds
60 60
  /// and supply values in the algorithm. By default it is \c int.
61 61
  /// \tparam C The value type used for costs and potentials in the
62 62
  /// algorithm. By default it is the same as \c V.
63 63
  ///
64 64
  /// \warning Both value types must be signed and all input data must
65 65
  /// be integer.
66 66
  ///
67 67
  /// \note %NetworkSimplex provides five different pivot rule
68 68
  /// implementations, from which the most efficient one is used
69 69
  /// by default. For more information see \ref PivotRule.
70 70
  template <typename GR, typename V = int, typename C = V>
71 71
  class NetworkSimplex
72 72
  {
73 73
  public:
74 74

	
75 75
    /// The type of the flow amounts, capacity bounds and supply values
76 76
    typedef V Value;
77 77
    /// The type of the arc costs
78 78
    typedef C Cost;
79 79

	
80 80
  public:
81 81

	
82 82
    /// \brief Problem type constants for the \c run() function.
83 83
    ///
84 84
    /// Enum type containing the problem type constants that can be
85 85
    /// returned by the \ref run() function of the algorithm.
86 86
    enum ProblemType {
87 87
      /// The problem has no feasible solution (flow).
88 88
      INFEASIBLE,
89 89
      /// The problem has optimal solution (i.e. it is feasible and
90 90
      /// bounded), and the algorithm has found optimal flow and node
91 91
      /// potentials (primal and dual solutions).
92 92
      OPTIMAL,
93 93
      /// The objective function of the problem is unbounded, i.e.
94 94
      /// there is a directed cycle having negative total cost and
95 95
      /// infinite upper bound.
96 96
      UNBOUNDED
97 97
    };
98 98
    
99 99
    /// \brief Constants for selecting the type of the supply constraints.
100 100
    ///
101 101
    /// Enum type containing constants for selecting the supply type,
102 102
    /// i.e. the direction of the inequalities in the supply/demand
103 103
    /// constraints of the \ref min_cost_flow "minimum cost flow problem".
104 104
    ///
105
    /// The default supply type is \c GEQ, since this form is supported
106
    /// by other minimum cost flow algorithms and the \ref Circulation
107
    /// algorithm, as well.
108
    /// The \c LEQ problem type can be selected using the \ref supplyType()
109
    /// function.
110
    ///
111
    /// Note that the equality form is a special case of both supply types.
105
    /// The default supply type is \c GEQ, the \c LEQ type can be
106
    /// selected using \ref supplyType().
107
    /// The equality form is a special case of both supply types.
112 108
    enum SupplyType {
113

	
114 109
      /// This option means that there are <em>"greater or equal"</em>
115
      /// supply/demand constraints in the definition, i.e. the exact
116
      /// formulation of the problem is the following.
117
      /**
118
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
119
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
120
              sup(u) \quad \forall u\in V \f]
121
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
122
      */
123
      /// It means that the total demand must be greater or equal to the 
124
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
125
      /// negative) and all the supplies have to be carried out from 
126
      /// the supply nodes, but there could be demands that are not 
127
      /// satisfied.
110
      /// supply/demand constraints in the definition of the problem.
128 111
      GEQ,
129
      /// It is just an alias for the \c GEQ option.
130
      CARRY_SUPPLIES = GEQ,
131

	
132 112
      /// This option means that there are <em>"less or equal"</em>
133
      /// supply/demand constraints in the definition, i.e. the exact
134
      /// formulation of the problem is the following.
135
      /**
136
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
137
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
138
              sup(u) \quad \forall u\in V \f]
139
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
140
      */
141
      /// It means that the total demand must be less or equal to the 
142
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
143
      /// positive) and all the demands have to be satisfied, but there
144
      /// could be supplies that are not carried out from the supply
145
      /// nodes.
146
      LEQ,
147
      /// It is just an alias for the \c LEQ option.
148
      SATISFY_DEMANDS = LEQ
113
      /// supply/demand constraints in the definition of the problem.
114
      LEQ
149 115
    };
150 116
    
151 117
    /// \brief Constants for selecting the pivot rule.
152 118
    ///
153 119
    /// Enum type containing constants for selecting the pivot rule for
154 120
    /// the \ref run() function.
155 121
    ///
156 122
    /// \ref NetworkSimplex provides five different pivot rule
157 123
    /// implementations that significantly affect the running time
158 124
    /// of the algorithm.
159 125
    /// By default \ref BLOCK_SEARCH "Block Search" is used, which
160 126
    /// proved to be the most efficient and the most robust on various
161 127
    /// test inputs according to our benchmark tests.
162 128
    /// However another pivot rule can be selected using the \ref run()
163 129
    /// function with the proper parameter.
164 130
    enum PivotRule {
165 131

	
166 132
      /// The First Eligible pivot rule.
167 133
      /// The next eligible arc is selected in a wraparound fashion
168 134
      /// in every iteration.
169 135
      FIRST_ELIGIBLE,
170 136

	
171 137
      /// The Best Eligible pivot rule.
172 138
      /// The best eligible arc is selected in every iteration.
173 139
      BEST_ELIGIBLE,
174 140

	
175 141
      /// The Block Search pivot rule.
176 142
      /// A specified number of arcs are examined in every iteration
177 143
      /// in a wraparound fashion and the best eligible arc is selected
178 144
      /// from this block.
179 145
      BLOCK_SEARCH,
180 146

	
181 147
      /// The Candidate List pivot rule.
182 148
      /// In a major iteration a candidate list is built from eligible arcs
183 149
      /// in a wraparound fashion and in the following minor iterations
184 150
      /// the best eligible arc is selected from this list.
185 151
      CANDIDATE_LIST,
186 152

	
187 153
      /// The Altering Candidate List pivot rule.
188 154
      /// It is a modified version of the Candidate List method.
189 155
      /// It keeps only the several best eligible arcs from the former
190 156
      /// candidate list and extends this list in every iteration.
191 157
      ALTERING_LIST
192 158
    };
193 159
    
194 160
  private:
195 161

	
196 162
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
197 163

	
198 164
    typedef std::vector<Arc> ArcVector;
199 165
    typedef std::vector<Node> NodeVector;
200 166
    typedef std::vector<int> IntVector;
201 167
    typedef std::vector<bool> BoolVector;
202 168
    typedef std::vector<Value> ValueVector;
203 169
    typedef std::vector<Cost> CostVector;
204 170

	
205 171
    // State constants for arcs
206 172
    enum ArcStateEnum {
207 173
      STATE_UPPER = -1,
208 174
      STATE_TREE  =  0,
209 175
      STATE_LOWER =  1
210 176
    };
211 177

	
212 178
  private:
213 179

	
214 180
    // Data related to the underlying digraph
215 181
    const GR &_graph;
216 182
    int _node_num;
217 183
    int _arc_num;
184
    int _all_arc_num;
185
    int _search_arc_num;
218 186

	
219 187
    // Parameters of the problem
220 188
    bool _have_lower;
221 189
    SupplyType _stype;
222 190
    Value _sum_supply;
223 191

	
224 192
    // Data structures for storing the digraph
225 193
    IntNodeMap _node_id;
226 194
    IntArcMap _arc_id;
227 195
    IntVector _source;
228 196
    IntVector _target;
229 197

	
230 198
    // Node and arc data
231 199
    ValueVector _lower;
232 200
    ValueVector _upper;
233 201
    ValueVector _cap;
234 202
    CostVector _cost;
235 203
    ValueVector _supply;
236 204
    ValueVector _flow;
237 205
    CostVector _pi;
238 206

	
239 207
    // Data for storing the spanning tree structure
240 208
    IntVector _parent;
241 209
    IntVector _pred;
242 210
    IntVector _thread;
243 211
    IntVector _rev_thread;
244 212
    IntVector _succ_num;
245 213
    IntVector _last_succ;
246 214
    IntVector _dirty_revs;
247 215
    BoolVector _forward;
248 216
    IntVector _state;
249 217
    int _root;
250 218

	
251 219
    // Temporary data used in the current pivot iteration
252 220
    int in_arc, join, u_in, v_in, u_out, v_out;
253 221
    int first, second, right, last;
254 222
    int stem, par_stem, new_stem;
255 223
    Value delta;
256 224

	
257 225
  public:
258 226
  
259 227
    /// \brief Constant for infinite upper bounds (capacities).
260 228
    ///
261 229
    /// Constant for infinite upper bounds (capacities).
262 230
    /// It is \c std::numeric_limits<Value>::infinity() if available,
263 231
    /// \c std::numeric_limits<Value>::max() otherwise.
264 232
    const Value INF;
265 233

	
266 234
  private:
267 235

	
268 236
    // Implementation of the First Eligible pivot rule
269 237
    class FirstEligiblePivotRule
270 238
    {
271 239
    private:
272 240

	
273 241
      // References to the NetworkSimplex class
274 242
      const IntVector  &_source;
275 243
      const IntVector  &_target;
276 244
      const CostVector &_cost;
277 245
      const IntVector  &_state;
278 246
      const CostVector &_pi;
279 247
      int &_in_arc;
280
      int _arc_num;
248
      int _search_arc_num;
281 249

	
282 250
      // Pivot rule data
283 251
      int _next_arc;
284 252

	
285 253
    public:
286 254

	
287 255
      // Constructor
288 256
      FirstEligiblePivotRule(NetworkSimplex &ns) :
289 257
        _source(ns._source), _target(ns._target),
290 258
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
291
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
259
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
260
        _next_arc(0)
292 261
      {}
293 262

	
294 263
      // Find next entering arc
295 264
      bool findEnteringArc() {
296 265
        Cost c;
297
        for (int e = _next_arc; e < _arc_num; ++e) {
266
        for (int e = _next_arc; e < _search_arc_num; ++e) {
298 267
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
299 268
          if (c < 0) {
300 269
            _in_arc = e;
301 270
            _next_arc = e + 1;
302 271
            return true;
303 272
          }
304 273
        }
305 274
        for (int e = 0; e < _next_arc; ++e) {
306 275
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
307 276
          if (c < 0) {
308 277
            _in_arc = e;
309 278
            _next_arc = e + 1;
310 279
            return true;
311 280
          }
312 281
        }
313 282
        return false;
314 283
      }
315 284

	
316 285
    }; //class FirstEligiblePivotRule
317 286

	
318 287

	
319 288
    // Implementation of the Best Eligible pivot rule
320 289
    class BestEligiblePivotRule
321 290
    {
322 291
    private:
323 292

	
324 293
      // References to the NetworkSimplex class
325 294
      const IntVector  &_source;
326 295
      const IntVector  &_target;
327 296
      const CostVector &_cost;
328 297
      const IntVector  &_state;
329 298
      const CostVector &_pi;
330 299
      int &_in_arc;
331
      int _arc_num;
300
      int _search_arc_num;
332 301

	
333 302
    public:
334 303

	
335 304
      // Constructor
336 305
      BestEligiblePivotRule(NetworkSimplex &ns) :
337 306
        _source(ns._source), _target(ns._target),
338 307
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
339
        _in_arc(ns.in_arc), _arc_num(ns._arc_num)
308
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
340 309
      {}
341 310

	
342 311
      // Find next entering arc
343 312
      bool findEnteringArc() {
344 313
        Cost c, min = 0;
345
        for (int e = 0; e < _arc_num; ++e) {
314
        for (int e = 0; e < _search_arc_num; ++e) {
346 315
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
347 316
          if (c < min) {
348 317
            min = c;
349 318
            _in_arc = e;
350 319
          }
351 320
        }
352 321
        return min < 0;
353 322
      }
354 323

	
355 324
    }; //class BestEligiblePivotRule
356 325

	
357 326

	
358 327
    // Implementation of the Block Search pivot rule
359 328
    class BlockSearchPivotRule
360 329
    {
361 330
    private:
362 331

	
363 332
      // References to the NetworkSimplex class
364 333
      const IntVector  &_source;
365 334
      const IntVector  &_target;
366 335
      const CostVector &_cost;
367 336
      const IntVector  &_state;
368 337
      const CostVector &_pi;
369 338
      int &_in_arc;
370
      int _arc_num;
339
      int _search_arc_num;
371 340

	
372 341
      // Pivot rule data
373 342
      int _block_size;
374 343
      int _next_arc;
375 344

	
376 345
    public:
377 346

	
378 347
      // Constructor
379 348
      BlockSearchPivotRule(NetworkSimplex &ns) :
380 349
        _source(ns._source), _target(ns._target),
381 350
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
382
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
351
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
352
        _next_arc(0)
383 353
      {
384 354
        // The main parameters of the pivot rule
385
        const double BLOCK_SIZE_FACTOR = 2.0;
355
        const double BLOCK_SIZE_FACTOR = 0.5;
386 356
        const int MIN_BLOCK_SIZE = 10;
387 357

	
388 358
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
389
                                    std::sqrt(double(_arc_num))),
359
                                    std::sqrt(double(_search_arc_num))),
390 360
                                MIN_BLOCK_SIZE );
391 361
      }
392 362

	
393 363
      // Find next entering arc
394 364
      bool findEnteringArc() {
395 365
        Cost c, min = 0;
396 366
        int cnt = _block_size;
397 367
        int e, min_arc = _next_arc;
398
        for (e = _next_arc; e < _arc_num; ++e) {
368
        for (e = _next_arc; e < _search_arc_num; ++e) {
399 369
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
400 370
          if (c < min) {
401 371
            min = c;
402 372
            min_arc = e;
403 373
          }
404 374
          if (--cnt == 0) {
405 375
            if (min < 0) break;
406 376
            cnt = _block_size;
407 377
          }
408 378
        }
409 379
        if (min == 0 || cnt > 0) {
410 380
          for (e = 0; e < _next_arc; ++e) {
411 381
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
412 382
            if (c < min) {
413 383
              min = c;
414 384
              min_arc = e;
415 385
            }
416 386
            if (--cnt == 0) {
417 387
              if (min < 0) break;
418 388
              cnt = _block_size;
419 389
            }
420 390
          }
421 391
        }
422 392
        if (min >= 0) return false;
423 393
        _in_arc = min_arc;
424 394
        _next_arc = e;
425 395
        return true;
426 396
      }
427 397

	
428 398
    }; //class BlockSearchPivotRule
429 399

	
430 400

	
431 401
    // Implementation of the Candidate List pivot rule
432 402
    class CandidateListPivotRule
433 403
    {
434 404
    private:
435 405

	
436 406
      // References to the NetworkSimplex class
437 407
      const IntVector  &_source;
438 408
      const IntVector  &_target;
439 409
      const CostVector &_cost;
440 410
      const IntVector  &_state;
441 411
      const CostVector &_pi;
442 412
      int &_in_arc;
443
      int _arc_num;
413
      int _search_arc_num;
444 414

	
445 415
      // Pivot rule data
446 416
      IntVector _candidates;
447 417
      int _list_length, _minor_limit;
448 418
      int _curr_length, _minor_count;
449 419
      int _next_arc;
450 420

	
451 421
    public:
452 422

	
453 423
      /// Constructor
454 424
      CandidateListPivotRule(NetworkSimplex &ns) :
455 425
        _source(ns._source), _target(ns._target),
456 426
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
457
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
427
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
428
        _next_arc(0)
458 429
      {
459 430
        // The main parameters of the pivot rule
460 431
        const double LIST_LENGTH_FACTOR = 1.0;
461 432
        const int MIN_LIST_LENGTH = 10;
462 433
        const double MINOR_LIMIT_FACTOR = 0.1;
463 434
        const int MIN_MINOR_LIMIT = 3;
464 435

	
465 436
        _list_length = std::max( int(LIST_LENGTH_FACTOR *
466
                                     std::sqrt(double(_arc_num))),
437
                                     std::sqrt(double(_search_arc_num))),
467 438
                                 MIN_LIST_LENGTH );
468 439
        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
469 440
                                 MIN_MINOR_LIMIT );
470 441
        _curr_length = _minor_count = 0;
471 442
        _candidates.resize(_list_length);
472 443
      }
473 444

	
474 445
      /// Find next entering arc
475 446
      bool findEnteringArc() {
476 447
        Cost min, c;
477 448
        int e, min_arc = _next_arc;
478 449
        if (_curr_length > 0 && _minor_count < _minor_limit) {
479 450
          // Minor iteration: select the best eligible arc from the
480 451
          // current candidate list
481 452
          ++_minor_count;
482 453
          min = 0;
483 454
          for (int i = 0; i < _curr_length; ++i) {
484 455
            e = _candidates[i];
485 456
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
486 457
            if (c < min) {
487 458
              min = c;
488 459
              min_arc = e;
489 460
            }
490 461
            if (c >= 0) {
491 462
              _candidates[i--] = _candidates[--_curr_length];
492 463
            }
493 464
          }
494 465
          if (min < 0) {
495 466
            _in_arc = min_arc;
496 467
            return true;
497 468
          }
498 469
        }
499 470

	
500 471
        // Major iteration: build a new candidate list
501 472
        min = 0;
502 473
        _curr_length = 0;
503
        for (e = _next_arc; e < _arc_num; ++e) {
474
        for (e = _next_arc; e < _search_arc_num; ++e) {
504 475
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
505 476
          if (c < 0) {
506 477
            _candidates[_curr_length++] = e;
507 478
            if (c < min) {
508 479
              min = c;
509 480
              min_arc = e;
510 481
            }
511 482
            if (_curr_length == _list_length) break;
512 483
          }
513 484
        }
514 485
        if (_curr_length < _list_length) {
515 486
          for (e = 0; e < _next_arc; ++e) {
516 487
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
517 488
            if (c < 0) {
518 489
              _candidates[_curr_length++] = e;
519 490
              if (c < min) {
520 491
                min = c;
521 492
                min_arc = e;
522 493
              }
523 494
              if (_curr_length == _list_length) break;
524 495
            }
525 496
          }
526 497
        }
527 498
        if (_curr_length == 0) return false;
528 499
        _minor_count = 1;
529 500
        _in_arc = min_arc;
530 501
        _next_arc = e;
531 502
        return true;
532 503
      }
533 504

	
534 505
    }; //class CandidateListPivotRule
535 506

	
536 507

	
537 508
    // Implementation of the Altering Candidate List pivot rule
538 509
    class AlteringListPivotRule
539 510
    {
540 511
    private:
541 512

	
542 513
      // References to the NetworkSimplex class
543 514
      const IntVector  &_source;
544 515
      const IntVector  &_target;
545 516
      const CostVector &_cost;
546 517
      const IntVector  &_state;
547 518
      const CostVector &_pi;
548 519
      int &_in_arc;
549
      int _arc_num;
520
      int _search_arc_num;
550 521

	
551 522
      // Pivot rule data
552 523
      int _block_size, _head_length, _curr_length;
553 524
      int _next_arc;
554 525
      IntVector _candidates;
555 526
      CostVector _cand_cost;
556 527

	
557 528
      // Functor class to compare arcs during sort of the candidate list
558 529
      class SortFunc
559 530
      {
560 531
      private:
561 532
        const CostVector &_map;
562 533
      public:
563 534
        SortFunc(const CostVector &map) : _map(map) {}
564 535
        bool operator()(int left, int right) {
565 536
          return _map[left] > _map[right];
566 537
        }
567 538
      };
568 539

	
569 540
      SortFunc _sort_func;
570 541

	
571 542
    public:
572 543

	
573 544
      // Constructor
574 545
      AlteringListPivotRule(NetworkSimplex &ns) :
575 546
        _source(ns._source), _target(ns._target),
576 547
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
577
        _in_arc(ns.in_arc), _arc_num(ns._arc_num),
578
        _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
548
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
549
        _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
579 550
      {
580 551
        // The main parameters of the pivot rule
581 552
        const double BLOCK_SIZE_FACTOR = 1.5;
582 553
        const int MIN_BLOCK_SIZE = 10;
583 554
        const double HEAD_LENGTH_FACTOR = 0.1;
584 555
        const int MIN_HEAD_LENGTH = 3;
585 556

	
586 557
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
587
                                    std::sqrt(double(_arc_num))),
558
                                    std::sqrt(double(_search_arc_num))),
588 559
                                MIN_BLOCK_SIZE );
589 560
        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
590 561
                                 MIN_HEAD_LENGTH );
591 562
        _candidates.resize(_head_length + _block_size);
592 563
        _curr_length = 0;
593 564
      }
594 565

	
595 566
      // Find next entering arc
596 567
      bool findEnteringArc() {
597 568
        // Check the current candidate list
598 569
        int e;
599 570
        for (int i = 0; i < _curr_length; ++i) {
600 571
          e = _candidates[i];
601 572
          _cand_cost[e] = _state[e] *
602 573
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
603 574
          if (_cand_cost[e] >= 0) {
604 575
            _candidates[i--] = _candidates[--_curr_length];
605 576
          }
606 577
        }
607 578

	
608 579
        // Extend the list
609 580
        int cnt = _block_size;
610 581
        int last_arc = 0;
611 582
        int limit = _head_length;
612 583

	
613
        for (int e = _next_arc; e < _arc_num; ++e) {
584
        for (int e = _next_arc; e < _search_arc_num; ++e) {
614 585
          _cand_cost[e] = _state[e] *
615 586
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
616 587
          if (_cand_cost[e] < 0) {
617 588
            _candidates[_curr_length++] = e;
618 589
            last_arc = e;
619 590
          }
620 591
          if (--cnt == 0) {
621 592
            if (_curr_length > limit) break;
622 593
            limit = 0;
623 594
            cnt = _block_size;
624 595
          }
625 596
        }
626 597
        if (_curr_length <= limit) {
627 598
          for (int e = 0; e < _next_arc; ++e) {
628 599
            _cand_cost[e] = _state[e] *
629 600
              (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
630 601
            if (_cand_cost[e] < 0) {
631 602
              _candidates[_curr_length++] = e;
632 603
              last_arc = e;
633 604
            }
634 605
            if (--cnt == 0) {
635 606
              if (_curr_length > limit) break;
636 607
              limit = 0;
637 608
              cnt = _block_size;
638 609
            }
639 610
          }
640 611
        }
641 612
        if (_curr_length == 0) return false;
642 613
        _next_arc = last_arc + 1;
643 614

	
644 615
        // Make heap of the candidate list (approximating a partial sort)
645 616
        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
646 617
                   _sort_func );
647 618

	
648 619
        // Pop the first element of the heap
649 620
        _in_arc = _candidates[0];
650 621
        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
651 622
                  _sort_func );
652 623
        _curr_length = std::min(_head_length, _curr_length - 1);
653 624
        return true;
654 625
      }
655 626

	
656 627
    }; //class AlteringListPivotRule
657 628

	
658 629
  public:
659 630

	
660 631
    /// \brief Constructor.
661 632
    ///
662 633
    /// The constructor of the class.
663 634
    ///
664 635
    /// \param graph The digraph the algorithm runs on.
665 636
    NetworkSimplex(const GR& graph) :
666 637
      _graph(graph), _node_id(graph), _arc_id(graph),
667 638
      INF(std::numeric_limits<Value>::has_infinity ?
668 639
          std::numeric_limits<Value>::infinity() :
669 640
          std::numeric_limits<Value>::max())
670 641
    {
671 642
      // Check the value types
672 643
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
673 644
        "The flow type of NetworkSimplex must be signed");
674 645
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
675 646
        "The cost type of NetworkSimplex must be signed");
676 647
        
677 648
      // Resize vectors
678 649
      _node_num = countNodes(_graph);
679 650
      _arc_num = countArcs(_graph);
680 651
      int all_node_num = _node_num + 1;
681
      int all_arc_num = _arc_num + _node_num;
652
      int max_arc_num = _arc_num + 2 * _node_num;
682 653

	
683
      _source.resize(all_arc_num);
684
      _target.resize(all_arc_num);
654
      _source.resize(max_arc_num);
655
      _target.resize(max_arc_num);
685 656

	
686
      _lower.resize(all_arc_num);
687
      _upper.resize(all_arc_num);
688
      _cap.resize(all_arc_num);
689
      _cost.resize(all_arc_num);
657
      _lower.resize(_arc_num);
658
      _upper.resize(_arc_num);
659
      _cap.resize(max_arc_num);
660
      _cost.resize(max_arc_num);
690 661
      _supply.resize(all_node_num);
691
      _flow.resize(all_arc_num);
662
      _flow.resize(max_arc_num);
692 663
      _pi.resize(all_node_num);
693 664

	
694 665
      _parent.resize(all_node_num);
695 666
      _pred.resize(all_node_num);
696 667
      _forward.resize(all_node_num);
697 668
      _thread.resize(all_node_num);
698 669
      _rev_thread.resize(all_node_num);
699 670
      _succ_num.resize(all_node_num);
700 671
      _last_succ.resize(all_node_num);
701
      _state.resize(all_arc_num);
672
      _state.resize(max_arc_num);
702 673

	
703 674
      // Copy the graph (store the arcs in a mixed order)
704 675
      int i = 0;
705 676
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
706 677
        _node_id[n] = i;
707 678
      }
708 679
      int k = std::max(int(std::sqrt(double(_arc_num))), 10);
709 680
      i = 0;
710 681
      for (ArcIt a(_graph); a != INVALID; ++a) {
711 682
        _arc_id[a] = i;
712 683
        _source[i] = _node_id[_graph.source(a)];
713 684
        _target[i] = _node_id[_graph.target(a)];
714 685
        if ((i += k) >= _arc_num) i = (i % k) + 1;
715 686
      }
716 687
      
717 688
      // Initialize maps
718 689
      for (int i = 0; i != _node_num; ++i) {
719 690
        _supply[i] = 0;
720 691
      }
721 692
      for (int i = 0; i != _arc_num; ++i) {
722 693
        _lower[i] = 0;
723 694
        _upper[i] = INF;
724 695
        _cost[i] = 1;
725 696
      }
726 697
      _have_lower = false;
727 698
      _stype = GEQ;
728 699
    }
729 700

	
730 701
    /// \name Parameters
731 702
    /// The parameters of the algorithm can be specified using these
732 703
    /// functions.
733 704

	
734 705
    /// @{
735 706

	
736 707
    /// \brief Set the lower bounds on the arcs.
737 708
    ///
738 709
    /// This function sets the lower bounds on the arcs.
739 710
    /// If it is not used before calling \ref run(), the lower bounds
740 711
    /// will be set to zero on all arcs.
741 712
    ///
742 713
    /// \param map An arc map storing the lower bounds.
743 714
    /// Its \c Value type must be convertible to the \c Value type
744 715
    /// of the algorithm.
745 716
    ///
746 717
    /// \return <tt>(*this)</tt>
747 718
    template <typename LowerMap>
748 719
    NetworkSimplex& lowerMap(const LowerMap& map) {
749 720
      _have_lower = true;
750 721
      for (ArcIt a(_graph); a != INVALID; ++a) {
751 722
        _lower[_arc_id[a]] = map[a];
752 723
      }
753 724
      return *this;
754 725
    }
755 726

	
756 727
    /// \brief Set the upper bounds (capacities) on the arcs.
757 728
    ///
758 729
    /// This function sets the upper bounds (capacities) on the arcs.
759 730
    /// If it is not used before calling \ref run(), the upper bounds
760 731
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
761 732
    /// unbounded from above on each arc).
762 733
    ///
763 734
    /// \param map An arc map storing the upper bounds.
764 735
    /// Its \c Value type must be convertible to the \c Value type
765 736
    /// of the algorithm.
766 737
    ///
767 738
    /// \return <tt>(*this)</tt>
768 739
    template<typename UpperMap>
769 740
    NetworkSimplex& upperMap(const UpperMap& map) {
770 741
      for (ArcIt a(_graph); a != INVALID; ++a) {
771 742
        _upper[_arc_id[a]] = map[a];
772 743
      }
773 744
      return *this;
774 745
    }
775 746

	
776 747
    /// \brief Set the costs of the arcs.
777 748
    ///
778 749
    /// This function sets the costs of the arcs.
779 750
    /// If it is not used before calling \ref run(), the costs
780 751
    /// will be set to \c 1 on all arcs.
781 752
    ///
782 753
    /// \param map An arc map storing the costs.
783 754
    /// Its \c Value type must be convertible to the \c Cost type
784 755
    /// of the algorithm.
785 756
    ///
786 757
    /// \return <tt>(*this)</tt>
787 758
    template<typename CostMap>
788 759
    NetworkSimplex& costMap(const CostMap& map) {
789 760
      for (ArcIt a(_graph); a != INVALID; ++a) {
790 761
        _cost[_arc_id[a]] = map[a];
791 762
      }
792 763
      return *this;
793 764
    }
794 765

	
795 766
    /// \brief Set the supply values of the nodes.
796 767
    ///
797 768
    /// This function sets the supply values of the nodes.
798 769
    /// If neither this function nor \ref stSupply() is used before
799 770
    /// calling \ref run(), the supply of each node will be set to zero.
800 771
    /// (It makes sense only if non-zero lower bounds are given.)
801 772
    ///
802 773
    /// \param map A node map storing the supply values.
803 774
    /// Its \c Value type must be convertible to the \c Value type
804 775
    /// of the algorithm.
805 776
    ///
806 777
    /// \return <tt>(*this)</tt>
807 778
    template<typename SupplyMap>
808 779
    NetworkSimplex& supplyMap(const SupplyMap& map) {
809 780
      for (NodeIt n(_graph); n != INVALID; ++n) {
810 781
        _supply[_node_id[n]] = map[n];
811 782
      }
812 783
      return *this;
813 784
    }
814 785

	
815 786
    /// \brief Set single source and target nodes and a supply value.
816 787
    ///
817 788
    /// This function sets a single source node and a single target node
818 789
    /// and the required flow value.
819 790
    /// If neither this function nor \ref supplyMap() is used before
820 791
    /// calling \ref run(), the supply of each node will be set to zero.
821 792
    /// (It makes sense only if non-zero lower bounds are given.)
822 793
    ///
823 794
    /// Using this function has the same effect as using \ref supplyMap()
824 795
    /// with such a map in which \c k is assigned to \c s, \c -k is
825 796
    /// assigned to \c t and all other nodes have zero supply value.
826 797
    ///
827 798
    /// \param s The source node.
828 799
    /// \param t The target node.
829 800
    /// \param k The required amount of flow from node \c s to node \c t
830 801
    /// (i.e. the supply of \c s and the demand of \c t).
831 802
    ///
832 803
    /// \return <tt>(*this)</tt>
833 804
    NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
834 805
      for (int i = 0; i != _node_num; ++i) {
835 806
        _supply[i] = 0;
836 807
      }
837 808
      _supply[_node_id[s]] =  k;
838 809
      _supply[_node_id[t]] = -k;
839 810
      return *this;
840 811
    }
841 812
    
842 813
    /// \brief Set the type of the supply constraints.
843 814
    ///
844 815
    /// This function sets the type of the supply/demand constraints.
845 816
    /// If it is not used before calling \ref run(), the \ref GEQ supply
846 817
    /// type will be used.
847 818
    ///
848 819
    /// For more information see \ref SupplyType.
849 820
    ///
850 821
    /// \return <tt>(*this)</tt>
851 822
    NetworkSimplex& supplyType(SupplyType supply_type) {
852 823
      _stype = supply_type;
853 824
      return *this;
854 825
    }
855 826

	
856 827
    /// @}
857 828

	
858 829
    /// \name Execution Control
859 830
    /// The algorithm can be executed using \ref run().
860 831

	
861 832
    /// @{
862 833

	
863 834
    /// \brief Run the algorithm.
864 835
    ///
865 836
    /// This function runs the algorithm.
866 837
    /// The paramters can be specified using functions \ref lowerMap(),
867 838
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(), 
868 839
    /// \ref supplyType().
869 840
    /// For example,
870 841
    /// \code
871 842
    ///   NetworkSimplex<ListDigraph> ns(graph);
872 843
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
873 844
    ///     .supplyMap(sup).run();
874 845
    /// \endcode
875 846
    ///
876 847
    /// This function can be called more than once. All the parameters
877 848
    /// that have been given are kept for the next call, unless
878 849
    /// \ref reset() is called, thus only the modified parameters
879 850
    /// have to be set again. See \ref reset() for examples.
880 851
    /// However the underlying digraph must not be modified after this
881 852
    /// class have been constructed, since it copies and extends the graph.
882 853
    ///
883 854
    /// \param pivot_rule The pivot rule that will be used during the
884 855
    /// algorithm. For more information see \ref PivotRule.
885 856
    ///
886 857
    /// \return \c INFEASIBLE if no feasible flow exists,
887 858
    /// \n \c OPTIMAL if the problem has optimal solution
888 859
    /// (i.e. it is feasible and bounded), and the algorithm has found
889 860
    /// optimal flow and node potentials (primal and dual solutions),
890 861
    /// \n \c UNBOUNDED if the objective function of the problem is
891 862
    /// unbounded, i.e. there is a directed cycle having negative total
892 863
    /// cost and infinite upper bound.
893 864
    ///
894 865
    /// \see ProblemType, PivotRule
895 866
    ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
896 867
      if (!init()) return INFEASIBLE;
897 868
      return start(pivot_rule);
898 869
    }
899 870

	
900 871
    /// \brief Reset all the parameters that have been given before.
901 872
    ///
902 873
    /// This function resets all the paramaters that have been given
903 874
    /// before using functions \ref lowerMap(), \ref upperMap(),
904 875
    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
905 876
    ///
906 877
    /// It is useful for multiple run() calls. If this function is not
907 878
    /// used, all the parameters given before are kept for the next
908 879
    /// \ref run() call.
909 880
    /// However the underlying digraph must not be modified after this
910 881
    /// class have been constructed, since it copies and extends the graph.
911 882
    ///
912 883
    /// For example,
913 884
    /// \code
914 885
    ///   NetworkSimplex<ListDigraph> ns(graph);
915 886
    ///
916 887
    ///   // First run
917 888
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
918 889
    ///     .supplyMap(sup).run();
919 890
    ///
920 891
    ///   // Run again with modified cost map (reset() is not called,
921 892
    ///   // so only the cost map have to be set again)
922 893
    ///   cost[e] += 100;
923 894
    ///   ns.costMap(cost).run();
924 895
    ///
925 896
    ///   // Run again from scratch using reset()
926 897
    ///   // (the lower bounds will be set to zero on all arcs)
927 898
    ///   ns.reset();
928 899
    ///   ns.upperMap(capacity).costMap(cost)
929 900
    ///     .supplyMap(sup).run();
930 901
    /// \endcode
931 902
    ///
932 903
    /// \return <tt>(*this)</tt>
933 904
    NetworkSimplex& reset() {
934 905
      for (int i = 0; i != _node_num; ++i) {
935 906
        _supply[i] = 0;
936 907
      }
937 908
      for (int i = 0; i != _arc_num; ++i) {
938 909
        _lower[i] = 0;
939 910
        _upper[i] = INF;
940 911
        _cost[i] = 1;
941 912
      }
942 913
      _have_lower = false;
943 914
      _stype = GEQ;
944 915
      return *this;
945 916
    }
946 917

	
947 918
    /// @}
948 919

	
949 920
    /// \name Query Functions
950 921
    /// The results of the algorithm can be obtained using these
951 922
    /// functions.\n
952 923
    /// The \ref run() function must be called before using them.
953 924

	
954 925
    /// @{
955 926

	
956 927
    /// \brief Return the total cost of the found flow.
957 928
    ///
958 929
    /// This function returns the total cost of the found flow.
959 930
    /// Its complexity is O(e).
960 931
    ///
961 932
    /// \note The return type of the function can be specified as a
962 933
    /// template parameter. For example,
963 934
    /// \code
964 935
    ///   ns.totalCost<double>();
965 936
    /// \endcode
966 937
    /// It is useful if the total cost cannot be stored in the \c Cost
967 938
    /// type of the algorithm, which is the default return type of the
968 939
    /// function.
969 940
    ///
970 941
    /// \pre \ref run() must be called before using this function.
971 942
    template <typename Number>
972 943
    Number totalCost() const {
973 944
      Number c = 0;
974 945
      for (ArcIt a(_graph); a != INVALID; ++a) {
975 946
        int i = _arc_id[a];
976 947
        c += Number(_flow[i]) * Number(_cost[i]);
977 948
      }
978 949
      return c;
979 950
    }
980 951

	
981 952
#ifndef DOXYGEN
982 953
    Cost totalCost() const {
983 954
      return totalCost<Cost>();
984 955
    }
985 956
#endif
986 957

	
987 958
    /// \brief Return the flow on the given arc.
988 959
    ///
989 960
    /// This function returns the flow on the given arc.
990 961
    ///
991 962
    /// \pre \ref run() must be called before using this function.
992 963
    Value flow(const Arc& a) const {
993 964
      return _flow[_arc_id[a]];
994 965
    }
995 966

	
996 967
    /// \brief Return the flow map (the primal solution).
997 968
    ///
998 969
    /// This function copies the flow value on each arc into the given
999 970
    /// map. The \c Value type of the algorithm must be convertible to
1000 971
    /// the \c Value type of the map.
1001 972
    ///
1002 973
    /// \pre \ref run() must be called before using this function.
1003 974
    template <typename FlowMap>
1004 975
    void flowMap(FlowMap &map) const {
1005 976
      for (ArcIt a(_graph); a != INVALID; ++a) {
1006 977
        map.set(a, _flow[_arc_id[a]]);
1007 978
      }
1008 979
    }
1009 980

	
1010 981
    /// \brief Return the potential (dual value) of the given node.
1011 982
    ///
1012 983
    /// This function returns the potential (dual value) of the
1013 984
    /// given node.
1014 985
    ///
1015 986
    /// \pre \ref run() must be called before using this function.
1016 987
    Cost potential(const Node& n) const {
1017 988
      return _pi[_node_id[n]];
1018 989
    }
1019 990

	
1020 991
    /// \brief Return the potential map (the dual solution).
1021 992
    ///
1022 993
    /// This function copies the potential (dual value) of each node
1023 994
    /// into the given map.
1024 995
    /// The \c Cost type of the algorithm must be convertible to the
1025 996
    /// \c Value type of the map.
1026 997
    ///
1027 998
    /// \pre \ref run() must be called before using this function.
1028 999
    template <typename PotentialMap>
1029 1000
    void potentialMap(PotentialMap &map) const {
1030 1001
      for (NodeIt n(_graph); n != INVALID; ++n) {
1031 1002
        map.set(n, _pi[_node_id[n]]);
1032 1003
      }
1033 1004
    }
1034 1005

	
1035 1006
    /// @}
1036 1007

	
1037 1008
  private:
1038 1009

	
1039 1010
    // Initialize internal data structures
1040 1011
    bool init() {
1041 1012
      if (_node_num == 0) return false;
1042 1013

	
1043 1014
      // Check the sum of supply values
1044 1015
      _sum_supply = 0;
1045 1016
      for (int i = 0; i != _node_num; ++i) {
1046 1017
        _sum_supply += _supply[i];
1047 1018
      }
1048 1019
      if ( !((_stype == GEQ && _sum_supply <= 0) ||
1049 1020
             (_stype == LEQ && _sum_supply >= 0)) ) return false;
1050 1021

	
1051 1022
      // Remove non-zero lower bounds
1052 1023
      if (_have_lower) {
1053 1024
        for (int i = 0; i != _arc_num; ++i) {
1054 1025
          Value c = _lower[i];
1055 1026
          if (c >= 0) {
1056 1027
            _cap[i] = _upper[i] < INF ? _upper[i] - c : INF;
1057 1028
          } else {
1058 1029
            _cap[i] = _upper[i] < INF + c ? _upper[i] - c : INF;
1059 1030
          }
1060 1031
          _supply[_source[i]] -= c;
1061 1032
          _supply[_target[i]] += c;
1062 1033
        }
1063 1034
      } else {
1064 1035
        for (int i = 0; i != _arc_num; ++i) {
1065 1036
          _cap[i] = _upper[i];
1066 1037
        }
1067 1038
      }
1068 1039

	
1069 1040
      // Initialize artifical cost
1070 1041
      Cost ART_COST;
1071 1042
      if (std::numeric_limits<Cost>::is_exact) {
1072
        ART_COST = std::numeric_limits<Cost>::max() / 4 + 1;
1043
        ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1073 1044
      } else {
1074 1045
        ART_COST = std::numeric_limits<Cost>::min();
1075 1046
        for (int i = 0; i != _arc_num; ++i) {
1076 1047
          if (_cost[i] > ART_COST) ART_COST = _cost[i];
1077 1048
        }
1078 1049
        ART_COST = (ART_COST + 1) * _node_num;
1079 1050
      }
1080 1051

	
1081 1052
      // Initialize arc maps
1082 1053
      for (int i = 0; i != _arc_num; ++i) {
1083 1054
        _flow[i] = 0;
1084 1055
        _state[i] = STATE_LOWER;
1085 1056
      }
1086 1057
      
1087 1058
      // Set data for the artificial root node
1088 1059
      _root = _node_num;
1089 1060
      _parent[_root] = -1;
1090 1061
      _pred[_root] = -1;
1091 1062
      _thread[_root] = 0;
1092 1063
      _rev_thread[0] = _root;
1093 1064
      _succ_num[_root] = _node_num + 1;
1094 1065
      _last_succ[_root] = _root - 1;
1095 1066
      _supply[_root] = -_sum_supply;
1096
      _pi[_root] = _sum_supply < 0 ? -ART_COST : ART_COST;
1067
      _pi[_root] = 0;
1097 1068

	
1098 1069
      // Add artificial arcs and initialize the spanning tree data structure
1099
      for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1100
        _parent[u] = _root;
1101
        _pred[u] = e;
1102
        _thread[u] = u + 1;
1103
        _rev_thread[u + 1] = u;
1104
        _succ_num[u] = 1;
1105
        _last_succ[u] = u;
1106
        _cost[e] = ART_COST;
1107
        _cap[e] = INF;
1108
        _state[e] = STATE_TREE;
1109
        if (_supply[u] > 0 || (_supply[u] == 0 && _sum_supply <= 0)) {
1110
          _flow[e] = _supply[u];
1111
          _forward[u] = true;
1112
          _pi[u] = -ART_COST + _pi[_root];
1113
        } else {
1114
          _flow[e] = -_supply[u];
1115
          _forward[u] = false;
1116
          _pi[u] = ART_COST + _pi[_root];
1070
      if (_sum_supply == 0) {
1071
        // EQ supply constraints
1072
        _search_arc_num = _arc_num;
1073
        _all_arc_num = _arc_num + _node_num;
1074
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1075
          _parent[u] = _root;
1076
          _pred[u] = e;
1077
          _thread[u] = u + 1;
1078
          _rev_thread[u + 1] = u;
1079
          _succ_num[u] = 1;
1080
          _last_succ[u] = u;
1081
          _cap[e] = INF;
1082
          _state[e] = STATE_TREE;
1083
          if (_supply[u] >= 0) {
1084
            _forward[u] = true;
1085
            _pi[u] = 0;
1086
            _source[e] = u;
1087
            _target[e] = _root;
1088
            _flow[e] = _supply[u];
1089
            _cost[e] = 0;
1090
          } else {
1091
            _forward[u] = false;
1092
            _pi[u] = ART_COST;
1093
            _source[e] = _root;
1094
            _target[e] = u;
1095
            _flow[e] = -_supply[u];
1096
            _cost[e] = ART_COST;
1097
          }
1117 1098
        }
1118 1099
      }
1100
      else if (_sum_supply > 0) {
1101
        // LEQ supply constraints
1102
        _search_arc_num = _arc_num + _node_num;
1103
        int f = _arc_num + _node_num;
1104
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1105
          _parent[u] = _root;
1106
          _thread[u] = u + 1;
1107
          _rev_thread[u + 1] = u;
1108
          _succ_num[u] = 1;
1109
          _last_succ[u] = u;
1110
          if (_supply[u] >= 0) {
1111
            _forward[u] = true;
1112
            _pi[u] = 0;
1113
            _pred[u] = e;
1114
            _source[e] = u;
1115
            _target[e] = _root;
1116
            _cap[e] = INF;
1117
            _flow[e] = _supply[u];
1118
            _cost[e] = 0;
1119
            _state[e] = STATE_TREE;
1120
          } else {
1121
            _forward[u] = false;
1122
            _pi[u] = ART_COST;
1123
            _pred[u] = f;
1124
            _source[f] = _root;
1125
            _target[f] = u;
1126
            _cap[f] = INF;
1127
            _flow[f] = -_supply[u];
1128
            _cost[f] = ART_COST;
1129
            _state[f] = STATE_TREE;
1130
            _source[e] = u;
1131
            _target[e] = _root;
1132
            _cap[e] = INF;
1133
            _flow[e] = 0;
1134
            _cost[e] = 0;
1135
            _state[e] = STATE_LOWER;
1136
            ++f;
1137
          }
1138
        }
1139
        _all_arc_num = f;
1140
      }
1141
      else {
1142
        // GEQ supply constraints
1143
        _search_arc_num = _arc_num + _node_num;
1144
        int f = _arc_num + _node_num;
1145
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1146
          _parent[u] = _root;
1147
          _thread[u] = u + 1;
1148
          _rev_thread[u + 1] = u;
1149
          _succ_num[u] = 1;
1150
          _last_succ[u] = u;
1151
          if (_supply[u] <= 0) {
1152
            _forward[u] = false;
1153
            _pi[u] = 0;
1154
            _pred[u] = e;
1155
            _source[e] = _root;
1156
            _target[e] = u;
1157
            _cap[e] = INF;
1158
            _flow[e] = -_supply[u];
1159
            _cost[e] = 0;
1160
            _state[e] = STATE_TREE;
1161
          } else {
1162
            _forward[u] = true;
1163
            _pi[u] = -ART_COST;
1164
            _pred[u] = f;
1165
            _source[f] = u;
1166
            _target[f] = _root;
1167
            _cap[f] = INF;
1168
            _flow[f] = _supply[u];
1169
            _state[f] = STATE_TREE;
1170
            _cost[f] = ART_COST;
1171
            _source[e] = _root;
1172
            _target[e] = u;
1173
            _cap[e] = INF;
1174
            _flow[e] = 0;
1175
            _cost[e] = 0;
1176
            _state[e] = STATE_LOWER;
1177
            ++f;
1178
          }
1179
        }
1180
        _all_arc_num = f;
1181
      }
1119 1182

	
1120 1183
      return true;
1121 1184
    }
1122 1185

	
1123 1186
    // Find the join node
1124 1187
    void findJoinNode() {
1125 1188
      int u = _source[in_arc];
1126 1189
      int v = _target[in_arc];
1127 1190
      while (u != v) {
1128 1191
        if (_succ_num[u] < _succ_num[v]) {
1129 1192
          u = _parent[u];
1130 1193
        } else {
1131 1194
          v = _parent[v];
1132 1195
        }
1133 1196
      }
1134 1197
      join = u;
1135 1198
    }
1136 1199

	
1137 1200
    // Find the leaving arc of the cycle and returns true if the
1138 1201
    // leaving arc is not the same as the entering arc
1139 1202
    bool findLeavingArc() {
1140 1203
      // Initialize first and second nodes according to the direction
1141 1204
      // of the cycle
1142 1205
      if (_state[in_arc] == STATE_LOWER) {
1143 1206
        first  = _source[in_arc];
1144 1207
        second = _target[in_arc];
1145 1208
      } else {
1146 1209
        first  = _target[in_arc];
1147 1210
        second = _source[in_arc];
1148 1211
      }
1149 1212
      delta = _cap[in_arc];
1150 1213
      int result = 0;
1151 1214
      Value d;
1152 1215
      int e;
1153 1216

	
1154 1217
      // Search the cycle along the path form the first node to the root
1155 1218
      for (int u = first; u != join; u = _parent[u]) {
1156 1219
        e = _pred[u];
1157 1220
        d = _forward[u] ?
1158 1221
          _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1159 1222
        if (d < delta) {
1160 1223
          delta = d;
1161 1224
          u_out = u;
1162 1225
          result = 1;
1163 1226
        }
1164 1227
      }
1165 1228
      // Search the cycle along the path form the second node to the root
1166 1229
      for (int u = second; u != join; u = _parent[u]) {
1167 1230
        e = _pred[u];
1168 1231
        d = _forward[u] ? 
1169 1232
          (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1170 1233
        if (d <= delta) {
1171 1234
          delta = d;
1172 1235
          u_out = u;
1173 1236
          result = 2;
1174 1237
        }
1175 1238
      }
1176 1239

	
1177 1240
      if (result == 1) {
1178 1241
        u_in = first;
1179 1242
        v_in = second;
1180 1243
      } else {
1181 1244
        u_in = second;
1182 1245
        v_in = first;
1183 1246
      }
1184 1247
      return result != 0;
1185 1248
    }
1186 1249

	
1187 1250
    // Change _flow and _state vectors
1188 1251
    void changeFlow(bool change) {
1189 1252
      // Augment along the cycle
1190 1253
      if (delta > 0) {
1191 1254
        Value val = _state[in_arc] * delta;
1192 1255
        _flow[in_arc] += val;
1193 1256
        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1194 1257
          _flow[_pred[u]] += _forward[u] ? -val : val;
1195 1258
        }
1196 1259
        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1197 1260
          _flow[_pred[u]] += _forward[u] ? val : -val;
1198 1261
        }
1199 1262
      }
1200 1263
      // Update the state of the entering and leaving arcs
1201 1264
      if (change) {
1202 1265
        _state[in_arc] = STATE_TREE;
1203 1266
        _state[_pred[u_out]] =
1204 1267
          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1205 1268
      } else {
1206 1269
        _state[in_arc] = -_state[in_arc];
1207 1270
      }
1208 1271
    }
1209 1272

	
1210 1273
    // Update the tree structure
1211 1274
    void updateTreeStructure() {
1212 1275
      int u, w;
1213 1276
      int old_rev_thread = _rev_thread[u_out];
1214 1277
      int old_succ_num = _succ_num[u_out];
1215 1278
      int old_last_succ = _last_succ[u_out];
1216 1279
      v_out = _parent[u_out];
1217 1280

	
1218 1281
      u = _last_succ[u_in];  // the last successor of u_in
1219 1282
      right = _thread[u];    // the node after it
1220 1283

	
1221 1284
      // Handle the case when old_rev_thread equals to v_in
1222 1285
      // (it also means that join and v_out coincide)
1223 1286
      if (old_rev_thread == v_in) {
1224 1287
        last = _thread[_last_succ[u_out]];
1225 1288
      } else {
1226 1289
        last = _thread[v_in];
1227 1290
      }
1228 1291

	
1229 1292
      // Update _thread and _parent along the stem nodes (i.e. the nodes
1230 1293
      // between u_in and u_out, whose parent have to be changed)
1231 1294
      _thread[v_in] = stem = u_in;
1232 1295
      _dirty_revs.clear();
1233 1296
      _dirty_revs.push_back(v_in);
1234 1297
      par_stem = v_in;
1235 1298
      while (stem != u_out) {
1236 1299
        // Insert the next stem node into the thread list
1237 1300
        new_stem = _parent[stem];
1238 1301
        _thread[u] = new_stem;
1239 1302
        _dirty_revs.push_back(u);
1240 1303

	
1241 1304
        // Remove the subtree of stem from the thread list
1242 1305
        w = _rev_thread[stem];
1243 1306
        _thread[w] = right;
1244 1307
        _rev_thread[right] = w;
1245 1308

	
1246 1309
        // Change the parent node and shift stem nodes
1247 1310
        _parent[stem] = par_stem;
1248 1311
        par_stem = stem;
1249 1312
        stem = new_stem;
1250 1313

	
1251 1314
        // Update u and right
1252 1315
        u = _last_succ[stem] == _last_succ[par_stem] ?
1253 1316
          _rev_thread[par_stem] : _last_succ[stem];
1254 1317
        right = _thread[u];
1255 1318
      }
1256 1319
      _parent[u_out] = par_stem;
1257 1320
      _thread[u] = last;
1258 1321
      _rev_thread[last] = u;
1259 1322
      _last_succ[u_out] = u;
1260 1323

	
1261 1324
      // Remove the subtree of u_out from the thread list except for
1262 1325
      // the case when old_rev_thread equals to v_in
1263 1326
      // (it also means that join and v_out coincide)
1264 1327
      if (old_rev_thread != v_in) {
1265 1328
        _thread[old_rev_thread] = right;
1266 1329
        _rev_thread[right] = old_rev_thread;
1267 1330
      }
1268 1331

	
1269 1332
      // Update _rev_thread using the new _thread values
1270 1333
      for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1271 1334
        u = _dirty_revs[i];
1272 1335
        _rev_thread[_thread[u]] = u;
1273 1336
      }
1274 1337

	
1275 1338
      // Update _pred, _forward, _last_succ and _succ_num for the
1276 1339
      // stem nodes from u_out to u_in
1277 1340
      int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1278 1341
      u = u_out;
1279 1342
      while (u != u_in) {
1280 1343
        w = _parent[u];
1281 1344
        _pred[u] = _pred[w];
1282 1345
        _forward[u] = !_forward[w];
1283 1346
        tmp_sc += _succ_num[u] - _succ_num[w];
1284 1347
        _succ_num[u] = tmp_sc;
1285 1348
        _last_succ[w] = tmp_ls;
1286 1349
        u = w;
1287 1350
      }
1288 1351
      _pred[u_in] = in_arc;
1289 1352
      _forward[u_in] = (u_in == _source[in_arc]);
1290 1353
      _succ_num[u_in] = old_succ_num;
1291 1354

	
1292 1355
      // Set limits for updating _last_succ form v_in and v_out
1293 1356
      // towards the root
1294 1357
      int up_limit_in = -1;
1295 1358
      int up_limit_out = -1;
1296 1359
      if (_last_succ[join] == v_in) {
1297 1360
        up_limit_out = join;
1298 1361
      } else {
1299 1362
        up_limit_in = join;
1300 1363
      }
1301 1364

	
1302 1365
      // Update _last_succ from v_in towards the root
1303 1366
      for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1304 1367
           u = _parent[u]) {
1305 1368
        _last_succ[u] = _last_succ[u_out];
1306 1369
      }
1307 1370
      // Update _last_succ from v_out towards the root
1308 1371
      if (join != old_rev_thread && v_in != old_rev_thread) {
1309 1372
        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1310 1373
             u = _parent[u]) {
1311 1374
          _last_succ[u] = old_rev_thread;
1312 1375
        }
1313 1376
      } else {
1314 1377
        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1315 1378
             u = _parent[u]) {
1316 1379
          _last_succ[u] = _last_succ[u_out];
1317 1380
        }
1318 1381
      }
1319 1382

	
1320 1383
      // Update _succ_num from v_in to join
1321 1384
      for (u = v_in; u != join; u = _parent[u]) {
1322 1385
        _succ_num[u] += old_succ_num;
1323 1386
      }
1324 1387
      // Update _succ_num from v_out to join
1325 1388
      for (u = v_out; u != join; u = _parent[u]) {
1326 1389
        _succ_num[u] -= old_succ_num;
1327 1390
      }
1328 1391
    }
1329 1392

	
1330 1393
    // Update potentials
1331 1394
    void updatePotential() {
1332 1395
      Cost sigma = _forward[u_in] ?
1333 1396
        _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1334 1397
        _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1335 1398
      // Update potentials in the subtree, which has been moved
1336 1399
      int end = _thread[_last_succ[u_in]];
1337 1400
      for (int u = u_in; u != end; u = _thread[u]) {
1338 1401
        _pi[u] += sigma;
1339 1402
      }
1340 1403
    }
1341 1404

	
1342 1405
    // Execute the algorithm
1343 1406
    ProblemType start(PivotRule pivot_rule) {
1344 1407
      // Select the pivot rule implementation
1345 1408
      switch (pivot_rule) {
1346 1409
        case FIRST_ELIGIBLE:
1347 1410
          return start<FirstEligiblePivotRule>();
1348 1411
        case BEST_ELIGIBLE:
1349 1412
          return start<BestEligiblePivotRule>();
1350 1413
        case BLOCK_SEARCH:
1351 1414
          return start<BlockSearchPivotRule>();
1352 1415
        case CANDIDATE_LIST:
1353 1416
          return start<CandidateListPivotRule>();
1354 1417
        case ALTERING_LIST:
1355 1418
          return start<AlteringListPivotRule>();
1356 1419
      }
1357 1420
      return INFEASIBLE; // avoid warning
1358 1421
    }
1359 1422

	
1360 1423
    template <typename PivotRuleImpl>
1361 1424
    ProblemType start() {
1362 1425
      PivotRuleImpl pivot(*this);
1363 1426

	
1364 1427
      // Execute the Network Simplex algorithm
1365 1428
      while (pivot.findEnteringArc()) {
1366 1429
        findJoinNode();
1367 1430
        bool change = findLeavingArc();
1368 1431
        if (delta >= INF) return UNBOUNDED;
1369 1432
        changeFlow(change);
1370 1433
        if (change) {
1371 1434
          updateTreeStructure();
1372 1435
          updatePotential();
1373 1436
        }
1374 1437
      }
1375 1438
      
1376 1439
      // Check feasibility
1377
      if (_sum_supply < 0) {
1378
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1379
          if (_supply[u] >= 0 && _flow[e] != 0) return INFEASIBLE;
1380
        }
1381
      }
1382
      else if (_sum_supply > 0) {
1383
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1384
          if (_supply[u] <= 0 && _flow[e] != 0) return INFEASIBLE;
1385
        }
1386
      }
1387
      else {
1388
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1389
          if (_flow[e] != 0) return INFEASIBLE;
1390
        }
1440
      for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1441
        if (_flow[e] != 0) return INFEASIBLE;
1391 1442
      }
1392 1443

	
1393 1444
      // Transform the solution and the supply map to the original form
1394 1445
      if (_have_lower) {
1395 1446
        for (int i = 0; i != _arc_num; ++i) {
1396 1447
          Value c = _lower[i];
1397 1448
          if (c != 0) {
1398 1449
            _flow[i] += c;
1399 1450
            _supply[_source[i]] += c;
1400 1451
            _supply[_target[i]] -= c;
1401 1452
          }
1402 1453
        }
1403 1454
      }
1455
      
1456
      // Shift potentials to meet the requirements of the GEQ/LEQ type
1457
      // optimality conditions
1458
      if (_sum_supply == 0) {
1459
        if (_stype == GEQ) {
1460
          Cost max_pot = std::numeric_limits<Cost>::min();
1461
          for (int i = 0; i != _node_num; ++i) {
1462
            if (_pi[i] > max_pot) max_pot = _pi[i];
1463
          }
1464
          if (max_pot > 0) {
1465
            for (int i = 0; i != _node_num; ++i)
1466
              _pi[i] -= max_pot;
1467
          }
1468
        } else {
1469
          Cost min_pot = std::numeric_limits<Cost>::max();
1470
          for (int i = 0; i != _node_num; ++i) {
1471
            if (_pi[i] < min_pot) min_pot = _pi[i];
1472
          }
1473
          if (min_pot < 0) {
1474
            for (int i = 0; i != _node_num; ++i)
1475
              _pi[i] -= min_pot;
1476
          }
1477
        }
1478
      }
1404 1479

	
1405 1480
      return OPTIMAL;
1406 1481
    }
1407 1482

	
1408 1483
  }; //class NetworkSimplex
1409 1484

	
1410 1485
  ///@}
1411 1486

	
1412 1487
} //namespace lemon
1413 1488

	
1414 1489
#endif //LEMON_NETWORK_SIMPLEX_H
Ignore white space 6 line context
1 1
#!/bin/bash
2 2

	
3 3
YEAR=`date +%Y`
4 4
HGROOT=`hg root`
5 5

	
6 6
function hg_year() {
7 7
    if [ -n "$(hg st $1)" ]; then
8 8
        echo $YEAR
9
    else
10
        hg log -l 1 --template='{date|isodate}\n' $1 |
11
        cut -d '-' -f 1
12
    fi
9 13
}
10 14

	
11 15
# file enumaration modes
12 16

	
13 17
function all_files() {
14 18
    hg status -a -m -c |
15 19
    cut -d ' ' -f 2 | grep -E '(\.(cc|h|dox)$|Makefile\.am$)' |
16 20
    while read file; do echo $HGROOT/$file; done
17 21
}
18 22

	
19 23
function modified_files() {
20 24
    hg status -a -m |
21 25
    cut -d ' ' -f 2 | grep -E  '(\.(cc|h|dox)$|Makefile\.am$)' |
22 26
    while read file; do echo $HGROOT/$file; done
23 27
}
24 28

	
25 29
function changed_files() {
26 30
    {
27 31
        if [ -n "$HG_PARENT1" ]
28 32
        then
29 33
            hg status --rev $HG_PARENT1:$HG_NODE -a -m
30 34
        fi
31 35
        if [ -n "$HG_PARENT2" ]
32 36
        then
33 37
            hg status --rev $HG_PARENT2:$HG_NODE -a -m
34 38
        fi
35 39
    } | cut -d ' ' -f 2 | grep -E '(\.(cc|h|dox)$|Makefile\.am$)' | 
36 40
    sort | uniq |
37 41
    while read file; do echo $HGROOT/$file; done
38 42
}
39 43

	
40 44
function given_files() {
41 45
    for file in $GIVEN_FILES
42 46
    do
43 47
	echo $file
44 48
    done
45 49
}
46 50

	
47 51
# actions
48 52

	
49 53
function update_action() {
50 54
    if ! diff -q $1 $2 >/dev/null
51 55
    then
52 56
	echo -n " [$3 updated]"
53 57
	rm $2
54 58
	mv $1 $2
55 59
	CHANGED=YES
56 60
    fi
57 61
}
58 62

	
59 63
function update_warning() {
60 64
    echo -n " [$2 warning]"
61 65
    WARNED=YES
62 66
}
63 67

	
64 68
function update_init() {
65 69
    echo Update source files...
66 70
    TOTAL_FILES=0
67 71
    CHANGED_FILES=0
68 72
    WARNED_FILES=0
69 73
}
70 74

	
71 75
function update_done() {
72 76
    echo $CHANGED_FILES out of $TOTAL_FILES files has been changed.
73 77
    echo $WARNED_FILES out of $TOTAL_FILES files triggered warnings.
74 78
}
75 79

	
76 80
function update_begin() {
77 81
    ((TOTAL_FILES++))
78 82
    CHANGED=NO
79 83
    WARNED=NO
80 84
}
81 85

	
82 86
function update_end() {
83 87
    if [ $CHANGED == YES ]
84 88
    then
85 89
	((++CHANGED_FILES))
86 90
    fi
87 91
    if [ $WARNED == YES ]
88 92
    then
89 93
	((++WARNED_FILES))
90 94
    fi
91 95
}
92 96

	
93 97
function check_action() {
94 98
    if [ "$3" == 'tabs' ]
95 99
    then
96 100
        if echo $2 | grep -q -v -E 'Makefile\.am$'
97 101
        then
98 102
            PATTERN=$(echo -e '\t')
99 103
        else
100 104
            PATTERN='        '
101 105
        fi
102 106
    elif [ "$3" == 'trailing spaces' ]
103 107
    then
104 108
        PATTERN='\ +$'
105 109
    else
106 110
        PATTERN='*'
107 111
    fi
108 112

	
109 113
    if ! diff -q $1 $2 >/dev/null
110 114
    then
111 115
        if [ "$PATTERN" == '*' ]
112 116
        then
113 117
            diff $1 $2 | grep '^[0-9]' | sed "s|^\(.*\)c.*$|$2:\1: check failed: $3|g" |
114 118
              sed "s/:\([0-9]*\),\([0-9]*\):\(.*\)$/:\1:\3 (until line \2)/g"
115 119
        else
116 120
            grep -n -E "$PATTERN" $2 | sed "s|^\([0-9]*\):.*$|$2:\1: check failed: $3|g"
117 121
        fi
118 122
        FAILED=YES
119 123
    fi
120 124
}
121 125

	
122 126
function check_warning() {
123 127
    if [ "$2" == 'long lines' ]
124 128
    then
125 129
        grep -n -E '.{81,}' $1 | sed "s|^\([0-9]*\):.*$|$1:\1: warning: $2|g"
126 130
    else
127 131
        echo "$1: warning: $2"
128 132
    fi
129 133
    WARNED=YES
130 134
}
131 135

	
132 136
function check_init() {
133 137
    echo Check source files...
134 138
    FAILED_FILES=0
135 139
    WARNED_FILES=0
136 140
    TOTAL_FILES=0
137 141
}
138 142

	
139 143
function check_done() {
140 144
    echo $FAILED_FILES out of $TOTAL_FILES files has been failed.
141 145
    echo $WARNED_FILES out of $TOTAL_FILES files triggered warnings.
142 146

	
143 147
    if [ $WARNED_FILES -gt 0 -o $FAILED_FILES -gt 0 ]
144 148
    then
145 149
	if [ "$WARNING" == 'INTERACTIVE' ]
146 150
	then
147 151
	    echo -n "Are the files with errors/warnings acceptable? (yes/no) "
148 152
	    while read answer
149 153
	    do
150 154
		if [ "$answer" == 'yes' ]
151 155
		then
152 156
		    return 0
153 157
		elif [ "$answer" == 'no' ]
154 158
		then
155 159
		    return 1
156 160
		fi
157 161
		echo -n "Are the files with errors/warnings acceptable? (yes/no) "
158 162
	    done
159 163
	elif [ "$WARNING" == 'WERROR' ]
160 164
	then
161 165
	    return 1
162 166
	fi
163 167
    fi
164 168
}
165 169

	
166 170
function check_begin() {
167 171
    ((TOTAL_FILES++))
168 172
    FAILED=NO
169 173
    WARNED=NO
170 174
}
171 175

	
172 176
function check_end() {
173 177
    if [ $FAILED == YES ]
174 178
    then
175 179
	((++FAILED_FILES))
176 180
    fi
177 181
    if [ $WARNED == YES ]
178 182
    then
179 183
	((++WARNED_FILES))
180 184
    fi
181 185
}
182 186

	
183 187

	
184 188

	
185 189
# checks
186 190

	
187 191
function header_check() {
188 192
    if echo $1 | grep -q -E 'Makefile\.am$'
189 193
    then
190 194
	return
191 195
    fi
192 196

	
193 197
    TMP_FILE=`mktemp`
194 198

	
195 199
    (echo "/* -*- mode: C++; indent-tabs-mode: nil; -*-
196 200
 *
197 201
 * This file is a part of LEMON, a generic C++ optimization library.
198 202
 *
199 203
 * Copyright (C) 2003-"$(hg_year $1)"
200 204
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
201 205
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
202 206
 *
203 207
 * Permission to use, modify and distribute this software is granted
204 208
 * provided that this copyright notice appears in all copies. For
205 209
 * precise terms see the accompanying LICENSE file.
206 210
 *
207 211
 * This software is provided \"AS IS\" with no warranty of any kind,
208 212
 * express or implied, and with no claim as to its suitability for any
209 213
 * purpose.
210 214
 *
211 215
 */
212 216
"
213 217
    awk 'BEGIN { pm=0; }
214 218
     pm==3 { print }
215 219
     /\/\* / && pm==0 { pm=1;}
216 220
     /[^:blank:]/ && (pm==0 || pm==2) { pm=3; print;}
217 221
     /\*\// && pm==1 { pm=2;}
218 222
    ' $1
219 223
    ) >$TMP_FILE
220 224

	
221 225
    "$ACTION"_action "$TMP_FILE" "$1" header
222 226
}
223 227

	
224 228
function tabs_check() {
225 229
    if echo $1 | grep -q -v -E 'Makefile\.am$'
226 230
    then
227 231
        OLD_PATTERN=$(echo -e '\t')
228 232
        NEW_PATTERN='        '
229 233
    else
230 234
        OLD_PATTERN='        '
231 235
        NEW_PATTERN=$(echo -e '\t')
232 236
    fi
233 237
    TMP_FILE=`mktemp`
234 238
    cat $1 | sed -e "s/$OLD_PATTERN/$NEW_PATTERN/g" >$TMP_FILE
235 239

	
236 240
    "$ACTION"_action "$TMP_FILE" "$1" 'tabs'
237 241
}
238 242

	
239 243
function spaces_check() {
240 244
    TMP_FILE=`mktemp`
241 245
    cat $1 | sed -e 's/ \+$//g' >$TMP_FILE
242 246

	
243 247
    "$ACTION"_action "$TMP_FILE" "$1" 'trailing spaces'
244 248
}
245 249

	
246 250
function long_lines_check() {
247 251
    if cat $1 | grep -q -E '.{81,}'
248 252
    then
249 253
	"$ACTION"_warning $1 'long lines'
250 254
    fi
251 255
}
252 256

	
253 257
# process the file
254 258

	
255 259
function process_file() {
256 260
    if [ "$ACTION" == 'update' ]
257 261
    then
258 262
        echo -n "    $ACTION $1..."
259 263
    else
260 264
        echo "	  $ACTION $1..."
261 265
    fi
262 266

	
263 267
    CHECKING="header tabs spaces long_lines"
264 268

	
265 269
    "$ACTION"_begin $1
266 270
    for check in $CHECKING
267 271
    do
268 272
	"$check"_check $1
269 273
    done
270 274
    "$ACTION"_end $1
271 275
    if [ "$ACTION" == 'update' ]
272 276
    then
273 277
        echo
274 278
    fi
275 279
}
276 280

	
277 281
function process_all {
278 282
    "$ACTION"_init
279 283
    while read file
280 284
    do
281 285
	process_file $file
282 286
    done < <($FILES)
283 287
    "$ACTION"_done
284 288
}
285 289

	
286 290
while [ $# -gt 0 ]
287 291
do
288 292
    
289 293
    if [ "$1" == '--help' ] || [ "$1" == '-h' ]
290 294
    then
291 295
	echo -n \
292 296
"Usage:
293 297
  $0 [OPTIONS] [files]
294 298
Options:
295 299
  --dry-run|-n
296 300
     Check the files, but do not modify them.
297 301
  --interactive|-i
298 302
     If --dry-run is specified and the checker emits warnings,
299 303
     then the user is asked if the warnings should be considered
300 304
     errors.
301 305
  --werror|-w
302 306
     Make all warnings into errors.
303 307
  --all|-a
304 308
     Check all source files in the repository.
305 309
  --modified|-m
306 310
     Check only the modified (and new) source files. This option is
307 311
     useful to check the modification before making a commit.
308 312
  --changed|-c
309 313
     Check only the changed source files compared to the parent(s) of
310 314
     the current hg node.  This option is useful as hg hook script.
311 315
     To automatically check all your changes before making a commit,
312 316
     add the following section to the appropriate .hg/hgrc file.
313 317

	
314 318
       [hooks]
315 319
       pretxncommit.checksources = scripts/unify-sources.sh -c -n -i
316 320

	
317 321
  --help|-h
318 322
     Print this help message.
319 323
  files
320 324
     The files to check/unify. If no file names are given, the modified
321 325
     source files will be checked/unified (just like using the
322 326
     --modified|-m option).
323 327
"
324 328
        exit 0
325 329
    elif [ "$1" == '--dry-run' ] || [ "$1" == '-n' ]
326 330
    then
327 331
	[ -n "$ACTION" ] && echo "Conflicting action options" >&2 && exit 1
328 332
	ACTION=check
329 333
    elif [ "$1" == "--all" ] || [ "$1" == '-a' ]
330 334
    then
331 335
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
332 336
	FILES=all_files
333 337
    elif [ "$1" == "--changed" ] || [ "$1" == '-c' ]
334 338
    then
335 339
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
336 340
	FILES=changed_files
337 341
    elif [ "$1" == "--modified" ] || [ "$1" == '-m' ]
338 342
    then
339 343
	[ -n "$FILES" ] && echo "Conflicting target options" >&2 && exit 1
340 344
	FILES=modified_files
341 345
    elif [ "$1" == "--interactive" ] || [ "$1" == "-i" ]
342 346
    then
343 347
	[ -n "$WARNING" ] && echo "Conflicting warning options" >&2 && exit 1
344 348
	WARNING='INTERACTIVE'
345 349
    elif [ "$1" == "--werror" ] || [ "$1" == "-w" ]
346 350
    then
347 351
	[ -n "$WARNING" ] && echo "Conflicting warning options" >&2 && exit 1
348 352
	WARNING='WERROR'
349 353
    elif [ $(echo x$1 | cut -c 2) == '-' ]
350 354
    then
351 355
	echo "Invalid option $1" >&2 && exit 1
352 356
    else
353 357
	[ -n "$FILES" ] && echo "Invalid option $1" >&2 && exit 1
354 358
	GIVEN_FILES=$@
355 359
	FILES=given_files
356 360
	break
357 361
    fi
358 362
    
359 363
    shift
360 364
done
361 365

	
362 366
if [ -z $FILES ]
363 367
then
364 368
    FILES=modified_files
365 369
fi
366 370

	
367 371
if [ -z $ACTION ]
368 372
then
369 373
    ACTION=update
370 374
fi
371 375

	
372 376
process_all
Ignore white space 6 line context
1 1
INCLUDE_DIRECTORIES(
2 2
  ${PROJECT_SOURCE_DIR}
3 3
  ${PROJECT_BINARY_DIR}
4 4
)
5 5

	
6 6
LINK_DIRECTORIES(${PROJECT_BINARY_DIR}/lemon)
7 7

	
8 8
SET(TESTS
9 9
  adaptors_test
10 10
  bfs_test
11 11
  circulation_test
12
  connectivity_test
12 13
  counter_test
13 14
  dfs_test
14 15
  digraph_test
15 16
  dijkstra_test
16 17
  dim_test
17 18
  edge_set_test
18 19
  error_test
19 20
  euler_test
20 21
  gomory_hu_test
21 22
  graph_copy_test
22 23
  graph_test
23 24
  graph_utils_test
24 25
  hao_orlin_test
25 26
  heap_test
26 27
  kruskal_test
27 28
  maps_test
28 29
  matching_test
29 30
  min_cost_arborescence_test
30 31
  min_cost_flow_test
31 32
  path_test
32 33
  preflow_test
33 34
  radix_sort_test
34 35
  random_test
35 36
  suurballe_test
36 37
  time_measure_test
37 38
  unionfind_test)
38 39

	
39 40
IF(LEMON_HAVE_LP)
40 41
  ADD_EXECUTABLE(lp_test lp_test.cc)
41 42
  SET(LP_TEST_LIBS lemon)
42 43
  IF(LEMON_HAVE_GLPK)
43 44
    SET(LP_TEST_LIBS ${LP_TEST_LIBS} ${GLPK_LIBRARIES})
44 45
  ENDIF(LEMON_HAVE_GLPK)
45 46
  IF(LEMON_HAVE_CPLEX)
46 47
    SET(LP_TEST_LIBS ${LP_TEST_LIBS} ${CPLEX_LIBRARIES})
47 48
  ENDIF(LEMON_HAVE_CPLEX)
48 49
  IF(LEMON_HAVE_CLP)
49 50
    SET(LP_TEST_LIBS ${LP_TEST_LIBS} ${COIN_CLP_LIBRARIES})
50 51
  ENDIF(LEMON_HAVE_CLP)
51 52
  TARGET_LINK_LIBRARIES(lp_test ${LP_TEST_LIBS})
52 53
  ADD_TEST(lp_test lp_test)
53 54

	
54 55
  IF(WIN32 AND LEMON_HAVE_GLPK)
55 56
    GET_TARGET_PROPERTY(TARGET_LOC lp_test LOCATION)
56 57
    GET_FILENAME_COMPONENT(TARGET_PATH ${TARGET_LOC} PATH)
57 58
    ADD_CUSTOM_COMMAND(TARGET lp_test POST_BUILD
58 59
      COMMAND cmake -E copy ${GLPK_BIN_DIR}/glpk.dll ${TARGET_PATH}
59 60
      COMMAND cmake -E copy ${GLPK_BIN_DIR}/libltdl3.dll ${TARGET_PATH}
60 61
      COMMAND cmake -E copy ${GLPK_BIN_DIR}/zlib1.dll ${TARGET_PATH}
61 62
    )
62 63
  ENDIF(WIN32 AND LEMON_HAVE_GLPK)
63 64
  IF(WIN32 AND LEMON_HAVE_CPLEX)
64 65
    GET_TARGET_PROPERTY(TARGET_LOC lp_test LOCATION)
65 66
    GET_FILENAME_COMPONENT(TARGET_PATH ${TARGET_LOC} PATH)
66 67
    ADD_CUSTOM_COMMAND(TARGET lp_test POST_BUILD
67 68
      COMMAND cmake -E copy ${CPLEX_BIN_DIR}/cplex91.dll ${TARGET_PATH}
68 69
    )
69 70
  ENDIF(WIN32 AND LEMON_HAVE_CPLEX)
70 71
ENDIF(LEMON_HAVE_LP)
71 72

	
72 73
IF(LEMON_HAVE_MIP)
73 74
  ADD_EXECUTABLE(mip_test mip_test.cc)
74 75
  SET(MIP_TEST_LIBS lemon)
75 76
  IF(LEMON_HAVE_GLPK)
76 77
    SET(MIP_TEST_LIBS ${MIP_TEST_LIBS} ${GLPK_LIBRARIES})
77 78
  ENDIF(LEMON_HAVE_GLPK)
78 79
  IF(LEMON_HAVE_CPLEX)
79 80
    SET(MIP_TEST_LIBS ${MIP_TEST_LIBS} ${CPLEX_LIBRARIES})
80 81
  ENDIF(LEMON_HAVE_CPLEX)
81 82
  IF(LEMON_HAVE_CBC)
82 83
    SET(MIP_TEST_LIBS ${MIP_TEST_LIBS} ${COIN_CBC_LIBRARIES})
83 84
  ENDIF(LEMON_HAVE_CBC)
84 85
  TARGET_LINK_LIBRARIES(mip_test ${MIP_TEST_LIBS})
85 86
  ADD_TEST(mip_test mip_test)
86 87

	
87 88
  IF(WIN32 AND LEMON_HAVE_GLPK)
88 89
    GET_TARGET_PROPERTY(TARGET_LOC mip_test LOCATION)
89 90
    GET_FILENAME_COMPONENT(TARGET_PATH ${TARGET_LOC} PATH)
90 91
    ADD_CUSTOM_COMMAND(TARGET mip_test POST_BUILD
91 92
      COMMAND cmake -E copy ${GLPK_BIN_DIR}/glpk.dll ${TARGET_PATH}
92 93
      COMMAND cmake -E copy ${GLPK_BIN_DIR}/libltdl3.dll ${TARGET_PATH}
93 94
      COMMAND cmake -E copy ${GLPK_BIN_DIR}/zlib1.dll ${TARGET_PATH}
94 95
    )
95 96
  ENDIF(WIN32 AND LEMON_HAVE_GLPK)
96 97
  IF(WIN32 AND LEMON_HAVE_CPLEX)
97 98
    GET_TARGET_PROPERTY(TARGET_LOC mip_test LOCATION)
98 99
    GET_FILENAME_COMPONENT(TARGET_PATH ${TARGET_LOC} PATH)
99 100
    ADD_CUSTOM_COMMAND(TARGET mip_test POST_BUILD
100 101
      COMMAND cmake -E copy ${CPLEX_BIN_DIR}/cplex91.dll ${TARGET_PATH}
101 102
    )
102 103
  ENDIF(WIN32 AND LEMON_HAVE_CPLEX)
103 104
ENDIF(LEMON_HAVE_MIP)
104 105

	
105 106
FOREACH(TEST_NAME ${TESTS})
106 107
  ADD_EXECUTABLE(${TEST_NAME} ${TEST_NAME}.cc)
107 108
  TARGET_LINK_LIBRARIES(${TEST_NAME} lemon)
108 109
  ADD_TEST(${TEST_NAME} ${TEST_NAME})
109 110
ENDFOREACH(TEST_NAME)
Ignore white space 6 line context
1 1
EXTRA_DIST += \
2 2
	test/CMakeLists.txt
3 3

	
4 4
noinst_HEADERS += \
5 5
	test/graph_test.h \
6 6
	test/test_tools.h
7 7

	
8 8
check_PROGRAMS += \
9 9
	test/adaptors_test \
10 10
	test/bfs_test \
11 11
	test/circulation_test \
12
	test/connectivity_test \
12 13
	test/counter_test \
13 14
	test/dfs_test \
14 15
	test/digraph_test \
15 16
	test/dijkstra_test \
16 17
	test/dim_test \
17 18
	test/edge_set_test \
18 19
	test/error_test \
19 20
	test/euler_test \
20 21
	test/gomory_hu_test \
21 22
	test/graph_copy_test \
22 23
	test/graph_test \
23 24
	test/graph_utils_test \
24 25
	test/hao_orlin_test \
25 26
	test/heap_test \
26 27
	test/kruskal_test \
27 28
	test/maps_test \
28 29
	test/matching_test \
29 30
	test/min_cost_arborescence_test \
30 31
	test/min_cost_flow_test \
31 32
	test/path_test \
32 33
	test/preflow_test \
33 34
	test/radix_sort_test \
34 35
	test/random_test \
35 36
	test/suurballe_test \
36 37
	test/test_tools_fail \
37 38
	test/test_tools_pass \
38 39
	test/time_measure_test \
39 40
	test/unionfind_test
40 41

	
41 42
test_test_tools_pass_DEPENDENCIES = demo
42 43

	
43 44
if HAVE_LP
44 45
check_PROGRAMS += test/lp_test
45 46
endif HAVE_LP
46 47
if HAVE_MIP
47 48
check_PROGRAMS += test/mip_test
48 49
endif HAVE_MIP
49 50

	
50 51
TESTS += $(check_PROGRAMS)
51 52
XFAIL_TESTS += test/test_tools_fail$(EXEEXT)
52 53

	
53 54
test_adaptors_test_SOURCES = test/adaptors_test.cc
54 55
test_bfs_test_SOURCES = test/bfs_test.cc
55 56
test_circulation_test_SOURCES = test/circulation_test.cc
56 57
test_counter_test_SOURCES = test/counter_test.cc
58
test_connectivity_test_SOURCES = test/connectivity_test.cc
57 59
test_dfs_test_SOURCES = test/dfs_test.cc
58 60
test_digraph_test_SOURCES = test/digraph_test.cc
59 61
test_dijkstra_test_SOURCES = test/dijkstra_test.cc
60 62
test_dim_test_SOURCES = test/dim_test.cc
61 63
test_edge_set_test_SOURCES = test/edge_set_test.cc
62 64
test_error_test_SOURCES = test/error_test.cc
63 65
test_euler_test_SOURCES = test/euler_test.cc
64 66
test_gomory_hu_test_SOURCES = test/gomory_hu_test.cc
65 67
test_graph_copy_test_SOURCES = test/graph_copy_test.cc
66 68
test_graph_test_SOURCES = test/graph_test.cc
67 69
test_graph_utils_test_SOURCES = test/graph_utils_test.cc
68 70
test_heap_test_SOURCES = test/heap_test.cc
69 71
test_kruskal_test_SOURCES = test/kruskal_test.cc
70 72
test_hao_orlin_test_SOURCES = test/hao_orlin_test.cc
71 73
test_lp_test_SOURCES = test/lp_test.cc
72 74
test_maps_test_SOURCES = test/maps_test.cc
73 75
test_mip_test_SOURCES = test/mip_test.cc
74 76
test_matching_test_SOURCES = test/matching_test.cc
75 77
test_min_cost_arborescence_test_SOURCES = test/min_cost_arborescence_test.cc
76 78
test_min_cost_flow_test_SOURCES = test/min_cost_flow_test.cc
77 79
test_path_test_SOURCES = test/path_test.cc
78 80
test_preflow_test_SOURCES = test/preflow_test.cc
79 81
test_radix_sort_test_SOURCES = test/radix_sort_test.cc
80 82
test_suurballe_test_SOURCES = test/suurballe_test.cc
81 83
test_random_test_SOURCES = test/random_test.cc
82 84
test_test_tools_fail_SOURCES = test/test_tools_fail.cc
83 85
test_test_tools_pass_SOURCES = test/test_tools_pass.cc
84 86
test_time_measure_test_SOURCES = test/time_measure_test.cc
85 87
test_unionfind_test_SOURCES = test/unionfind_test.cc
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#include <iostream>
20 20
#include <fstream>
21 21
#include <limits>
22 22

	
23 23
#include <lemon/list_graph.h>
24 24
#include <lemon/lgf_reader.h>
25 25

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

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

	
31 31
#include "test_tools.h"
32 32

	
33 33
using namespace lemon;
34 34

	
35 35
char test_lgf[] =
36 36
  "@nodes\n"
37 37
  "label  sup1 sup2 sup3 sup4 sup5 sup6\n"
38 38
  "    1    20   27    0   30   20   30\n"
39 39
  "    2    -4    0    0    0   -8   -3\n"
40 40
  "    3     0    0    0    0    0    0\n"
41 41
  "    4     0    0    0    0    0    0\n"
42 42
  "    5     9    0    0    0    6   11\n"
43 43
  "    6    -6    0    0    0   -5   -6\n"
44 44
  "    7     0    0    0    0    0    0\n"
45 45
  "    8     0    0    0    0    0    3\n"
46 46
  "    9     3    0    0    0    0    0\n"
47 47
  "   10    -2    0    0    0   -7   -2\n"
48 48
  "   11     0    0    0    0  -10    0\n"
49 49
  "   12   -20  -27    0  -30  -30  -20\n"
50 50
  "\n"                
51 51
  "@arcs\n"
52 52
  "       cost  cap low1 low2 low3\n"
53 53
  " 1  2    70   11    0    8    8\n"
54 54
  " 1  3   150    3    0    1    0\n"
55 55
  " 1  4    80   15    0    2    2\n"
56 56
  " 2  8    80   12    0    0    0\n"
57 57
  " 3  5   140    5    0    3    1\n"
58 58
  " 4  6    60   10    0    1    0\n"
59 59
  " 4  7    80    2    0    0    0\n"
60 60
  " 4  8   110    3    0    0    0\n"
61 61
  " 5  7    60   14    0    0    0\n"
62 62
  " 5 11   120   12    0    0    0\n"
63 63
  " 6  3     0    3    0    0    0\n"
64 64
  " 6  9   140    4    0    0    0\n"
65 65
  " 6 10    90    8    0    0    0\n"
66 66
  " 7  1    30    5    0    0   -5\n"
67 67
  " 8 12    60   16    0    4    3\n"
68 68
  " 9 12    50    6    0    0    0\n"
69 69
  "10 12    70   13    0    5    2\n"
70 70
  "10  2   100    7    0    0    0\n"
71 71
  "10  7    60   10    0    0   -3\n"
72 72
  "11 10    20   14    0    6  -20\n"
73 73
  "12 11    30   10    0    0  -10\n"
74 74
  "\n"
75 75
  "@attributes\n"
76 76
  "source 1\n"
77 77
  "target 12\n";
78 78

	
79 79

	
80 80
enum SupplyType {
81 81
  EQ,
82 82
  GEQ,
83 83
  LEQ
84 84
};
85 85

	
86 86
// Check the interface of an MCF algorithm
87 87
template <typename GR, typename Value, typename Cost>
88 88
class McfClassConcept
89 89
{
90 90
public:
91 91

	
92 92
  template <typename MCF>
93 93
  struct Constraints {
94 94
    void constraints() {
95 95
      checkConcept<concepts::Digraph, GR>();
96 96

	
97 97
      MCF mcf(g);
98 98
      const MCF& const_mcf = mcf;
99 99

	
100 100
      b = mcf.reset()
101 101
             .lowerMap(lower)
102 102
             .upperMap(upper)
103 103
             .costMap(cost)
104 104
             .supplyMap(sup)
105 105
             .stSupply(n, n, k)
106 106
             .run();
107 107

	
108 108
      c = const_mcf.totalCost();
109 109
      x = const_mcf.template totalCost<double>();
110 110
      v = const_mcf.flow(a);
111 111
      c = const_mcf.potential(n);
112 112
      const_mcf.flowMap(fm);
113 113
      const_mcf.potentialMap(pm);
114 114
    }
115 115

	
116 116
    typedef typename GR::Node Node;
117 117
    typedef typename GR::Arc Arc;
118 118
    typedef concepts::ReadMap<Node, Value> NM;
119 119
    typedef concepts::ReadMap<Arc, Value> VAM;
120 120
    typedef concepts::ReadMap<Arc, Cost> CAM;
121 121
    typedef concepts::WriteMap<Arc, Value> FlowMap;
122 122
    typedef concepts::WriteMap<Node, Cost> PotMap;
123 123

	
124 124
    const GR &g;
125 125
    const VAM &lower;
126 126
    const VAM &upper;
127 127
    const CAM &cost;
128 128
    const NM &sup;
129 129
    const Node &n;
130 130
    const Arc &a;
131 131
    const Value &k;
132 132
    FlowMap fm;
133 133
    PotMap pm;
134 134
    bool b;
135 135
    double x;
136 136
    typename MCF::Value v;
137 137
    typename MCF::Cost c;
138 138
  };
139 139

	
140 140
};
141 141

	
142 142

	
143 143
// Check the feasibility of the given flow (primal soluiton)
144 144
template < typename GR, typename LM, typename UM,
145 145
           typename SM, typename FM >
146 146
bool checkFlow( const GR& gr, const LM& lower, const UM& upper,
147 147
                const SM& supply, const FM& flow,
148 148
                SupplyType type = EQ )
149 149
{
150 150
  TEMPLATE_DIGRAPH_TYPEDEFS(GR);
151 151

	
152 152
  for (ArcIt e(gr); e != INVALID; ++e) {
153 153
    if (flow[e] < lower[e] || flow[e] > upper[e]) return false;
154 154
  }
155 155

	
156 156
  for (NodeIt n(gr); n != INVALID; ++n) {
157 157
    typename SM::Value sum = 0;
158 158
    for (OutArcIt e(gr, n); e != INVALID; ++e)
159 159
      sum += flow[e];
160 160
    for (InArcIt e(gr, n); e != INVALID; ++e)
161 161
      sum -= flow[e];
162 162
    bool b = (type ==  EQ && sum == supply[n]) ||
163 163
             (type == GEQ && sum >= supply[n]) ||
164 164
             (type == LEQ && sum <= supply[n]);
165 165
    if (!b) return false;
166 166
  }
167 167

	
168 168
  return true;
169 169
}
170 170

	
171 171
// Check the feasibility of the given potentials (dual soluiton)
172 172
// using the "Complementary Slackness" optimality condition
173 173
template < typename GR, typename LM, typename UM,
174 174
           typename CM, typename SM, typename FM, typename PM >
175 175
bool checkPotential( const GR& gr, const LM& lower, const UM& upper,
176 176
                     const CM& cost, const SM& supply, const FM& flow, 
177
                     const PM& pi )
177
                     const PM& pi, SupplyType type )
178 178
{
179 179
  TEMPLATE_DIGRAPH_TYPEDEFS(GR);
180 180

	
181 181
  bool opt = true;
182 182
  for (ArcIt e(gr); opt && e != INVALID; ++e) {
183 183
    typename CM::Value red_cost =
184 184
      cost[e] + pi[gr.source(e)] - pi[gr.target(e)];
185 185
    opt = red_cost == 0 ||
186 186
          (red_cost > 0 && flow[e] == lower[e]) ||
187 187
          (red_cost < 0 && flow[e] == upper[e]);
188 188
  }
189 189
  
190 190
  for (NodeIt n(gr); opt && n != INVALID; ++n) {
191 191
    typename SM::Value sum = 0;
192 192
    for (OutArcIt e(gr, n); e != INVALID; ++e)
193 193
      sum += flow[e];
194 194
    for (InArcIt e(gr, n); e != INVALID; ++e)
195 195
      sum -= flow[e];
196
    opt = (sum == supply[n]) || (pi[n] == 0);
196
    if (type != LEQ) {
197
      opt = (pi[n] <= 0) && (sum == supply[n] || pi[n] == 0);
198
    } else {
199
      opt = (pi[n] >= 0) && (sum == supply[n] || pi[n] == 0);
200
    }
197 201
  }
198 202
  
199 203
  return opt;
200 204
}
201 205

	
206
// Check whether the dual cost is equal to the primal cost
207
template < typename GR, typename LM, typename UM,
208
           typename CM, typename SM, typename PM >
209
bool checkDualCost( const GR& gr, const LM& lower, const UM& upper,
210
                    const CM& cost, const SM& supply, const PM& pi,
211
                    typename CM::Value total )
212
{
213
  TEMPLATE_DIGRAPH_TYPEDEFS(GR);
214

	
215
  typename CM::Value dual_cost = 0;
216
  SM red_supply(gr);
217
  for (NodeIt n(gr); n != INVALID; ++n) {
218
    red_supply[n] = supply[n];
219
  }
220
  for (ArcIt a(gr); a != INVALID; ++a) {
221
    if (lower[a] != 0) {
222
      dual_cost += lower[a] * cost[a];
223
      red_supply[gr.source(a)] -= lower[a];
224
      red_supply[gr.target(a)] += lower[a];
225
    }
226
  }
227
  
228
  for (NodeIt n(gr); n != INVALID; ++n) {
229
    dual_cost -= red_supply[n] * pi[n];
230
  }
231
  for (ArcIt a(gr); a != INVALID; ++a) {
232
    typename CM::Value red_cost =
233
      cost[a] + pi[gr.source(a)] - pi[gr.target(a)];
234
    dual_cost -= (upper[a] - lower[a]) * std::max(-red_cost, 0);
235
  }
236
  
237
  return dual_cost == total;
238
}
239

	
202 240
// Run a minimum cost flow algorithm and check the results
203 241
template < typename MCF, typename GR,
204 242
           typename LM, typename UM,
205 243
           typename CM, typename SM,
206 244
           typename PT >
207 245
void checkMcf( const MCF& mcf, PT mcf_result,
208 246
               const GR& gr, const LM& lower, const UM& upper,
209 247
               const CM& cost, const SM& supply,
210 248
               PT result, bool optimal, typename CM::Value total,
211 249
               const std::string &test_id = "",
212 250
               SupplyType type = EQ )
213 251
{
214 252
  check(mcf_result == result, "Wrong result " + test_id);
215 253
  if (optimal) {
216 254
    typename GR::template ArcMap<typename SM::Value> flow(gr);
217 255
    typename GR::template NodeMap<typename CM::Value> pi(gr);
218 256
    mcf.flowMap(flow);
219 257
    mcf.potentialMap(pi);
220 258
    check(checkFlow(gr, lower, upper, supply, flow, type),
221 259
          "The flow is not feasible " + test_id);
222 260
    check(mcf.totalCost() == total, "The flow is not optimal " + test_id);
223
    check(checkPotential(gr, lower, upper, cost, supply, flow, pi),
261
    check(checkPotential(gr, lower, upper, cost, supply, flow, pi, type),
224 262
          "Wrong potentials " + test_id);
263
    check(checkDualCost(gr, lower, upper, cost, supply, pi, total),
264
          "Wrong dual cost " + test_id);
225 265
  }
226 266
}
227 267

	
228 268
int main()
229 269
{
230 270
  // Check the interfaces
231 271
  {
232 272
    typedef concepts::Digraph GR;
233 273
    checkConcept< McfClassConcept<GR, int, int>,
234 274
                  NetworkSimplex<GR> >();
235 275
    checkConcept< McfClassConcept<GR, double, double>,
236 276
                  NetworkSimplex<GR, double> >();
237 277
    checkConcept< McfClassConcept<GR, int, double>,
238 278
                  NetworkSimplex<GR, int, double> >();
239 279
  }
240 280

	
241 281
  // Run various MCF tests
242 282
  typedef ListDigraph Digraph;
243 283
  DIGRAPH_TYPEDEFS(ListDigraph);
244 284

	
245 285
  // Read the test digraph
246 286
  Digraph gr;
247 287
  Digraph::ArcMap<int> c(gr), l1(gr), l2(gr), l3(gr), u(gr);
248 288
  Digraph::NodeMap<int> s1(gr), s2(gr), s3(gr), s4(gr), s5(gr), s6(gr);
249 289
  ConstMap<Arc, int> cc(1), cu(std::numeric_limits<int>::max());
250 290
  Node v, w;
251 291

	
252 292
  std::istringstream input(test_lgf);
253 293
  DigraphReader<Digraph>(gr, input)
254 294
    .arcMap("cost", c)
255 295
    .arcMap("cap", u)
256 296
    .arcMap("low1", l1)
257 297
    .arcMap("low2", l2)
258 298
    .arcMap("low3", l3)
259 299
    .nodeMap("sup1", s1)
260 300
    .nodeMap("sup2", s2)
261 301
    .nodeMap("sup3", s3)
262 302
    .nodeMap("sup4", s4)
263 303
    .nodeMap("sup5", s5)
264 304
    .nodeMap("sup6", s6)
265 305
    .node("source", v)
266 306
    .node("target", w)
267 307
    .run();
268 308
  
269
  // Build a test digraph for testing negative costs
270
  Digraph ngr;
271
  Node n1 = ngr.addNode();
272
  Node n2 = ngr.addNode();
273
  Node n3 = ngr.addNode();
274
  Node n4 = ngr.addNode();
275
  Node n5 = ngr.addNode();
276
  Node n6 = ngr.addNode();
277
  Node n7 = ngr.addNode();
309
  // Build test digraphs with negative costs
310
  Digraph neg_gr;
311
  Node n1 = neg_gr.addNode();
312
  Node n2 = neg_gr.addNode();
313
  Node n3 = neg_gr.addNode();
314
  Node n4 = neg_gr.addNode();
315
  Node n5 = neg_gr.addNode();
316
  Node n6 = neg_gr.addNode();
317
  Node n7 = neg_gr.addNode();
278 318
  
279
  Arc a1 = ngr.addArc(n1, n2);
280
  Arc a2 = ngr.addArc(n1, n3);
281
  Arc a3 = ngr.addArc(n2, n4);
282
  Arc a4 = ngr.addArc(n3, n4);
283
  Arc a5 = ngr.addArc(n3, n2);
284
  Arc a6 = ngr.addArc(n5, n3);
285
  Arc a7 = ngr.addArc(n5, n6);
286
  Arc a8 = ngr.addArc(n6, n7);
287
  Arc a9 = ngr.addArc(n7, n5);
319
  Arc a1 = neg_gr.addArc(n1, n2);
320
  Arc a2 = neg_gr.addArc(n1, n3);
321
  Arc a3 = neg_gr.addArc(n2, n4);
322
  Arc a4 = neg_gr.addArc(n3, n4);
323
  Arc a5 = neg_gr.addArc(n3, n2);
324
  Arc a6 = neg_gr.addArc(n5, n3);
325
  Arc a7 = neg_gr.addArc(n5, n6);
326
  Arc a8 = neg_gr.addArc(n6, n7);
327
  Arc a9 = neg_gr.addArc(n7, n5);
288 328
  
289
  Digraph::ArcMap<int> nc(ngr), nl1(ngr, 0), nl2(ngr, 0);
290
  ConstMap<Arc, int> nu1(std::numeric_limits<int>::max()), nu2(5000);
291
  Digraph::NodeMap<int> ns(ngr, 0);
329
  Digraph::ArcMap<int> neg_c(neg_gr), neg_l1(neg_gr, 0), neg_l2(neg_gr, 0);
330
  ConstMap<Arc, int> neg_u1(std::numeric_limits<int>::max()), neg_u2(5000);
331
  Digraph::NodeMap<int> neg_s(neg_gr, 0);
292 332
  
293
  nl2[a7] =  1000;
294
  nl2[a8] = -1000;
333
  neg_l2[a7] =  1000;
334
  neg_l2[a8] = -1000;
295 335
  
296
  ns[n1] =  100;
297
  ns[n4] = -100;
336
  neg_s[n1] =  100;
337
  neg_s[n4] = -100;
298 338
  
299
  nc[a1] =  100;
300
  nc[a2] =   30;
301
  nc[a3] =   20;
302
  nc[a4] =   80;
303
  nc[a5] =   50;
304
  nc[a6] =   10;
305
  nc[a7] =   80;
306
  nc[a8] =   30;
307
  nc[a9] = -120;
339
  neg_c[a1] =  100;
340
  neg_c[a2] =   30;
341
  neg_c[a3] =   20;
342
  neg_c[a4] =   80;
343
  neg_c[a5] =   50;
344
  neg_c[a6] =   10;
345
  neg_c[a7] =   80;
346
  neg_c[a8] =   30;
347
  neg_c[a9] = -120;
348

	
349
  Digraph negs_gr;
350
  Digraph::NodeMap<int> negs_s(negs_gr);
351
  Digraph::ArcMap<int> negs_c(negs_gr);
352
  ConstMap<Arc, int> negs_l(0), negs_u(1000);
353
  n1 = negs_gr.addNode();
354
  n2 = negs_gr.addNode();
355
  negs_s[n1] = 100;
356
  negs_s[n2] = -300;
357
  negs_c[negs_gr.addArc(n1, n2)] = -1;
358

	
308 359

	
309 360
  // A. Test NetworkSimplex with the default pivot rule
310 361
  {
311 362
    NetworkSimplex<Digraph> mcf(gr);
312 363

	
313 364
    // Check the equality form
314 365
    mcf.upperMap(u).costMap(c);
315 366
    checkMcf(mcf, mcf.supplyMap(s1).run(),
316 367
             gr, l1, u, c, s1, mcf.OPTIMAL, true,   5240, "#A1");
317 368
    checkMcf(mcf, mcf.stSupply(v, w, 27).run(),
318 369
             gr, l1, u, c, s2, mcf.OPTIMAL, true,   7620, "#A2");
319 370
    mcf.lowerMap(l2);
320 371
    checkMcf(mcf, mcf.supplyMap(s1).run(),
321 372
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#A3");
322 373
    checkMcf(mcf, mcf.stSupply(v, w, 27).run(),
323 374
             gr, l2, u, c, s2, mcf.OPTIMAL, true,   8010, "#A4");
324 375
    mcf.reset();
325 376
    checkMcf(mcf, mcf.supplyMap(s1).run(),
326 377
             gr, l1, cu, cc, s1, mcf.OPTIMAL, true,   74, "#A5");
327 378
    checkMcf(mcf, mcf.lowerMap(l2).stSupply(v, w, 27).run(),
328 379
             gr, l2, cu, cc, s2, mcf.OPTIMAL, true,   94, "#A6");
329 380
    mcf.reset();
330 381
    checkMcf(mcf, mcf.run(),
331 382
             gr, l1, cu, cc, s3, mcf.OPTIMAL, true,    0, "#A7");
332 383
    checkMcf(mcf, mcf.lowerMap(l2).upperMap(u).run(),
333 384
             gr, l2, u, cc, s3, mcf.INFEASIBLE, false, 0, "#A8");
334 385
    mcf.reset().lowerMap(l3).upperMap(u).costMap(c).supplyMap(s4);
335 386
    checkMcf(mcf, mcf.run(),
336 387
             gr, l3, u, c, s4, mcf.OPTIMAL, true,   6360, "#A9");
337 388

	
338 389
    // Check the GEQ form
339 390
    mcf.reset().upperMap(u).costMap(c).supplyMap(s5);
340 391
    checkMcf(mcf, mcf.run(),
341 392
             gr, l1, u, c, s5, mcf.OPTIMAL, true,   3530, "#A10", GEQ);
342 393
    mcf.supplyType(mcf.GEQ);
343 394
    checkMcf(mcf, mcf.lowerMap(l2).run(),
344 395
             gr, l2, u, c, s5, mcf.OPTIMAL, true,   4540, "#A11", GEQ);
345
    mcf.supplyType(mcf.CARRY_SUPPLIES).supplyMap(s6);
396
    mcf.supplyMap(s6);
346 397
    checkMcf(mcf, mcf.run(),
347 398
             gr, l2, u, c, s6, mcf.INFEASIBLE, false,  0, "#A12", GEQ);
348 399

	
349 400
    // Check the LEQ form
350 401
    mcf.reset().supplyType(mcf.LEQ);
351 402
    mcf.upperMap(u).costMap(c).supplyMap(s6);
352 403
    checkMcf(mcf, mcf.run(),
353 404
             gr, l1, u, c, s6, mcf.OPTIMAL, true,   5080, "#A13", LEQ);
354 405
    checkMcf(mcf, mcf.lowerMap(l2).run(),
355 406
             gr, l2, u, c, s6, mcf.OPTIMAL, true,   5930, "#A14", LEQ);
356
    mcf.supplyType(mcf.SATISFY_DEMANDS).supplyMap(s5);
407
    mcf.supplyMap(s5);
357 408
    checkMcf(mcf, mcf.run(),
358 409
             gr, l2, u, c, s5, mcf.INFEASIBLE, false,  0, "#A15", LEQ);
359 410

	
360 411
    // Check negative costs
361
    NetworkSimplex<Digraph> nmcf(ngr);
362
    nmcf.lowerMap(nl1).costMap(nc).supplyMap(ns);
363
    checkMcf(nmcf, nmcf.run(),
364
      ngr, nl1, nu1, nc, ns, nmcf.UNBOUNDED, false,    0, "#A16");
365
    checkMcf(nmcf, nmcf.upperMap(nu2).run(),
366
      ngr, nl1, nu2, nc, ns, nmcf.OPTIMAL, true,  -40000, "#A17");
367
    nmcf.reset().lowerMap(nl2).costMap(nc).supplyMap(ns);
368
    checkMcf(nmcf, nmcf.run(),
369
      ngr, nl2, nu1, nc, ns, nmcf.UNBOUNDED, false,    0, "#A18");
412
    NetworkSimplex<Digraph> neg_mcf(neg_gr);
413
    neg_mcf.lowerMap(neg_l1).costMap(neg_c).supplyMap(neg_s);
414
    checkMcf(neg_mcf, neg_mcf.run(), neg_gr, neg_l1, neg_u1,
415
      neg_c, neg_s, neg_mcf.UNBOUNDED, false,    0, "#A16");
416
    neg_mcf.upperMap(neg_u2);
417
    checkMcf(neg_mcf, neg_mcf.run(), neg_gr, neg_l1, neg_u2,
418
      neg_c, neg_s, neg_mcf.OPTIMAL, true,  -40000, "#A17");
419
    neg_mcf.reset().lowerMap(neg_l2).costMap(neg_c).supplyMap(neg_s);
420
    checkMcf(neg_mcf, neg_mcf.run(), neg_gr, neg_l2, neg_u1,
421
      neg_c, neg_s, neg_mcf.UNBOUNDED, false,    0, "#A18");
422
      
423
    NetworkSimplex<Digraph> negs_mcf(negs_gr);
424
    negs_mcf.costMap(negs_c).supplyMap(negs_s);
425
    checkMcf(negs_mcf, negs_mcf.run(), negs_gr, negs_l, negs_u,
426
      negs_c, negs_s, negs_mcf.OPTIMAL, true, -300, "#A19", GEQ);
370 427
  }
371 428

	
372 429
  // B. Test NetworkSimplex with each pivot rule
373 430
  {
374 431
    NetworkSimplex<Digraph> mcf(gr);
375 432
    mcf.supplyMap(s1).costMap(c).upperMap(u).lowerMap(l2);
376 433

	
377 434
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::FIRST_ELIGIBLE),
378 435
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B1");
379 436
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::BEST_ELIGIBLE),
380 437
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B2");
381 438
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::BLOCK_SEARCH),
382 439
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B3");
383 440
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::CANDIDATE_LIST),
384 441
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B4");
385 442
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::ALTERING_LIST),
386 443
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B5");
387 444
  }
388 445

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

	
19 19
/// \ingroup tools
20 20
/// \file
21
/// \brief Special plane digraph generator.
21
/// \brief Special plane graph generator.
22 22
///
23 23
/// Graph generator application for various types of plane graphs.
24 24
///
25 25
/// See
26 26
/// \code
27 27
///   lgf-gen --help
28 28
/// \endcode
29
/// for more info on the usage.
29
/// for more information on the usage.
30 30

	
31 31
#include <algorithm>
32 32
#include <set>
33 33
#include <ctime>
34 34
#include <lemon/list_graph.h>
35 35
#include <lemon/random.h>
36 36
#include <lemon/dim2.h>
37 37
#include <lemon/bfs.h>
38 38
#include <lemon/counter.h>
39 39
#include <lemon/suurballe.h>
40 40
#include <lemon/graph_to_eps.h>
41 41
#include <lemon/lgf_writer.h>
42 42
#include <lemon/arg_parser.h>
43 43
#include <lemon/euler.h>
44 44
#include <lemon/math.h>
45 45
#include <lemon/kruskal.h>
46 46
#include <lemon/time_measure.h>
47 47

	
48 48
using namespace lemon;
49 49

	
50 50
typedef dim2::Point<double> Point;
51 51

	
52 52
GRAPH_TYPEDEFS(ListGraph);
53 53

	
54 54
bool progress=true;
55 55

	
56 56
int N;
57 57
// int girth;
58 58

	
59 59
ListGraph g;
60 60

	
61 61
std::vector<Node> nodes;
62 62
ListGraph::NodeMap<Point> coords(g);
63 63

	
64 64

	
65 65
double totalLen(){
66 66
  double tlen=0;
67 67
  for(EdgeIt e(g);e!=INVALID;++e)
68 68
    tlen+=std::sqrt((coords[g.v(e)]-coords[g.u(e)]).normSquare());
69 69
  return tlen;
70 70
}
71 71

	
72 72
int tsp_impr_num=0;
73 73

	
74 74
const double EPSILON=1e-8;
75 75
bool tsp_improve(Node u, Node v)
76 76
{
77 77
  double luv=std::sqrt((coords[v]-coords[u]).normSquare());
78 78
  Node u2=u;
79 79
  Node v2=v;
80 80
  do {
81 81
    Node n;
82 82
    for(IncEdgeIt e(g,v2);(n=g.runningNode(e))==u2;++e) { }
83 83
    u2=v2;
84 84
    v2=n;
85 85
    if(luv+std::sqrt((coords[v2]-coords[u2]).normSquare())-EPSILON>
86 86
       std::sqrt((coords[u]-coords[u2]).normSquare())+
87 87
       std::sqrt((coords[v]-coords[v2]).normSquare()))
88 88
      {
89 89
         g.erase(findEdge(g,u,v));
90 90
         g.erase(findEdge(g,u2,v2));
91 91
        g.addEdge(u2,u);
92 92
        g.addEdge(v,v2);
93 93
        tsp_impr_num++;
94 94
        return true;
95 95
      }
96 96
  } while(v2!=u);
97 97
  return false;
98 98
}
99 99

	
100 100
bool tsp_improve(Node u)
101 101
{
102 102
  for(IncEdgeIt e(g,u);e!=INVALID;++e)
103 103
    if(tsp_improve(u,g.runningNode(e))) return true;
104 104
  return false;
105 105
}
106 106

	
107 107
void tsp_improve()
108 108
{
109 109
  bool b;
110 110
  do {
111 111
    b=false;
112 112
    for(NodeIt n(g);n!=INVALID;++n)
113 113
      if(tsp_improve(n)) b=true;
114 114
  } while(b);
115 115
}
116 116

	
117 117
void tsp()
118 118
{
119 119
  for(int i=0;i<N;i++) g.addEdge(nodes[i],nodes[(i+1)%N]);
120 120
  tsp_improve();
121 121
}
122 122

	
123 123
class Line
124 124
{
125 125
public:
126 126
  Point a;
127 127
  Point b;
128 128
  Line(Point _a,Point _b) :a(_a),b(_b) {}
129 129
  Line(Node _a,Node _b) : a(coords[_a]),b(coords[_b]) {}
130 130
  Line(const Arc &e) : a(coords[g.source(e)]),b(coords[g.target(e)]) {}
131 131
  Line(const Edge &e) : a(coords[g.u(e)]),b(coords[g.v(e)]) {}
132 132
};
133 133

	
134 134
inline std::ostream& operator<<(std::ostream &os, const Line &l)
135 135
{
136 136
  os << l.a << "->" << l.b;
137 137
  return os;
138 138
}
139 139

	
140 140
bool cross(Line a, Line b)
141 141
{
142 142
  Point ao=rot90(a.b-a.a);
143 143
  Point bo=rot90(b.b-b.a);
144 144
  return (ao*(b.a-a.a))*(ao*(b.b-a.a))<0 &&
145 145
    (bo*(a.a-b.a))*(bo*(a.b-b.a))<0;
146 146
}
147 147

	
148 148
struct Parc
149 149
{
150 150
  Node a;
151 151
  Node b;
152 152
  double len;
153 153
};
154 154

	
155 155
bool pedgeLess(Parc a,Parc b)
156 156
{
157 157
  return a.len<b.len;
158 158
}
159 159

	
160 160
std::vector<Edge> arcs;
161 161

	
162 162
namespace _delaunay_bits {
163 163

	
164 164
  struct Part {
165 165
    int prev, curr, next;
166 166

	
167 167
    Part(int p, int c, int n) : prev(p), curr(c), next(n) {}
168 168
  };
169 169

	
170 170
  inline std::ostream& operator<<(std::ostream& os, const Part& part) {
171 171
    os << '(' << part.prev << ',' << part.curr << ',' << part.next << ')';
172 172
    return os;
173 173
  }
174 174

	
175 175
  inline double circle_point(const Point& p, const Point& q, const Point& r) {
176 176
    double a = p.x * (q.y - r.y) + q.x * (r.y - p.y) + r.x * (p.y - q.y);
177 177
    if (a == 0) return std::numeric_limits<double>::quiet_NaN();
178 178

	
179 179
    double d = (p.x * p.x + p.y * p.y) * (q.y - r.y) +
180 180
      (q.x * q.x + q.y * q.y) * (r.y - p.y) +
181 181
      (r.x * r.x + r.y * r.y) * (p.y - q.y);
182 182

	
183 183
    double e = (p.x * p.x + p.y * p.y) * (q.x - r.x) +
184 184
      (q.x * q.x + q.y * q.y) * (r.x - p.x) +
185 185
      (r.x * r.x + r.y * r.y) * (p.x - q.x);
186 186

	
187 187
    double f = (p.x * p.x + p.y * p.y) * (q.x * r.y - r.x * q.y) +
188 188
      (q.x * q.x + q.y * q.y) * (r.x * p.y - p.x * r.y) +
189 189
      (r.x * r.x + r.y * r.y) * (p.x * q.y - q.x * p.y);
190 190

	
191 191
    return d / (2 * a) + std::sqrt((d * d + e * e) / (4 * a * a) + f / a);
192 192
  }
193 193

	
194 194
  inline bool circle_form(const Point& p, const Point& q, const Point& r) {
195 195
    return rot90(q - p) * (r - q) < 0.0;
196 196
  }
197 197

	
198 198
  inline double intersection(const Point& p, const Point& q, double sx) {
199 199
    const double epsilon = 1e-8;
200 200

	
201 201
    if (p.x == q.x) return (p.y + q.y) / 2.0;
202 202

	
203 203
    if (sx < p.x + epsilon) return p.y;
204 204
    if (sx < q.x + epsilon) return q.y;
205 205

	
206 206
    double a = q.x - p.x;
207 207
    double b = (q.x - sx) * p.y - (p.x - sx) * q.y;
208 208
    double d = (q.x - sx) * (p.x - sx) * (p - q).normSquare();
209 209
    return (b - std::sqrt(d)) / a;
210 210
  }
211 211

	
212 212
  struct YLess {
213 213

	
214 214

	
215 215
    YLess(const std::vector<Point>& points, double& sweep)
216 216
      : _points(points), _sweep(sweep) {}
217 217

	
218 218
    bool operator()(const Part& l, const Part& r) const {
219 219
      const double epsilon = 1e-8;
220 220

	
221 221
      //      std::cerr << l << " vs " << r << std::endl;
222 222
      double lbx = l.prev != -1 ?
223 223
        intersection(_points[l.prev], _points[l.curr], _sweep) :
224 224
        - std::numeric_limits<double>::infinity();
225 225
      double rbx = r.prev != -1 ?
226 226
        intersection(_points[r.prev], _points[r.curr], _sweep) :
227 227
        - std::numeric_limits<double>::infinity();
228 228
      double lex = l.next != -1 ?
229 229
        intersection(_points[l.curr], _points[l.next], _sweep) :
230 230
        std::numeric_limits<double>::infinity();
231 231
      double rex = r.next != -1 ?
232 232
        intersection(_points[r.curr], _points[r.next], _sweep) :
233 233
        std::numeric_limits<double>::infinity();
234 234

	
235 235
      if (lbx > lex) std::swap(lbx, lex);
236 236
      if (rbx > rex) std::swap(rbx, rex);
237 237

	
238 238
      if (lex < epsilon + rex && lbx + epsilon < rex) return true;
239 239
      if (rex < epsilon + lex && rbx + epsilon < lex) return false;
240 240
      return lex < rex;
241 241
    }
242 242

	
243 243
    const std::vector<Point>& _points;
244 244
    double& _sweep;
245 245
  };
246 246

	
247 247
  struct BeachIt;
248 248

	
249 249
  typedef std::multimap<double, BeachIt> SpikeHeap;
250 250

	
251 251
  typedef std::multimap<Part, SpikeHeap::iterator, YLess> Beach;
252 252

	
253 253
  struct BeachIt {
254 254
    Beach::iterator it;
255 255

	
256 256
    BeachIt(Beach::iterator iter) : it(iter) {}
257 257
  };
258 258

	
259 259
}
260 260

	
261 261
inline void delaunay() {
262 262
  Counter cnt("Number of arcs added: ");
263 263

	
264 264
  using namespace _delaunay_bits;
265 265

	
266 266
  typedef _delaunay_bits::Part Part;
267 267
  typedef std::vector<std::pair<double, int> > SiteHeap;
268 268

	
269 269

	
270 270
  std::vector<Point> points;
271 271
  std::vector<Node> nodes;
272 272

	
273 273
  for (NodeIt it(g); it != INVALID; ++it) {
274 274
    nodes.push_back(it);
275 275
    points.push_back(coords[it]);
276 276
  }
277 277

	
278 278
  SiteHeap siteheap(points.size());
279 279

	
280 280
  double sweep;
281 281

	
282 282

	
283 283
  for (int i = 0; i < int(siteheap.size()); ++i) {
284 284
    siteheap[i] = std::make_pair(points[i].x, i);
285 285
  }
286 286

	
287 287
  std::sort(siteheap.begin(), siteheap.end());
288 288
  sweep = siteheap.front().first;
289 289

	
290 290
  YLess yless(points, sweep);
291 291
  Beach beach(yless);
292 292

	
293 293
  SpikeHeap spikeheap;
294 294

	
295 295
  std::set<std::pair<int, int> > arcs;
296 296

	
297 297
  int siteindex = 0;
298 298
  {
299 299
    SiteHeap front;
300 300

	
301 301
    while (siteindex < int(siteheap.size()) &&
302 302
           siteheap[0].first == siteheap[siteindex].first) {
303 303
      front.push_back(std::make_pair(points[siteheap[siteindex].second].y,
304 304
                                     siteheap[siteindex].second));
305 305
      ++siteindex;
306 306
    }
307 307

	
308 308
    std::sort(front.begin(), front.end());
309 309

	
310 310
    for (int i = 0; i < int(front.size()); ++i) {
311 311
      int prev = (i == 0 ? -1 : front[i - 1].second);
312 312
      int curr = front[i].second;
313 313
      int next = (i + 1 == int(front.size()) ? -1 : front[i + 1].second);
314 314

	
315 315
      beach.insert(std::make_pair(Part(prev, curr, next),
316 316
                                  spikeheap.end()));
317 317
    }
318 318
  }
319 319

	
320 320
  while (siteindex < int(points.size()) || !spikeheap.empty()) {
321 321

	
322 322
    SpikeHeap::iterator spit = spikeheap.begin();
323 323

	
324 324
    if (siteindex < int(points.size()) &&
325 325
        (spit == spikeheap.end() || siteheap[siteindex].first < spit->first)) {
326 326
      int site = siteheap[siteindex].second;
327 327
      sweep = siteheap[siteindex].first;
328 328

	
329 329
      Beach::iterator bit = beach.upper_bound(Part(site, site, site));
330 330

	
331 331
      if (bit->second != spikeheap.end()) {
332 332
        spikeheap.erase(bit->second);
333 333
      }
334 334

	
335 335
      int prev = bit->first.prev;
336 336
      int curr = bit->first.curr;
337 337
      int next = bit->first.next;
338 338

	
339 339
      beach.erase(bit);
340 340

	
341 341
      SpikeHeap::iterator pit = spikeheap.end();
342 342
      if (prev != -1 &&
343 343
          circle_form(points[prev], points[curr], points[site])) {
344 344
        double x = circle_point(points[prev], points[curr], points[site]);
345 345
        pit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
346 346
        pit->second.it =
347 347
          beach.insert(std::make_pair(Part(prev, curr, site), pit));
348 348
      } else {
349 349
        beach.insert(std::make_pair(Part(prev, curr, site), pit));
350 350
      }
351 351

	
352 352
      beach.insert(std::make_pair(Part(curr, site, curr), spikeheap.end()));
353 353

	
354 354
      SpikeHeap::iterator nit = spikeheap.end();
355 355
      if (next != -1 &&
356 356
          circle_form(points[site], points[curr],points[next])) {
357 357
        double x = circle_point(points[site], points[curr], points[next]);
358 358
        nit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
359 359
        nit->second.it =
360 360
          beach.insert(std::make_pair(Part(site, curr, next), nit));
361 361
      } else {
362 362
        beach.insert(std::make_pair(Part(site, curr, next), nit));
363 363
      }
364 364

	
365 365
      ++siteindex;
366 366
    } else {
367 367
      sweep = spit->first;
368 368

	
369 369
      Beach::iterator bit = spit->second.it;
370 370

	
371 371
      int prev = bit->first.prev;
372 372
      int curr = bit->first.curr;
373 373
      int next = bit->first.next;
374 374

	
375 375
      {
376 376
        std::pair<int, int> arc;
377 377

	
378 378
        arc = prev < curr ?
379 379
          std::make_pair(prev, curr) : std::make_pair(curr, prev);
380 380

	
381 381
        if (arcs.find(arc) == arcs.end()) {
382 382
          arcs.insert(arc);
383 383
          g.addEdge(nodes[prev], nodes[curr]);
384 384
          ++cnt;
385 385
        }
386 386

	
387 387
        arc = curr < next ?
388 388
          std::make_pair(curr, next) : std::make_pair(next, curr);
389 389

	
390 390
        if (arcs.find(arc) == arcs.end()) {
391 391
          arcs.insert(arc);
392 392
          g.addEdge(nodes[curr], nodes[next]);
393 393
          ++cnt;
394 394
        }
395 395
      }
396 396

	
397 397
      Beach::iterator pbit = bit; --pbit;
398 398
      int ppv = pbit->first.prev;
399 399
      Beach::iterator nbit = bit; ++nbit;
400 400
      int nnt = nbit->first.next;
401 401

	
402 402
      if (bit->second != spikeheap.end()) spikeheap.erase(bit->second);
403 403
      if (pbit->second != spikeheap.end()) spikeheap.erase(pbit->second);
404 404
      if (nbit->second != spikeheap.end()) spikeheap.erase(nbit->second);
405 405

	
406 406
      beach.erase(nbit);
407 407
      beach.erase(bit);
408 408
      beach.erase(pbit);
409 409

	
410 410
      SpikeHeap::iterator pit = spikeheap.end();
411 411
      if (ppv != -1 && ppv != next &&
412 412
          circle_form(points[ppv], points[prev], points[next])) {
413 413
        double x = circle_point(points[ppv], points[prev], points[next]);
414 414
        if (x < sweep) x = sweep;
415 415
        pit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
416 416
        pit->second.it =
417 417
          beach.insert(std::make_pair(Part(ppv, prev, next), pit));
418 418
      } else {
419 419
        beach.insert(std::make_pair(Part(ppv, prev, next), pit));
420 420
      }
421 421

	
422 422
      SpikeHeap::iterator nit = spikeheap.end();
423 423
      if (nnt != -1 && prev != nnt &&
424 424
          circle_form(points[prev], points[next], points[nnt])) {
425 425
        double x = circle_point(points[prev], points[next], points[nnt]);
426 426
        if (x < sweep) x = sweep;
427 427
        nit = spikeheap.insert(std::make_pair(x, BeachIt(beach.end())));
428 428
        nit->second.it =
429 429
          beach.insert(std::make_pair(Part(prev, next, nnt), nit));
430 430
      } else {
431 431
        beach.insert(std::make_pair(Part(prev, next, nnt), nit));
432 432
      }
433 433

	
434 434
    }
435 435
  }
436 436

	
437 437
  for (Beach::iterator it = beach.begin(); it != beach.end(); ++it) {
438 438
    int curr = it->first.curr;
439 439
    int next = it->first.next;
440 440

	
441 441
    if (next == -1) continue;
442 442

	
443 443
    std::pair<int, int> arc;
444 444

	
445 445
    arc = curr < next ?
446 446
      std::make_pair(curr, next) : std::make_pair(next, curr);
447 447

	
448 448
    if (arcs.find(arc) == arcs.end()) {
449 449
      arcs.insert(arc);
450 450
      g.addEdge(nodes[curr], nodes[next]);
451 451
      ++cnt;
452 452
    }
453 453
  }
454 454
}
455 455

	
456 456
void sparse(int d)
457 457
{
458 458
  Counter cnt("Number of arcs removed: ");
459 459
  Bfs<ListGraph> bfs(g);
460 460
  for(std::vector<Edge>::reverse_iterator ei=arcs.rbegin();
461 461
      ei!=arcs.rend();++ei)
462 462
    {
463 463
      Node a=g.u(*ei);
464 464
      Node b=g.v(*ei);
465 465
      g.erase(*ei);
466 466
      bfs.run(a,b);
467 467
      if(bfs.predArc(b)==INVALID || bfs.dist(b)>d)
468 468
        g.addEdge(a,b);
469 469
      else cnt++;
470 470
    }
471 471
}
472 472

	
473 473
void sparse2(int d)
474 474
{
475 475
  Counter cnt("Number of arcs removed: ");
476 476
  for(std::vector<Edge>::reverse_iterator ei=arcs.rbegin();
477 477
      ei!=arcs.rend();++ei)
478 478
    {
479 479
      Node a=g.u(*ei);
480 480
      Node b=g.v(*ei);
481 481
      g.erase(*ei);
482 482
      ConstMap<Arc,int> cegy(1);
483 483
      Suurballe<ListGraph,ConstMap<Arc,int> > sur(g,cegy);
484 484
      int k=sur.run(a,b,2);
485 485
      if(k<2 || sur.totalLength()>d)
486 486
        g.addEdge(a,b);
487 487
      else cnt++;
488 488
//       else std::cout << "Remove arc " << g.id(a) << "-" << g.id(b) << '\n';
489 489
    }
490 490
}
491 491

	
492 492
void sparseTriangle(int d)
493 493
{
494 494
  Counter cnt("Number of arcs added: ");
495 495
  std::vector<Parc> pedges;
496 496
  for(NodeIt n(g);n!=INVALID;++n)
497 497
    for(NodeIt m=++(NodeIt(n));m!=INVALID;++m)
498 498
      {
499 499
        Parc p;
500 500
        p.a=n;
501 501
        p.b=m;
502 502
        p.len=(coords[m]-coords[n]).normSquare();
503 503
        pedges.push_back(p);
504 504
      }
505 505
  std::sort(pedges.begin(),pedges.end(),pedgeLess);
506 506
  for(std::vector<Parc>::iterator pi=pedges.begin();pi!=pedges.end();++pi)
507 507
    {
508 508
      Line li(pi->a,pi->b);
509 509
      EdgeIt e(g);
510 510
      for(;e!=INVALID && !cross(e,li);++e) ;
511 511
      Edge ne;
512 512
      if(e==INVALID) {
513 513
        ConstMap<Arc,int> cegy(1);
514 514
        Suurballe<ListGraph,ConstMap<Arc,int> > sur(g,cegy);
515 515
        int k=sur.run(pi->a,pi->b,2);
516 516
        if(k<2 || sur.totalLength()>d)
517 517
          {
518 518
            ne=g.addEdge(pi->a,pi->b);
519 519
            arcs.push_back(ne);
520 520
            cnt++;
521 521
          }
522 522
      }
523 523
    }
524 524
}
525 525

	
526 526
template <typename Graph, typename CoordMap>
527 527
class LengthSquareMap {
528 528
public:
529 529
  typedef typename Graph::Edge Key;
530 530
  typedef typename CoordMap::Value::Value Value;
531 531

	
532 532
  LengthSquareMap(const Graph& graph, const CoordMap& coords)
533 533
    : _graph(graph), _coords(coords) {}
534 534

	
535 535
  Value operator[](const Key& key) const {
536 536
    return (_coords[_graph.v(key)] -
537 537
            _coords[_graph.u(key)]).normSquare();
538 538
  }
539 539

	
540 540
private:
541 541

	
542 542
  const Graph& _graph;
543 543
  const CoordMap& _coords;
544 544
};
545 545

	
546 546
void minTree() {
547 547
  std::vector<Parc> pedges;
548 548
  Timer T;
549 549
  std::cout << T.realTime() << "s: Creating delaunay triangulation...\n";
550 550
  delaunay();
551 551
  std::cout << T.realTime() << "s: Calculating spanning tree...\n";
552 552
  LengthSquareMap<ListGraph, ListGraph::NodeMap<Point> > ls(g, coords);
553 553
  ListGraph::EdgeMap<bool> tree(g);
554 554
  kruskal(g, ls, tree);
555 555
  std::cout << T.realTime() << "s: Removing non tree arcs...\n";
556 556
  std::vector<Edge> remove;
557 557
  for (EdgeIt e(g); e != INVALID; ++e) {
558 558
    if (!tree[e]) remove.push_back(e);
559 559
  }
560 560
  for(int i = 0; i < int(remove.size()); ++i) {
561 561
    g.erase(remove[i]);
562 562
  }
563 563
  std::cout << T.realTime() << "s: Done\n";
564 564
}
565 565

	
566 566
void tsp2()
567 567
{
568 568
  std::cout << "Find a tree..." << std::endl;
569 569

	
570 570
  minTree();
571 571

	
572 572
  std::cout << "Total arc length (tree) : " << totalLen() << std::endl;
573 573

	
574 574
  std::cout << "Make it Euler..." << std::endl;
575 575

	
576 576
  {
577 577
    std::vector<Node> leafs;
578 578
    for(NodeIt n(g);n!=INVALID;++n)
579 579
      if(countIncEdges(g,n)%2==1) leafs.push_back(n);
580 580

	
581 581
//    for(unsigned int i=0;i<leafs.size();i+=2)
582 582
//       g.addArc(leafs[i],leafs[i+1]);
583 583

	
584 584
    std::vector<Parc> pedges;
585 585
    for(unsigned int i=0;i<leafs.size()-1;i++)
586 586
      for(unsigned int j=i+1;j<leafs.size();j++)
587 587
        {
588 588
          Node n=leafs[i];
589 589
          Node m=leafs[j];
590 590
          Parc p;
591 591
          p.a=n;
592 592
          p.b=m;
593 593
          p.len=(coords[m]-coords[n]).normSquare();
594 594
          pedges.push_back(p);
595 595
        }
596 596
    std::sort(pedges.begin(),pedges.end(),pedgeLess);
597 597
    for(unsigned int i=0;i<pedges.size();i++)
598 598
      if(countIncEdges(g,pedges[i].a)%2 &&
599 599
         countIncEdges(g,pedges[i].b)%2)
600 600
        g.addEdge(pedges[i].a,pedges[i].b);
601 601
  }
602 602

	
603 603
  for(NodeIt n(g);n!=INVALID;++n)
604 604
    if(countIncEdges(g,n)%2 || countIncEdges(g,n)==0 )
605 605
      std::cout << "GEBASZ!!!" << std::endl;
606 606

	
607 607
  for(EdgeIt e(g);e!=INVALID;++e)
608 608
    if(g.u(e)==g.v(e))
609 609
      std::cout << "LOOP GEBASZ!!!" << std::endl;
610 610

	
611 611
  std::cout << "Number of arcs : " << countEdges(g) << std::endl;
612 612

	
613 613
  std::cout << "Total arc length (euler) : " << totalLen() << std::endl;
614 614

	
615 615
  ListGraph::EdgeMap<Arc> enext(g);
616 616
  {
617 617
    EulerIt<ListGraph> e(g);
618 618
    Arc eo=e;
619 619
    Arc ef=e;
620 620
//     std::cout << "Tour arc: " << g.id(Edge(e)) << std::endl;
621 621
    for(++e;e!=INVALID;++e)
622 622
      {
623 623
//         std::cout << "Tour arc: " << g.id(Edge(e)) << std::endl;
624 624
        enext[eo]=e;
625 625
        eo=e;
626 626
      }
627 627
    enext[eo]=ef;
628 628
  }
629 629

	
630 630
  std::cout << "Creating a tour from that..." << std::endl;
631 631

	
632 632
  int nnum = countNodes(g);
633 633
  int ednum = countEdges(g);
634 634

	
635 635
  for(Arc p=enext[EdgeIt(g)];ednum>nnum;p=enext[p])
636 636
    {
637 637
//       std::cout << "Checking arc " << g.id(p) << std::endl;
638 638
      Arc e=enext[p];
639 639
      Arc f=enext[e];
640 640
      Node n2=g.source(f);
641 641
      Node n1=g.oppositeNode(n2,e);
642 642
      Node n3=g.oppositeNode(n2,f);
643 643
      if(countIncEdges(g,n2)>2)
644 644
        {
645 645
//           std::cout << "Remove an Arc" << std::endl;
646 646
          Arc ff=enext[f];
647 647
          g.erase(e);
648 648
          g.erase(f);
649 649
          if(n1!=n3)
650 650
            {
651 651
              Arc ne=g.direct(g.addEdge(n1,n3),n1);
652 652
              enext[p]=ne;
653 653
              enext[ne]=ff;
654 654
              ednum--;
655 655
            }
656 656
          else {
657 657
            enext[p]=ff;
658 658
            ednum-=2;
659 659
          }
660 660
        }
661 661
    }
662 662

	
663 663
  std::cout << "Total arc length (tour) : " << totalLen() << std::endl;
664 664

	
665 665
  std::cout << "2-opt the tour..." << std::endl;
666 666

	
667 667
  tsp_improve();
668 668

	
669 669
  std::cout << "Total arc length (2-opt tour) : " << totalLen() << std::endl;
670 670
}
671 671

	
672 672

	
673 673
int main(int argc,const char **argv)
674 674
{
675 675
  ArgParser ap(argc,argv);
676 676

	
677 677
//   bool eps;
678 678
  bool disc_d, square_d, gauss_d;
679 679
//   bool tsp_a,two_a,tree_a;
680 680
  int num_of_cities=1;
681 681
  double area=1;
682 682
  N=100;
683 683
//   girth=10;
684 684
  std::string ndist("disc");
685 685
  ap.refOption("n", "Number of nodes (default is 100)", N)
686 686
    .intOption("g", "Girth parameter (default is 10)", 10)
687 687
    .refOption("cities", "Number of cities (default is 1)", num_of_cities)
688 688
    .refOption("area", "Full relative area of the cities (default is 1)", area)
689
    .refOption("disc", "Nodes are evenly distributed on a unit disc (default)",disc_d)
689
    .refOption("disc", "Nodes are evenly distributed on a unit disc (default)",
690
               disc_d)
690 691
    .optionGroup("dist", "disc")
691
    .refOption("square", "Nodes are evenly distributed on a unit square", square_d)
692
    .refOption("square", "Nodes are evenly distributed on a unit square",
693
               square_d)
692 694
    .optionGroup("dist", "square")
693
    .refOption("gauss",
694
            "Nodes are located according to a two-dim gauss distribution",
695
            gauss_d)
695
    .refOption("gauss", "Nodes are located according to a two-dim Gauss "
696
               "distribution", gauss_d)
696 697
    .optionGroup("dist", "gauss")
697
//     .mandatoryGroup("dist")
698 698
    .onlyOneGroup("dist")
699
    .boolOption("eps", "Also generate .eps output (prefix.eps)")
700
    .boolOption("nonodes", "Draw the edges only in the generated .eps")
701
    .boolOption("dir", "Directed digraph is generated (each arcs are replaced by two directed ones)")
702
    .boolOption("2con", "Create a two connected planar digraph")
699
    .boolOption("eps", "Also generate .eps output (<prefix>.eps)")
700
    .boolOption("nonodes", "Draw only the edges in the generated .eps output")
701
    .boolOption("dir", "Directed graph is generated (each edge is replaced by "
702
                "two directed arcs)")
703
    .boolOption("2con", "Create a two connected planar graph")
703 704
    .optionGroup("alg","2con")
704 705
    .boolOption("tree", "Create a min. cost spanning tree")
705 706
    .optionGroup("alg","tree")
706 707
    .boolOption("tsp", "Create a TSP tour")
707 708
    .optionGroup("alg","tsp")
708 709
    .boolOption("tsp2", "Create a TSP tour (tree based)")
709 710
    .optionGroup("alg","tsp2")
710
    .boolOption("dela", "Delaunay triangulation digraph")
711
    .boolOption("dela", "Delaunay triangulation graph")
711 712
    .optionGroup("alg","dela")
712 713
    .onlyOneGroup("alg")
713 714
    .boolOption("rand", "Use time seed for random number generator")
714 715
    .optionGroup("rand", "rand")
715 716
    .intOption("seed", "Random seed", -1)
716 717
    .optionGroup("rand", "seed")
717 718
    .onlyOneGroup("rand")
718 719
    .other("[prefix]","Prefix of the output files. Default is 'lgf-gen-out'")
719 720
    .run();
720 721

	
721 722
  if (ap["rand"]) {
722 723
    int seed = int(time(0));
723 724
    std::cout << "Random number seed: " << seed << std::endl;
724 725
    rnd = Random(seed);
725 726
  }
726 727
  if (ap.given("seed")) {
727 728
    int seed = ap["seed"];
728 729
    std::cout << "Random number seed: " << seed << std::endl;
729 730
    rnd = Random(seed);
730 731
  }
731 732

	
732 733
  std::string prefix;
733 734
  switch(ap.files().size())
734 735
    {
735 736
    case 0:
736 737
      prefix="lgf-gen-out";
737 738
      break;
738 739
    case 1:
739 740
      prefix=ap.files()[0];
740 741
      break;
741 742
    default:
742 743
      std::cerr << "\nAt most one prefix can be given\n\n";
743 744
      exit(1);
744 745
    }
745 746

	
746 747
  double sum_sizes=0;
747 748
  std::vector<double> sizes;
748 749
  std::vector<double> cum_sizes;
749 750
  for(int s=0;s<num_of_cities;s++)
750 751
    {
751 752
      //         sum_sizes+=rnd.exponential();
752 753
      double d=rnd();
753 754
      sum_sizes+=d;
754 755
      sizes.push_back(d);
755 756
      cum_sizes.push_back(sum_sizes);
756 757
    }
757 758
  int i=0;
758 759
  for(int s=0;s<num_of_cities;s++)
759 760
    {
760 761
      Point center=(num_of_cities==1?Point(0,0):rnd.disc());
761 762
      if(gauss_d)
762 763
        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
763 764
          Node n=g.addNode();
764 765
          nodes.push_back(n);
765 766
          coords[n]=center+rnd.gauss2()*area*
766 767
            std::sqrt(sizes[s]/sum_sizes);
767 768
        }
768 769
      else if(square_d)
769 770
        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
770 771
          Node n=g.addNode();
771 772
          nodes.push_back(n);
772 773
          coords[n]=center+Point(rnd()*2-1,rnd()*2-1)*area*
773 774
            std::sqrt(sizes[s]/sum_sizes);
774 775
        }
775 776
      else if(disc_d || true)
776 777
        for(;i<N*(cum_sizes[s]/sum_sizes);i++) {
777 778
          Node n=g.addNode();
778 779
          nodes.push_back(n);
779 780
          coords[n]=center+rnd.disc()*area*
780 781
            std::sqrt(sizes[s]/sum_sizes);
781 782
        }
782 783
    }
783 784

	
784 785
//   for (ListGraph::NodeIt n(g); n != INVALID; ++n) {
785 786
//     std::cerr << coords[n] << std::endl;
786 787
//   }
787 788

	
788 789
  if(ap["tsp"]) {
789 790
    tsp();
790 791
    std::cout << "#2-opt improvements: " << tsp_impr_num << std::endl;
791 792
  }
792 793
  if(ap["tsp2"]) {
793 794
    tsp2();
794 795
    std::cout << "#2-opt improvements: " << tsp_impr_num << std::endl;
795 796
  }
796 797
  else if(ap["2con"]) {
797 798
    std::cout << "Make triangles\n";
798 799
    //   triangle();
799 800
    sparseTriangle(ap["g"]);
800 801
    std::cout << "Make it sparser\n";
801 802
    sparse2(ap["g"]);
802 803
  }
803 804
  else if(ap["tree"]) {
804 805
    minTree();
805 806
  }
806 807
  else if(ap["dela"]) {
807 808
    delaunay();
808 809
  }
809 810

	
810 811

	
811 812
  std::cout << "Number of nodes    : " << countNodes(g) << std::endl;
812 813
  std::cout << "Number of arcs    : " << countEdges(g) << std::endl;
813 814
  double tlen=0;
814 815
  for(EdgeIt e(g);e!=INVALID;++e)
815 816
    tlen+=std::sqrt((coords[g.v(e)]-coords[g.u(e)]).normSquare());
816 817
  std::cout << "Total arc length  : " << tlen << std::endl;
817 818

	
818 819
  if(ap["eps"])
819 820
    graphToEps(g,prefix+".eps").scaleToA4().
820 821
      scale(600).nodeScale(.005).arcWidthScale(.001).preScale(false).
821 822
      coords(coords).hideNodes(ap.given("nonodes")).run();
822 823

	
823 824
  if(ap["dir"])
824 825
    DigraphWriter<ListGraph>(g,prefix+".lgf").
825 826
      nodeMap("coordinates_x",scaleMap(xMap(coords),600)).
826 827
      nodeMap("coordinates_y",scaleMap(yMap(coords),600)).
827 828
      run();
828 829
  else GraphWriter<ListGraph>(g,prefix+".lgf").
829 830
         nodeMap("coordinates_x",scaleMap(xMap(coords),600)).
830 831
         nodeMap("coordinates_y",scaleMap(yMap(coords),600)).
831 832
         run();
832 833
}
833 834

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

	
19
#ifndef LEMON_BITS_BASE_EXTENDER_H
20
#define LEMON_BITS_BASE_EXTENDER_H
21

	
22
#include <lemon/core.h>
23
#include <lemon/error.h>
24

	
25
#include <lemon/bits/map_extender.h>
26
#include <lemon/bits/default_map.h>
27

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

	
31
//\ingroup digraphbits
32
//\file
33
//\brief Extenders for the graph types
34
namespace lemon {
35

	
36
  // \ingroup digraphbits
37
  //
38
  // \brief BaseDigraph to BaseGraph extender
39
  template <typename Base>
40
  class UndirDigraphExtender : public Base {
41
    typedef Base Parent;
42

	
43
  public:
44

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

	
48
    typedef True UndirectedTag;
49

	
50
    class Arc : public Edge {
51
      friend class UndirDigraphExtender;
52

	
53
    protected:
54
      bool forward;
55

	
56
      Arc(const Edge &ue, bool _forward) :
57
        Edge(ue), forward(_forward) {}
58

	
59
    public:
60
      Arc() {}
61

	
62
      // Invalid arc constructor
63
      Arc(Invalid i) : Edge(i), forward(true) {}
64

	
65
      bool operator==(const Arc &that) const {
66
        return forward==that.forward && Edge(*this)==Edge(that);
67
      }
68
      bool operator!=(const Arc &that) const {
69
        return forward!=that.forward || Edge(*this)!=Edge(that);
70
      }
71
      bool operator<(const Arc &that) const {
72
        return forward<that.forward ||
73
          (!(that.forward<forward) && Edge(*this)<Edge(that));
74
      }
75
    };
76

	
77
    // First node of the edge
78
    Node u(const Edge &e) const {
79
      return Parent::source(e);
80
    }
81

	
82
    // Source of the given arc
83
    Node source(const Arc &e) const {
84
      return e.forward ? Parent::source(e) : Parent::target(e);
85
    }
86

	
87
    // Second node of the edge
88
    Node v(const Edge &e) const {
89
      return Parent::target(e);
90
    }
91

	
92
    // Target of the given arc
93
    Node target(const Arc &e) const {
94
      return e.forward ? Parent::target(e) : Parent::source(e);
95
    }
96

	
97
    // \brief Directed arc from an edge.
98
    //
99
    // Returns a directed arc corresponding to the specified edge.
100
    // If the given bool is true, the first node of the given edge and
101
    // the source node of the returned arc are the same.
102
    static Arc direct(const Edge &e, bool d) {
103
      return Arc(e, d);
104
    }
105

	
106
    // Returns whether the given directed arc has the same orientation
107
    // as the corresponding edge.
108
    static bool direction(const Arc &a) { return a.forward; }
109

	
110
    using Parent::first;
111
    using Parent::next;
112

	
113
    void first(Arc &e) const {
114
      Parent::first(e);
115
      e.forward=true;
116
    }
117

	
118
    void next(Arc &e) const {
119
      if( e.forward ) {
120
        e.forward = false;
121
      }
122
      else {
123
        Parent::next(e);
124
        e.forward = true;
125
      }
126
    }
127

	
128
    void firstOut(Arc &e, const Node &n) const {
129
      Parent::firstIn(e,n);
130
      if( Edge(e) != INVALID ) {
131
        e.forward = false;
132
      }
133
      else {
134
        Parent::firstOut(e,n);
135
        e.forward = true;
136
      }
137
    }
138
    void nextOut(Arc &e) const {
139
      if( ! e.forward ) {
140
        Node n = Parent::target(e);
141
        Parent::nextIn(e);
142
        if( Edge(e) == INVALID ) {
143
          Parent::firstOut(e, n);
144
          e.forward = true;
145
        }
146
      }
147
      else {
148
        Parent::nextOut(e);
149
      }
150
    }
151

	
152
    void firstIn(Arc &e, const Node &n) const {
153
      Parent::firstOut(e,n);
154
      if( Edge(e) != INVALID ) {
155
        e.forward = false;
156
      }
157
      else {
158
        Parent::firstIn(e,n);
159
        e.forward = true;
160
      }
161
    }
162
    void nextIn(Arc &e) const {
163
      if( ! e.forward ) {
164
        Node n = Parent::source(e);
165
        Parent::nextOut(e);
166
        if( Edge(e) == INVALID ) {
167
          Parent::firstIn(e, n);
168
          e.forward = true;
169
        }
170
      }
171
      else {
172
        Parent::nextIn(e);
173
      }
174
    }
175

	
176
    void firstInc(Edge &e, bool &d, const Node &n) const {
177
      d = true;
178
      Parent::firstOut(e, n);
179
      if (e != INVALID) return;
180
      d = false;
181
      Parent::firstIn(e, n);
182
    }
183

	
184
    void nextInc(Edge &e, bool &d) const {
185
      if (d) {
186
        Node s = Parent::source(e);
187
        Parent::nextOut(e);
188
        if (e != INVALID) return;
189
        d = false;
190
        Parent::firstIn(e, s);
191
      } else {
192
        Parent::nextIn(e);
193
      }
194
    }
195

	
196
    Node nodeFromId(int ix) const {
197
      return Parent::nodeFromId(ix);
198
    }
199

	
200
    Arc arcFromId(int ix) const {
201
      return direct(Parent::arcFromId(ix >> 1), bool(ix & 1));
202
    }
203

	
204
    Edge edgeFromId(int ix) const {
205
      return Parent::arcFromId(ix);
206
    }
207

	
208
    int id(const Node &n) const {
209
      return Parent::id(n);
210
    }
211

	
212
    int id(const Edge &e) const {
213
      return Parent::id(e);
214
    }
215

	
216
    int id(const Arc &e) const {
217
      return 2 * Parent::id(e) + int(e.forward);
218
    }
219

	
220
    int maxNodeId() const {
221
      return Parent::maxNodeId();
222
    }
223

	
224
    int maxArcId() const {
225
      return 2 * Parent::maxArcId() + 1;
226
    }
227

	
228
    int maxEdgeId() const {
229
      return Parent::maxArcId();
230
    }
231

	
232
    int arcNum() const {
233
      return 2 * Parent::arcNum();
234
    }
235

	
236
    int edgeNum() const {
237
      return Parent::arcNum();
238
    }
239

	
240
    Arc findArc(Node s, Node t, Arc p = INVALID) const {
241
      if (p == INVALID) {
242
        Edge arc = Parent::findArc(s, t);
243
        if (arc != INVALID) return direct(arc, true);
244
        arc = Parent::findArc(t, s);
245
        if (arc != INVALID) return direct(arc, false);
246
      } else if (direction(p)) {
247
        Edge arc = Parent::findArc(s, t, p);
248
        if (arc != INVALID) return direct(arc, true);
249
        arc = Parent::findArc(t, s);
250
        if (arc != INVALID) return direct(arc, false);
251
      } else {
252
        Edge arc = Parent::findArc(t, s, p);
253
        if (arc != INVALID) return direct(arc, false);
254
      }
255
      return INVALID;
256
    }
257

	
258
    Edge findEdge(Node s, Node t, Edge p = INVALID) const {
259
      if (s != t) {
260
        if (p == INVALID) {
261
          Edge arc = Parent::findArc(s, t);
262
          if (arc != INVALID) return arc;
263
          arc = Parent::findArc(t, s);
264
          if (arc != INVALID) return arc;
265
        } else if (Parent::s(p) == s) {
266
          Edge arc = Parent::findArc(s, t, p);
267
          if (arc != INVALID) return arc;
268
          arc = Parent::findArc(t, s);
269
          if (arc != INVALID) return arc;
270
        } else {
271
          Edge arc = Parent::findArc(t, s, p);
272
          if (arc != INVALID) return arc;
273
        }
274
      } else {
275
        return Parent::findArc(s, t, p);
276
      }
277
      return INVALID;
278
    }
279
  };
280

	
281
  template <typename Base>
282
  class BidirBpGraphExtender : public Base {
283
    typedef Base Parent;
284

	
285
  public:
286
    typedef BidirBpGraphExtender Digraph;
287

	
288
    typedef typename Parent::Node Node;
289
    typedef typename Parent::Edge Edge;
290

	
291

	
292
    using Parent::first;
293
    using Parent::next;
294

	
295
    using Parent::id;
296

	
297
    class Red : public Node {
298
      friend class BidirBpGraphExtender;
299
    public:
300
      Red() {}
301
      Red(const Node& node) : Node(node) {
302
        LEMON_DEBUG(Parent::red(node) || node == INVALID,
303
                    typename Parent::NodeSetError());
304
      }
305
      Red& operator=(const Node& node) {
306
        LEMON_DEBUG(Parent::red(node) || node == INVALID,
307
                    typename Parent::NodeSetError());
308
        Node::operator=(node);
309
        return *this;
310
      }
311
      Red(Invalid) : Node(INVALID) {}
312
      Red& operator=(Invalid) {
313
        Node::operator=(INVALID);
314
        return *this;
315
      }
316
    };
317

	
318
    void first(Red& node) const {
319
      Parent::firstRed(static_cast<Node&>(node));
320
    }
321
    void next(Red& node) const {
322
      Parent::nextRed(static_cast<Node&>(node));
323
    }
324

	
325
    int id(const Red& node) const {
326
      return Parent::redId(node);
327
    }
328

	
329
    class Blue : public Node {
330
      friend class BidirBpGraphExtender;
331
    public:
332
      Blue() {}
333
      Blue(const Node& node) : Node(node) {
334
        LEMON_DEBUG(Parent::blue(node) || node == INVALID,
335
                    typename Parent::NodeSetError());
336
      }
337
      Blue& operator=(const Node& node) {
338
        LEMON_DEBUG(Parent::blue(node) || node == INVALID,
339
                    typename Parent::NodeSetError());
340
        Node::operator=(node);
341
        return *this;
342
      }
343
      Blue(Invalid) : Node(INVALID) {}
344
      Blue& operator=(Invalid) {
345
        Node::operator=(INVALID);
346
        return *this;
347
      }
348
    };
349

	
350
    void first(Blue& node) const {
351
      Parent::firstBlue(static_cast<Node&>(node));
352
    }
353
    void next(Blue& node) const {
354
      Parent::nextBlue(static_cast<Node&>(node));
355
    }
356

	
357
    int id(const Blue& node) const {
358
      return Parent::redId(node);
359
    }
360

	
361
    Node source(const Edge& arc) const {
362
      return red(arc);
363
    }
364
    Node target(const Edge& arc) const {
365
      return blue(arc);
366
    }
367

	
368
    void firstInc(Edge& arc, bool& dir, const Node& node) const {
369
      if (Parent::red(node)) {
370
        Parent::firstFromRed(arc, node);
371
        dir = true;
372
      } else {
373
        Parent::firstFromBlue(arc, node);
374
        dir = static_cast<Edge&>(arc) == INVALID;
375
      }
376
    }
377
    void nextInc(Edge& arc, bool& dir) const {
378
      if (dir) {
379
        Parent::nextFromRed(arc);
380
      } else {
381
        Parent::nextFromBlue(arc);
382
        if (arc == INVALID) dir = true;
383
      }
384
    }
385

	
386
    class Arc : public Edge {
387
      friend class BidirBpGraphExtender;
388
    protected:
389
      bool forward;
390

	
391
      Arc(const Edge& arc, bool _forward)
392
        : Edge(arc), forward(_forward) {}
393

	
394
    public:
395
      Arc() {}
396
      Arc (Invalid) : Edge(INVALID), forward(true) {}
397
      bool operator==(const Arc& i) const {
398
        return Edge::operator==(i) && forward == i.forward;
399
      }
400
      bool operator!=(const Arc& i) const {
401
        return Edge::operator!=(i) || forward != i.forward;
402
      }
403
      bool operator<(const Arc& i) const {
404
        return Edge::operator<(i) ||
405
          (!(i.forward<forward) && Edge(*this)<Edge(i));
406
      }
407
    };
408

	
409
    void first(Arc& arc) const {
410
      Parent::first(static_cast<Edge&>(arc));
411
      arc.forward = true;
412
    }
413

	
414
    void next(Arc& arc) const {
415
      if (!arc.forward) {
416
        Parent::next(static_cast<Edge&>(arc));
417
      }
418
      arc.forward = !arc.forward;
419
    }
420

	
421
    void firstOut(Arc& arc, const Node& node) const {
422
      if (Parent::red(node)) {
423
        Parent::firstFromRed(arc, node);
424
        arc.forward = true;
425
      } else {
426
        Parent::firstFromBlue(arc, node);
427
        arc.forward = static_cast<Edge&>(arc) == INVALID;
428
      }
429
    }
430
    void nextOut(Arc& arc) const {
431
      if (arc.forward) {
432
        Parent::nextFromRed(arc);
433
      } else {
434
        Parent::nextFromBlue(arc);
435
        arc.forward = static_cast<Edge&>(arc) == INVALID;
436
      }
437
    }
438

	
439
    void firstIn(Arc& arc, const Node& node) const {
440
      if (Parent::blue(node)) {
441
        Parent::firstFromBlue(arc, node);
442
        arc.forward = true;
443
      } else {
444
        Parent::firstFromRed(arc, node);
445
        arc.forward = static_cast<Edge&>(arc) == INVALID;
446
      }
447
    }
448
    void nextIn(Arc& arc) const {
449
      if (arc.forward) {
450
        Parent::nextFromBlue(arc);
451
      } else {
452
        Parent::nextFromRed(arc);
453
        arc.forward = static_cast<Edge&>(arc) == INVALID;
454
      }
455
    }
456

	
457
    Node source(const Arc& arc) const {
458
      return arc.forward ? Parent::red(arc) : Parent::blue(arc);
459
    }
460
    Node target(const Arc& arc) const {
461
      return arc.forward ? Parent::blue(arc) : Parent::red(arc);
462
    }
463

	
464
    int id(const Arc& arc) const {
465
      return (Parent::id(static_cast<const Edge&>(arc)) << 1) +
466
        (arc.forward ? 0 : 1);
467
    }
468
    Arc arcFromId(int ix) const {
469
      return Arc(Parent::fromEdgeId(ix >> 1), (ix & 1) == 0);
470
    }
471
    int maxArcId() const {
472
      return (Parent::maxEdgeId() << 1) + 1;
473
    }
474

	
475
    bool direction(const Arc& arc) const {
476
      return arc.forward;
477
    }
478

	
479
    Arc direct(const Edge& arc, bool dir) const {
480
      return Arc(arc, dir);
481
    }
482

	
483
    int arcNum() const {
484
      return 2 * Parent::edgeNum();
485
    }
486

	
487
    int edgeNum() const {
488
      return Parent::edgeNum();
489
    }
490

	
491

	
492
  };
493
}
494

	
495
#endif
0 comments (0 inline)