↑ 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}")
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
Ignore white space 96 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 6 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
Ignore white space 6 line context
... ...
@@ -93,106 +93,96 @@
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 {
... ...
@@ -270,264 +260,193 @@
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
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
... ...
@@ -66,69 +66,68 @@
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
... ...
@@ -1794,242 +1794,239 @@
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);
Ignore white space 6 line context
... ...
@@ -265,135 +265,137 @@
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.
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

	
... ...
@@ -186,337 +205,354 @@
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)]) {
... ...
@@ -661,203 +697,219 @@
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
      }
... ...
@@ -986,602 +1038,628 @@
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>;
... ...
@@ -185,97 +185,97 @@
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);
... ...
@@ -609,97 +609,97 @@
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() {
... ...
@@ -868,97 +868,97 @@
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();
... ...
@@ -1212,97 +1212,97 @@
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();
Ignore white space 6 line context
... ...
@@ -199,89 +199,89 @@
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

	
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
... ...
@@ -454,116 +454,116 @@
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
    }
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;
... ...
@@ -1024,143 +995,235 @@
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]) {
... ...
@@ -1329,86 +1392,98 @@
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
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}
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
... ...
@@ -129,262 +129,319 @@
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());
... ...
@@ -641,118 +641,119 @@
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++)
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)