gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Support negative costs and bounds in NetworkSimplex (#270) * The interface is reworked to support negative costs and bounds. - ProblemType and problemType() are renamed to SupplyType and supplyType(), see also #234. - ProblemType type is introduced similarly to the LP interface. - 'bool run()' is replaced by 'ProblemType run()' to handle unbounded problem instances, as well. - Add INF public member constant similarly to the LP interface. * Remove capacityMap() and boundMaps(), see also #266. * Update the problem definition in the MCF module. * Remove the usage of Circulation (and adaptors) for checking feasibility. Check feasibility by examining the artifical arcs instead (after solving the problem). * Additional check for unbounded negative cycles found during the algorithm (it is possible now, since negative costs are allowed). * Fix in the constructor (the value types needn't be integer any more), see also #254. * Improve and extend the doc. * Rework the test file and add test cases for negative costs and bounds.
0 4 0
default
4 files changed with 350 insertions and 332 deletions:
↑ Collapse diff ↑
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
namespace lemon {
20 20

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	
238 238
/**
239 239
@defgroup matrices Matrices
240 240
@ingroup datas
241 241
\brief Two dimensional data storages implemented in LEMON.
242 242

	
243 243
This group contains two dimensional data storages implemented in LEMON.
244 244
*/
245 245

	
246 246
/**
247 247
@defgroup paths Path Structures
248 248
@ingroup datas
249 249
\brief %Path structures implemented in LEMON.
250 250

	
251 251
This group contains the path structures implemented in LEMON.
252 252

	
253 253
LEMON provides flexible data structures to work with paths.
254 254
All of them have similar interfaces and they can be copied easily with
255 255
assignment operators and copy constructors. This makes it easy and
256 256
efficient to have e.g. the Dijkstra algorithm to store its result in
257 257
any kind of path structure.
258 258

	
259 259
\sa lemon::concepts::Path
260 260
*/
261 261

	
262 262
/**
263 263
@defgroup auxdat Auxiliary Data Structures
264 264
@ingroup datas
265 265
\brief Auxiliary data structures implemented in LEMON.
266 266

	
267 267
This group contains some data structures implemented in LEMON in
268 268
order to make it easier to implement combinatorial algorithms.
269 269
*/
270 270

	
271 271
/**
272 272
@defgroup algs Algorithms
273 273
\brief This group contains the several algorithms
274 274
implemented in LEMON.
275 275

	
276 276
This group contains the several algorithms
277 277
implemented in LEMON.
278 278
*/
279 279

	
280 280
/**
281 281
@defgroup search Graph Search
282 282
@ingroup algs
283 283
\brief Common graph search algorithms.
284 284

	
285 285
This group contains the common graph search algorithms, namely
286 286
\e breadth-first \e search (BFS) and \e depth-first \e search (DFS).
287 287
*/
288 288

	
289 289
/**
290 290
@defgroup shortest_path Shortest Path Algorithms
291 291
@ingroup algs
292 292
\brief Algorithms for finding shortest paths.
293 293

	
294 294
This group contains the algorithms for finding shortest paths in digraphs.
295 295

	
296 296
 - \ref Dijkstra algorithm for finding shortest paths from a source node
297 297
   when all arc lengths are non-negative.
298 298
 - \ref BellmanFord "Bellman-Ford" algorithm for finding shortest paths
299 299
   from a source node when arc lenghts can be either positive or negative,
300 300
   but the digraph should not contain directed cycles with negative total
301 301
   length.
302 302
 - \ref FloydWarshall "Floyd-Warshall" and \ref Johnson "Johnson" algorithms
303 303
   for solving the \e all-pairs \e shortest \e paths \e problem when arc
304 304
   lenghts can be either positive or negative, but the digraph should
305 305
   not contain directed cycles with negative total length.
306 306
 - \ref Suurballe A successive shortest path algorithm for finding
307 307
   arc-disjoint paths between two nodes having minimum total length.
308 308
*/
309 309

	
310 310
/**
311 311
@defgroup max_flow Maximum Flow Algorithms
312 312
@ingroup algs
313 313
\brief Algorithms for finding maximum flows.
314 314

	
315 315
This group contains the algorithms for finding maximum flows and
316 316
feasible circulations.
317 317

	
318 318
The \e maximum \e flow \e problem is to find a flow of maximum value between
319 319
a single source and a single target. Formally, there is a \f$G=(V,A)\f$
320 320
digraph, a \f$cap: A\rightarrow\mathbf{R}^+_0\f$ capacity function and
321 321
\f$s, t \in V\f$ source and target nodes.
322 322
A maximum flow is an \f$f: A\rightarrow\mathbf{R}^+_0\f$ solution of the
323 323
following optimization problem.
324 324

	
325 325
\f[ \max\sum_{sv\in A} f(sv) - \sum_{vs\in A} f(vs) \f]
326 326
\f[ \sum_{uv\in A} f(uv) = \sum_{vu\in A} f(vu)
327 327
    \quad \forall u\in V\setminus\{s,t\} \f]
328 328
\f[ 0 \leq f(uv) \leq cap(uv) \quad \forall uv\in A \f]
329 329

	
330 330
LEMON contains several algorithms for solving maximum flow problems:
331 331
- \ref EdmondsKarp Edmonds-Karp algorithm.
332 332
- \ref Preflow Goldberg-Tarjan's preflow push-relabel algorithm.
333 333
- \ref DinitzSleatorTarjan Dinitz's blocking flow algorithm with dynamic trees.
334 334
- \ref GoldbergTarjan Preflow push-relabel algorithm with dynamic trees.
335 335

	
336 336
In most cases the \ref Preflow "Preflow" algorithm provides the
337 337
fastest method for computing a maximum flow. All implementations
338 338
provides functions to also query the minimum cut, which is the dual
339 339
problem of the maximum flow.
340 340
*/
341 341

	
342 342
/**
343 343
@defgroup min_cost_flow Minimum Cost Flow Algorithms
344 344
@ingroup algs
345 345

	
346 346
\brief Algorithms for finding minimum cost flows and circulations.
347 347

	
348 348
This group contains the algorithms for finding minimum cost flows and
349 349
circulations.
350 350

	
351 351
The \e minimum \e cost \e flow \e problem is to find a feasible flow of
352 352
minimum total cost from a set of supply nodes to a set of demand nodes
353 353
in a network with capacity constraints (lower and upper bounds)
354 354
and arc costs.
355
Formally, let \f$G=(V,A)\f$ be a digraph,
356
\f$lower, upper: A\rightarrow\mathbf{Z}^+_0\f$ denote the lower and
355
Formally, let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{Z}\f$,
356
\f$upper: A\rightarrow\mathbf{Z}\cup\{+\infty\}\f$ denote the lower and
357 357
upper bounds for the flow values on the arcs, for which
358
\f$0 \leq lower(uv) \leq upper(uv)\f$ holds for all \f$uv\in A\f$.
359
\f$cost: A\rightarrow\mathbf{Z}^+_0\f$ denotes the cost per unit flow
360
on the arcs, and \f$sup: V\rightarrow\mathbf{Z}\f$ denotes the
358
\f$lower(uv) \leq upper(uv)\f$ must hold for all \f$uv\in A\f$,
359
\f$cost: A\rightarrow\mathbf{Z}\f$ denotes the cost per unit flow
360
on the arcs and \f$sup: V\rightarrow\mathbf{Z}\f$ denotes the
361 361
signed supply values of the nodes.
362 362
If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
363 363
supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
364 364
\f$-sup(u)\f$ demand.
365
A minimum cost flow is an \f$f: A\rightarrow\mathbf{Z}^+_0\f$ solution
365
A minimum cost flow is an \f$f: A\rightarrow\mathbf{Z}\f$ solution
366 366
of the following optimization problem.
367 367

	
368 368
\f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
369 369
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
370 370
    sup(u) \quad \forall u\in V \f]
371 371
\f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
372 372

	
373 373
The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
374 374
zero or negative in order to have a feasible solution (since the sum
375 375
of the expressions on the left-hand side of the inequalities is zero).
376 376
It means that the total demand must be greater or equal to the total
377 377
supply and all the supplies have to be carried out from the supply nodes,
378 378
but there could be demands that are not satisfied.
379 379
If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
380 380
constraints have to be satisfied with equality, i.e. all demands
381 381
have to be satisfied and all supplies have to be used.
382 382

	
383 383
If you need the opposite inequalities in the supply/demand constraints
384 384
(i.e. the total demand is less than the total supply and all the demands
385 385
have to be satisfied while there could be supplies that are not used),
386 386
then you could easily transform the problem to the above form by reversing
387 387
the direction of the arcs and taking the negative of the supply values
388 388
(e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
389 389
However \ref NetworkSimplex algorithm also supports this form directly
390 390
for the sake of convenience.
391 391

	
392 392
A feasible solution for this problem can be found using \ref Circulation.
393 393

	
394 394
Note that the above formulation is actually more general than the usual
395 395
definition of the minimum cost flow problem, in which strict equalities
396 396
are required in the supply/demand contraints, i.e.
397 397

	
398 398
\f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) =
399 399
    sup(u) \quad \forall u\in V. \f]
400 400

	
401 401
However if the sum of the supply values is zero, then these two problems
402 402
are equivalent. So if you need the equality form, you have to ensure this
403 403
additional contraint for the algorithms.
404 404

	
405 405
The dual solution of the minimum cost flow problem is represented by node 
406 406
potentials \f$\pi: V\rightarrow\mathbf{Z}\f$.
407
An \f$f: A\rightarrow\mathbf{Z}^+_0\f$ feasible solution of the problem
407
An \f$f: A\rightarrow\mathbf{Z}\f$ feasible solution of the problem
408 408
is optimal if and only if for some \f$\pi: V\rightarrow\mathbf{Z}\f$
409 409
node potentials the following \e complementary \e slackness optimality
410 410
conditions hold.
411 411

	
412 412
 - For all \f$uv\in A\f$ arcs:
413 413
   - if \f$cost^\pi(uv)>0\f$, then \f$f(uv)=lower(uv)\f$;
414 414
   - if \f$lower(uv)<f(uv)<upper(uv)\f$, then \f$cost^\pi(uv)=0\f$;
415 415
   - if \f$cost^\pi(uv)<0\f$, then \f$f(uv)=upper(uv)\f$.
416
 - For all \f$u\in V\f$:
416
 - For all \f$u\in V\f$ nodes:
417 417
   - if \f$\sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \neq sup(u)\f$,
418 418
     then \f$\pi(u)=0\f$.
419 419
 
420 420
Here \f$cost^\pi(uv)\f$ denotes the \e reduced \e cost of the arc
421
\f$uv\in A\f$ with respect to the node potentials \f$\pi\f$, i.e.
421
\f$uv\in A\f$ with respect to the potential function \f$\pi\f$, i.e.
422 422
\f[ cost^\pi(uv) = cost(uv) + \pi(u) - \pi(v).\f]
423 423

	
424
All algorithms provide dual solution (node potentials) as well
424
All algorithms provide dual solution (node potentials) as well,
425 425
if an optimal flow is found.
426 426

	
427 427
LEMON contains several algorithms for solving minimum cost flow problems.
428 428
 - \ref NetworkSimplex Primal Network Simplex algorithm with various
429 429
   pivot strategies.
430 430
 - \ref CostScaling Push-Relabel and Augment-Relabel algorithms based on
431 431
   cost scaling.
432 432
 - \ref CapacityScaling Successive Shortest %Path algorithm with optional
433 433
   capacity scaling.
434 434
 - \ref CancelAndTighten The Cancel and Tighten algorithm.
435 435
 - \ref CycleCanceling Cycle-Canceling algorithms.
436 436

	
437 437
Most of these implementations support the general inequality form of the
438 438
minimum cost flow problem, but CancelAndTighten and CycleCanceling
439 439
only support the equality form due to the primal method they use.
440 440

	
441 441
In general NetworkSimplex is the most efficient implementation,
442 442
but in special cases other algorithms could be faster.
443 443
For example, if the total supply and/or capacities are rather small,
444 444
CapacityScaling is usually the fastest algorithm (without effective scaling).
445 445
*/
446 446

	
447 447
/**
448 448
@defgroup min_cut Minimum Cut Algorithms
449 449
@ingroup algs
450 450

	
451 451
\brief Algorithms for finding minimum cut in graphs.
452 452

	
453 453
This group contains the algorithms for finding minimum cut in graphs.
454 454

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

	
461 461
\f[ \min_{X \subset V, X\not\in \{\emptyset, V\}}
462 462
    \sum_{uv\in A, u\in X, v\not\in X}cap(uv) \f]
463 463

	
464 464
LEMON contains several algorithms related to minimum cut problems:
465 465

	
466 466
- \ref HaoOrlin "Hao-Orlin algorithm" for calculating minimum cut
467 467
  in directed graphs.
468 468
- \ref NagamochiIbaraki "Nagamochi-Ibaraki algorithm" for
469 469
  calculating minimum cut in undirected graphs.
470 470
- \ref GomoryHu "Gomory-Hu tree computation" for calculating
471 471
  all-pairs minimum cut in undirected graphs.
472 472

	
473 473
If you want to find minimum cut just between two distinict nodes,
474 474
see the \ref max_flow "maximum flow problem".
475 475
*/
476 476

	
477 477
/**
478 478
@defgroup graph_properties Connectivity and Other Graph Properties
479 479
@ingroup algs
480 480
\brief Algorithms for discovering the graph properties
481 481

	
482 482
This group contains the algorithms for discovering the graph properties
483 483
like connectivity, bipartiteness, euler property, simplicity etc.
484 484

	
485 485
\image html edge_biconnected_components.png
486 486
\image latex edge_biconnected_components.eps "bi-edge-connected components" width=\textwidth
487 487
*/
488 488

	
489 489
/**
490 490
@defgroup planar Planarity Embedding and Drawing
491 491
@ingroup algs
492 492
\brief Algorithms for planarity checking, embedding and drawing
493 493

	
494 494
This group contains the algorithms for planarity checking,
495 495
embedding and drawing.
496 496

	
497 497
\image html planar.png
498 498
\image latex planar.eps "Plane graph" width=\textwidth
499 499
*/
500 500

	
501 501
/**
502 502
@defgroup matching Matching Algorithms
503 503
@ingroup algs
504 504
\brief Algorithms for finding matchings in graphs and bipartite graphs.
505 505

	
506 506
This group contains the algorithms for calculating
507 507
matchings in graphs and bipartite graphs. The general matching problem is
508 508
finding a subset of the edges for which each node has at most one incident
509 509
edge.
510 510

	
511 511
There are several different algorithms for calculate matchings in
512 512
graphs.  The matching problems in bipartite graphs are generally
513 513
easier than in general graphs. The goal of the matching optimization
514 514
can be finding maximum cardinality, maximum weight or minimum cost
515 515
matching. The search can be constrained to find perfect or
516 516
maximum cardinality matching.
517 517

	
518 518
The matching algorithms implemented in LEMON:
519 519
- \ref MaxBipartiteMatching Hopcroft-Karp augmenting path algorithm
520 520
  for calculating maximum cardinality matching in bipartite graphs.
521 521
- \ref PrBipartiteMatching Push-relabel algorithm
522 522
  for calculating maximum cardinality matching in bipartite graphs.
523 523
- \ref MaxWeightedBipartiteMatching
524 524
  Successive shortest path algorithm for calculating maximum weighted
525 525
  matching and maximum weighted bipartite matching in bipartite graphs.
526 526
- \ref MinCostMaxBipartiteMatching
527 527
  Successive shortest path algorithm for calculating minimum cost maximum
528 528
  matching in bipartite graphs.
529 529
- \ref MaxMatching Edmond's blossom shrinking algorithm for calculating
530 530
  maximum cardinality matching in general graphs.
531 531
- \ref MaxWeightedMatching Edmond's blossom shrinking algorithm for calculating
532 532
  maximum weighted matching in general graphs.
533 533
- \ref MaxWeightedPerfectMatching
534 534
  Edmond's blossom shrinking algorithm for calculating maximum weighted
535 535
  perfect matching in general graphs.
536 536

	
537 537
\image html bipartite_matching.png
538 538
\image latex bipartite_matching.eps "Bipartite Matching" width=\textwidth
539 539
*/
540 540

	
541 541
/**
542 542
@defgroup spantree Minimum Spanning Tree Algorithms
543 543
@ingroup algs
544 544
\brief Algorithms for finding a minimum cost spanning tree in a graph.
545 545

	
546 546
This group contains the algorithms for finding a minimum cost spanning
547 547
tree in a graph.
548 548
*/
549 549

	
550 550
/**
551 551
@defgroup auxalg Auxiliary Algorithms
552 552
@ingroup algs
553 553
\brief Auxiliary algorithms implemented in LEMON.
554 554

	
555 555
This group contains some algorithms implemented in LEMON
556 556
in order to make it easier to implement complex algorithms.
557 557
*/
558 558

	
559 559
/**
560 560
@defgroup approx Approximation Algorithms
561 561
@ingroup algs
562 562
\brief Approximation algorithms.
563 563

	
564 564
This group contains the approximation and heuristic algorithms
565 565
implemented in LEMON.
566 566
*/
567 567

	
568 568
/**
569 569
@defgroup gen_opt_group General Optimization Tools
570 570
\brief This group contains some general optimization frameworks
571 571
implemented in LEMON.
572 572

	
573 573
This group contains some general optimization frameworks
574 574
implemented in LEMON.
575 575
*/
576 576

	
577 577
/**
578 578
@defgroup lp_group Lp and Mip Solvers
579 579
@ingroup gen_opt_group
580 580
\brief Lp and Mip solver interfaces for LEMON.
581 581

	
582 582
This group contains Lp and Mip solver interfaces for LEMON. The
583 583
various LP solvers could be used in the same manner with this
584 584
interface.
585 585
*/
586 586

	
587 587
/**
588 588
@defgroup lp_utils Tools for Lp and Mip Solvers
589 589
@ingroup lp_group
590 590
\brief Helper tools to the Lp and Mip solvers.
591 591

	
592 592
This group adds some helper tools to general optimization framework
593 593
implemented in LEMON.
594 594
*/
595 595

	
596 596
/**
597 597
@defgroup metah Metaheuristics
598 598
@ingroup gen_opt_group
599 599
\brief Metaheuristics for LEMON library.
600 600

	
601 601
This group contains some metaheuristic optimization tools.
602 602
*/
603 603

	
604 604
/**
605 605
@defgroup utils Tools and Utilities
606 606
\brief Tools and utilities for programming in LEMON
607 607

	
608 608
Tools and utilities for programming in LEMON.
609 609
*/
610 610

	
611 611
/**
612 612
@defgroup gutils Basic Graph Utilities
613 613
@ingroup utils
614 614
\brief Simple basic graph utilities.
615 615

	
616 616
This group contains some simple basic graph utilities.
617 617
*/
618 618

	
619 619
/**
620 620
@defgroup misc Miscellaneous Tools
621 621
@ingroup utils
622 622
\brief Tools for development, debugging and testing.
623 623

	
624 624
This group contains several useful tools for development,
625 625
debugging and testing.
626 626
*/
627 627

	
628 628
/**
629 629
@defgroup timecount Time Measuring and Counting
630 630
@ingroup misc
631 631
\brief Simple tools for measuring the performance of algorithms.
632 632

	
633 633
This group contains simple tools for measuring the performance
634 634
of algorithms.
635 635
*/
636 636

	
637 637
/**
638 638
@defgroup exceptions Exceptions
639 639
@ingroup utils
640 640
\brief Exceptions defined in LEMON.
641 641

	
642 642
This group contains the exceptions defined in LEMON.
643 643
*/
644 644

	
645 645
/**
646 646
@defgroup io_group Input-Output
647 647
\brief Graph Input-Output methods
648 648

	
649 649
This group contains the tools for importing and exporting graphs
650 650
and graph related data. Now it supports the \ref lgf-format
651 651
"LEMON Graph Format", the \c DIMACS format and the encapsulated
652 652
postscript (EPS) format.
653 653
*/
654 654

	
655 655
/**
656 656
@defgroup lemon_io LEMON Graph Format
657 657
@ingroup io_group
658 658
\brief Reading and writing LEMON Graph Format.
659 659

	
660 660
This group contains methods for reading and writing
661 661
\ref lgf-format "LEMON Graph Format".
662 662
*/
663 663

	
664 664
/**
665 665
@defgroup eps_io Postscript Exporting
666 666
@ingroup io_group
667 667
\brief General \c EPS drawer and graph exporter
668 668

	
669 669
This group contains general \c EPS drawing methods and special
670 670
graph exporting tools.
671 671
*/
672 672

	
673 673
/**
674 674
@defgroup dimacs_group DIMACS format
675 675
@ingroup io_group
676 676
\brief Read and write files in DIMACS format
677 677

	
678 678
Tools to read a digraph from or write it to a file in DIMACS format data.
679 679
*/
680 680

	
681 681
/**
682 682
@defgroup nauty_group NAUTY Format
683 683
@ingroup io_group
684 684
\brief Read \e Nauty format
685 685

	
686 686
Tool to read graphs from \e Nauty format data.
687 687
*/
688 688

	
689 689
/**
690 690
@defgroup concept Concepts
691 691
\brief Skeleton classes and concept checking classes
692 692

	
693 693
This group contains the data/algorithm skeletons and concept checking
694 694
classes implemented in LEMON.
695 695

	
696 696
The purpose of the classes in this group is fourfold.
697 697

	
698 698
- These classes contain the documentations of the %concepts. In order
699 699
  to avoid document multiplications, an implementation of a concept
700 700
  simply refers to the corresponding concept class.
701 701

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

	
711 711
- The concept descriptor classes also provide a <em>checker class</em>
712 712
  that makes it possible to check whether a certain implementation of a
713 713
  concept indeed provides all the required features.
714 714

	
715 715
- Finally, They can serve as a skeleton of a new implementation of a concept.
716 716
*/
717 717

	
718 718
/**
719 719
@defgroup graph_concepts Graph Structure Concepts
720 720
@ingroup concept
721 721
\brief Skeleton and concept checking classes for graph structures
722 722

	
723 723
This group contains the skeletons and concept checking classes of LEMON's
724 724
graph structures and helper classes used to implement these.
725 725
*/
726 726

	
727 727
/**
728 728
@defgroup map_concepts Map Concepts
729 729
@ingroup concept
730 730
\brief Skeleton and concept checking classes for maps
731 731

	
732 732
This group contains the skeletons and concept checking classes of maps.
733 733
*/
734 734

	
735 735
/**
736 736
\anchor demoprograms
737 737

	
738 738
@defgroup demos Demo Programs
739 739

	
740 740
Some demo programs are listed here. Their full source codes can be found in
741 741
the \c demo subdirectory of the source tree.
742 742

	
743 743
In order to compile them, use the <tt>make demo</tt> or the
744 744
<tt>make check</tt> commands.
745 745
*/
746 746

	
747 747
/**
748 748
@defgroup tools Standalone Utility Applications
749 749

	
750 750
Some utility applications are listed here.
751 751

	
752 752
The standard compilation procedure (<tt>./configure;make</tt>) will compile
753 753
them, as well.
754 754
*/
755 755

	
756 756
}
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 22
/// \ingroup min_cost_flow
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
#include <lemon/maps.h>
34
#include <lemon/circulation.h>
35
#include <lemon/adaptors.h>
36 33

	
37 34
namespace lemon {
38 35

	
39 36
  /// \addtogroup min_cost_flow
40 37
  /// @{
41 38

	
42 39
  /// \brief Implementation of the primal Network Simplex algorithm
43 40
  /// for finding a \ref min_cost_flow "minimum cost flow".
44 41
  ///
45 42
  /// \ref NetworkSimplex implements the primal Network Simplex algorithm
46 43
  /// for finding a \ref min_cost_flow "minimum cost flow".
47 44
  /// This algorithm is a specialized version of the linear programming
48 45
  /// simplex method directly for the minimum cost flow problem.
49 46
  /// It is one of the most efficient solution methods.
50 47
  ///
51 48
  /// In general this class is the fastest implementation available
52 49
  /// in LEMON for the minimum cost flow problem.
53
  /// Moreover it supports both direction of the supply/demand inequality
54
  /// constraints. For more information see \ref ProblemType.
50
  /// Moreover it supports both directions of the supply/demand inequality
51
  /// constraints. For more information see \ref SupplyType.
52
  ///
53
  /// Most of the parameters of the problem (except for the digraph)
54
  /// can be given using separate functions, and the algorithm can be
55
  /// executed using the \ref run() function. If some parameters are not
56
  /// specified, then default values will be used.
55 57
  ///
56 58
  /// \tparam GR The digraph type the algorithm runs on.
57 59
  /// \tparam F The value type used for flow amounts, capacity bounds
58 60
  /// and supply values in the algorithm. By default it is \c int.
59 61
  /// \tparam C The value type used for costs and potentials in the
60 62
  /// algorithm. By default it is the same as \c F.
61 63
  ///
62 64
  /// \warning Both value types must be signed and all input data must
63 65
  /// be integer.
64 66
  ///
65 67
  /// \note %NetworkSimplex provides five different pivot rule
66 68
  /// implementations, from which the most efficient one is used
67 69
  /// by default. For more information see \ref PivotRule.
68 70
  template <typename GR, typename F = int, typename C = F>
69 71
  class NetworkSimplex
70 72
  {
71 73
  public:
72 74

	
73 75
    /// The flow type of the algorithm
74 76
    typedef F Flow;
75 77
    /// The cost type of the algorithm
76 78
    typedef C Cost;
77 79
#ifdef DOXYGEN
78 80
    /// The type of the flow map
79 81
    typedef GR::ArcMap<Flow> FlowMap;
80 82
    /// The type of the potential map
81 83
    typedef GR::NodeMap<Cost> PotentialMap;
82 84
#else
83 85
    /// The type of the flow map
84 86
    typedef typename GR::template ArcMap<Flow> FlowMap;
85 87
    /// The type of the potential map
86 88
    typedef typename GR::template NodeMap<Cost> PotentialMap;
87 89
#endif
88 90

	
89 91
  public:
90 92

	
91
    /// \brief Enum type for selecting the pivot rule.
93
    /// \brief Problem type constants for the \c run() function.
92 94
    ///
93
    /// Enum type for selecting the pivot rule for the \ref run()
95
    /// Enum type containing the problem type constants that can be
96
    /// returned by the \ref run() function of the algorithm.
97
    enum ProblemType {
98
      /// The problem has no feasible solution (flow).
99
      INFEASIBLE,
100
      /// The problem has optimal solution (i.e. it is feasible and
101
      /// bounded), and the algorithm has found optimal flow and node
102
      /// potentials (primal and dual solutions).
103
      OPTIMAL,
104
      /// The objective function of the problem is unbounded, i.e.
105
      /// there is a directed cycle having negative total cost and
106
      /// infinite upper bound.
107
      UNBOUNDED
108
    };
109
    
110
    /// \brief Constants for selecting the type of the supply constraints.
111
    ///
112
    /// Enum type containing constants for selecting the supply type,
113
    /// i.e. the direction of the inequalities in the supply/demand
114
    /// constraints of the \ref min_cost_flow "minimum cost flow problem".
115
    ///
116
    /// The default supply type is \c GEQ, since this form is supported
117
    /// by other minimum cost flow algorithms and the \ref Circulation
118
    /// algorithm, as well.
119
    /// The \c LEQ problem type can be selected using the \ref supplyType()
94 120
    /// function.
95 121
    ///
122
    /// Note that the equality form is a special case of both supply types.
123
    enum SupplyType {
124

	
125
      /// This option means that there are <em>"greater or equal"</em>
126
      /// supply/demand constraints in the definition, i.e. the exact
127
      /// formulation of the problem is the following.
128
      /**
129
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
130
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
131
              sup(u) \quad \forall u\in V \f]
132
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
133
      */
134
      /// It means that the total demand must be greater or equal to the 
135
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
136
      /// negative) and all the supplies have to be carried out from 
137
      /// the supply nodes, but there could be demands that are not 
138
      /// satisfied.
139
      GEQ,
140
      /// It is just an alias for the \c GEQ option.
141
      CARRY_SUPPLIES = GEQ,
142

	
143
      /// This option means that there are <em>"less or equal"</em>
144
      /// supply/demand constraints in the definition, i.e. the exact
145
      /// formulation of the problem is the following.
146
      /**
147
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
148
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
149
              sup(u) \quad \forall u\in V \f]
150
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
151
      */
152
      /// It means that the total demand must be less or equal to the 
153
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
154
      /// positive) and all the demands have to be satisfied, but there
155
      /// could be supplies that are not carried out from the supply
156
      /// nodes.
157
      LEQ,
158
      /// It is just an alias for the \c LEQ option.
159
      SATISFY_DEMANDS = LEQ
160
    };
161
    
162
    /// \brief Constants for selecting the pivot rule.
163
    ///
164
    /// Enum type containing constants for selecting the pivot rule for
165
    /// the \ref run() function.
166
    ///
96 167
    /// \ref NetworkSimplex provides five different pivot rule
97 168
    /// implementations that significantly affect the running time
98 169
    /// of the algorithm.
99 170
    /// By default \ref BLOCK_SEARCH "Block Search" is used, which
100 171
    /// proved to be the most efficient and the most robust on various
101 172
    /// test inputs according to our benchmark tests.
102 173
    /// However another pivot rule can be selected using the \ref run()
103 174
    /// function with the proper parameter.
104 175
    enum PivotRule {
105 176

	
106 177
      /// The First Eligible pivot rule.
107 178
      /// The next eligible arc is selected in a wraparound fashion
108 179
      /// in every iteration.
109 180
      FIRST_ELIGIBLE,
110 181

	
111 182
      /// The Best Eligible pivot rule.
112 183
      /// The best eligible arc is selected in every iteration.
113 184
      BEST_ELIGIBLE,
114 185

	
115 186
      /// The Block Search pivot rule.
116 187
      /// A specified number of arcs are examined in every iteration
117 188
      /// in a wraparound fashion and the best eligible arc is selected
118 189
      /// from this block.
119 190
      BLOCK_SEARCH,
120 191

	
121 192
      /// The Candidate List pivot rule.
122 193
      /// In a major iteration a candidate list is built from eligible arcs
123 194
      /// in a wraparound fashion and in the following minor iterations
124 195
      /// the best eligible arc is selected from this list.
125 196
      CANDIDATE_LIST,
126 197

	
127 198
      /// The Altering Candidate List pivot rule.
128 199
      /// It is a modified version of the Candidate List method.
129 200
      /// It keeps only the several best eligible arcs from the former
130 201
      /// candidate list and extends this list in every iteration.
131 202
      ALTERING_LIST
132 203
    };
133 204
    
134
    /// \brief Enum type for selecting the problem type.
135
    ///
136
    /// Enum type for selecting the problem type, i.e. the direction of
137
    /// the inequalities in the supply/demand constraints of the
138
    /// \ref min_cost_flow "minimum cost flow problem".
139
    ///
140
    /// The default problem type is \c GEQ, since this form is supported
141
    /// by other minimum cost flow algorithms and the \ref Circulation
142
    /// algorithm as well.
143
    /// The \c LEQ problem type can be selected using the \ref problemType()
144
    /// function.
145
    ///
146
    /// Note that the equality form is a special case of both problem type.
147
    enum ProblemType {
148

	
149
      /// This option means that there are "<em>greater or equal</em>"
150
      /// constraints in the defintion, i.e. the exact formulation of the
151
      /// problem is the following.
152
      /**
153
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
154
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \geq
155
              sup(u) \quad \forall u\in V \f]
156
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
157
      */
158
      /// It means that the total demand must be greater or equal to the 
159
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
160
      /// negative) and all the supplies have to be carried out from 
161
      /// the supply nodes, but there could be demands that are not 
162
      /// satisfied.
163
      GEQ,
164
      /// It is just an alias for the \c GEQ option.
165
      CARRY_SUPPLIES = GEQ,
166

	
167
      /// This option means that there are "<em>less or equal</em>"
168
      /// constraints in the defintion, i.e. the exact formulation of the
169
      /// problem is the following.
170
      /**
171
          \f[ \min\sum_{uv\in A} f(uv) \cdot cost(uv) \f]
172
          \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu) \leq
173
              sup(u) \quad \forall u\in V \f]
174
          \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A \f]
175
      */
176
      /// It means that the total demand must be less or equal to the 
177
      /// total supply (i.e. \f$\sum_{u\in V} sup(u)\f$ must be zero or
178
      /// positive) and all the demands have to be satisfied, but there
179
      /// could be supplies that are not carried out from the supply
180
      /// nodes.
181
      LEQ,
182
      /// It is just an alias for the \c LEQ option.
183
      SATISFY_DEMANDS = LEQ
184
    };
185

	
186 205
  private:
187 206

	
188 207
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
189 208

	
190 209
    typedef typename GR::template ArcMap<Flow> FlowArcMap;
191 210
    typedef typename GR::template ArcMap<Cost> CostArcMap;
192 211
    typedef typename GR::template NodeMap<Flow> FlowNodeMap;
193 212

	
194 213
    typedef std::vector<Arc> ArcVector;
195 214
    typedef std::vector<Node> NodeVector;
196 215
    typedef std::vector<int> IntVector;
197 216
    typedef std::vector<bool> BoolVector;
198 217
    typedef std::vector<Flow> FlowVector;
199 218
    typedef std::vector<Cost> CostVector;
200 219

	
201 220
    // State constants for arcs
202 221
    enum ArcStateEnum {
203 222
      STATE_UPPER = -1,
204 223
      STATE_TREE  =  0,
205 224
      STATE_LOWER =  1
206 225
    };
207 226

	
208 227
  private:
209 228

	
210 229
    // Data related to the underlying digraph
211 230
    const GR &_graph;
212 231
    int _node_num;
213 232
    int _arc_num;
214 233

	
215 234
    // Parameters of the problem
216 235
    FlowArcMap *_plower;
217 236
    FlowArcMap *_pupper;
218 237
    CostArcMap *_pcost;
219 238
    FlowNodeMap *_psupply;
220 239
    bool _pstsup;
221 240
    Node _psource, _ptarget;
222 241
    Flow _pstflow;
223
    ProblemType _ptype;
242
    SupplyType _stype;
243
    
244
    Flow _sum_supply;
224 245

	
225 246
    // Result maps
226 247
    FlowMap *_flow_map;
227 248
    PotentialMap *_potential_map;
228 249
    bool _local_flow;
229 250
    bool _local_potential;
230 251

	
231 252
    // Data structures for storing the digraph
232 253
    IntNodeMap _node_id;
233 254
    ArcVector _arc_ref;
234 255
    IntVector _source;
235 256
    IntVector _target;
236 257

	
237 258
    // Node and arc data
238 259
    FlowVector _cap;
239 260
    CostVector _cost;
240 261
    FlowVector _supply;
241 262
    FlowVector _flow;
242 263
    CostVector _pi;
243 264

	
244 265
    // Data for storing the spanning tree structure
245 266
    IntVector _parent;
246 267
    IntVector _pred;
247 268
    IntVector _thread;
248 269
    IntVector _rev_thread;
249 270
    IntVector _succ_num;
250 271
    IntVector _last_succ;
251 272
    IntVector _dirty_revs;
252 273
    BoolVector _forward;
253 274
    IntVector _state;
254 275
    int _root;
255 276

	
256 277
    // Temporary data used in the current pivot iteration
257 278
    int in_arc, join, u_in, v_in, u_out, v_out;
258 279
    int first, second, right, last;
259 280
    int stem, par_stem, new_stem;
260 281
    Flow delta;
261 282

	
283
  public:
284
  
285
    /// \brief Constant for infinite upper bounds (capacities).
286
    ///
287
    /// Constant for infinite upper bounds (capacities).
288
    /// It is \c std::numeric_limits<Flow>::infinity() if available,
289
    /// \c std::numeric_limits<Flow>::max() otherwise.
290
    const Flow INF;
291

	
262 292
  private:
263 293

	
264 294
    // Implementation of the First Eligible pivot rule
265 295
    class FirstEligiblePivotRule
266 296
    {
267 297
    private:
268 298

	
269 299
      // References to the NetworkSimplex class
270 300
      const IntVector  &_source;
271 301
      const IntVector  &_target;
272 302
      const CostVector &_cost;
273 303
      const IntVector  &_state;
274 304
      const CostVector &_pi;
275 305
      int &_in_arc;
276 306
      int _arc_num;
277 307

	
278 308
      // Pivot rule data
279 309
      int _next_arc;
280 310

	
281 311
    public:
282 312

	
283 313
      // Constructor
284 314
      FirstEligiblePivotRule(NetworkSimplex &ns) :
285 315
        _source(ns._source), _target(ns._target),
286 316
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
287 317
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
288 318
      {}
289 319

	
290 320
      // Find next entering arc
291 321
      bool findEnteringArc() {
292 322
        Cost c;
293 323
        for (int e = _next_arc; e < _arc_num; ++e) {
294 324
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
295 325
          if (c < 0) {
296 326
            _in_arc = e;
297 327
            _next_arc = e + 1;
298 328
            return true;
299 329
          }
300 330
        }
301 331
        for (int e = 0; e < _next_arc; ++e) {
302 332
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
303 333
          if (c < 0) {
304 334
            _in_arc = e;
305 335
            _next_arc = e + 1;
306 336
            return true;
307 337
          }
308 338
        }
309 339
        return false;
310 340
      }
311 341

	
312 342
    }; //class FirstEligiblePivotRule
313 343

	
314 344

	
315 345
    // Implementation of the Best Eligible pivot rule
316 346
    class BestEligiblePivotRule
317 347
    {
318 348
    private:
319 349

	
320 350
      // References to the NetworkSimplex class
321 351
      const IntVector  &_source;
322 352
      const IntVector  &_target;
323 353
      const CostVector &_cost;
324 354
      const IntVector  &_state;
325 355
      const CostVector &_pi;
326 356
      int &_in_arc;
327 357
      int _arc_num;
328 358

	
329 359
    public:
330 360

	
331 361
      // Constructor
332 362
      BestEligiblePivotRule(NetworkSimplex &ns) :
333 363
        _source(ns._source), _target(ns._target),
334 364
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
335 365
        _in_arc(ns.in_arc), _arc_num(ns._arc_num)
336 366
      {}
337 367

	
338 368
      // Find next entering arc
339 369
      bool findEnteringArc() {
340 370
        Cost c, min = 0;
341 371
        for (int e = 0; e < _arc_num; ++e) {
342 372
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
343 373
          if (c < min) {
344 374
            min = c;
345 375
            _in_arc = e;
346 376
          }
347 377
        }
348 378
        return min < 0;
349 379
      }
350 380

	
351 381
    }; //class BestEligiblePivotRule
352 382

	
353 383

	
354 384
    // Implementation of the Block Search pivot rule
355 385
    class BlockSearchPivotRule
356 386
    {
357 387
    private:
358 388

	
359 389
      // References to the NetworkSimplex class
360 390
      const IntVector  &_source;
361 391
      const IntVector  &_target;
362 392
      const CostVector &_cost;
363 393
      const IntVector  &_state;
364 394
      const CostVector &_pi;
365 395
      int &_in_arc;
366 396
      int _arc_num;
367 397

	
368 398
      // Pivot rule data
369 399
      int _block_size;
370 400
      int _next_arc;
371 401

	
372 402
    public:
373 403

	
374 404
      // Constructor
375 405
      BlockSearchPivotRule(NetworkSimplex &ns) :
376 406
        _source(ns._source), _target(ns._target),
377 407
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
378 408
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
379 409
      {
380 410
        // The main parameters of the pivot rule
381 411
        const double BLOCK_SIZE_FACTOR = 2.0;
382 412
        const int MIN_BLOCK_SIZE = 10;
383 413

	
384 414
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
385 415
                                    std::sqrt(double(_arc_num))),
386 416
                                MIN_BLOCK_SIZE );
387 417
      }
388 418

	
389 419
      // Find next entering arc
390 420
      bool findEnteringArc() {
391 421
        Cost c, min = 0;
392 422
        int cnt = _block_size;
393 423
        int e, min_arc = _next_arc;
394 424
        for (e = _next_arc; e < _arc_num; ++e) {
395 425
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
396 426
          if (c < min) {
397 427
            min = c;
398 428
            min_arc = e;
399 429
          }
400 430
          if (--cnt == 0) {
401 431
            if (min < 0) break;
402 432
            cnt = _block_size;
403 433
          }
404 434
        }
405 435
        if (min == 0 || cnt > 0) {
406 436
          for (e = 0; e < _next_arc; ++e) {
407 437
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
408 438
            if (c < min) {
409 439
              min = c;
410 440
              min_arc = e;
411 441
            }
412 442
            if (--cnt == 0) {
413 443
              if (min < 0) break;
414 444
              cnt = _block_size;
415 445
            }
416 446
          }
417 447
        }
418 448
        if (min >= 0) return false;
419 449
        _in_arc = min_arc;
420 450
        _next_arc = e;
421 451
        return true;
422 452
      }
423 453

	
424 454
    }; //class BlockSearchPivotRule
425 455

	
426 456

	
427 457
    // Implementation of the Candidate List pivot rule
428 458
    class CandidateListPivotRule
429 459
    {
430 460
    private:
431 461

	
432 462
      // References to the NetworkSimplex class
433 463
      const IntVector  &_source;
434 464
      const IntVector  &_target;
435 465
      const CostVector &_cost;
436 466
      const IntVector  &_state;
437 467
      const CostVector &_pi;
438 468
      int &_in_arc;
439 469
      int _arc_num;
440 470

	
441 471
      // Pivot rule data
442 472
      IntVector _candidates;
443 473
      int _list_length, _minor_limit;
444 474
      int _curr_length, _minor_count;
445 475
      int _next_arc;
446 476

	
447 477
    public:
448 478

	
449 479
      /// Constructor
450 480
      CandidateListPivotRule(NetworkSimplex &ns) :
451 481
        _source(ns._source), _target(ns._target),
452 482
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
453 483
        _in_arc(ns.in_arc), _arc_num(ns._arc_num), _next_arc(0)
454 484
      {
455 485
        // The main parameters of the pivot rule
456 486
        const double LIST_LENGTH_FACTOR = 1.0;
457 487
        const int MIN_LIST_LENGTH = 10;
458 488
        const double MINOR_LIMIT_FACTOR = 0.1;
459 489
        const int MIN_MINOR_LIMIT = 3;
460 490

	
461 491
        _list_length = std::max( int(LIST_LENGTH_FACTOR *
462 492
                                     std::sqrt(double(_arc_num))),
463 493
                                 MIN_LIST_LENGTH );
464 494
        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
465 495
                                 MIN_MINOR_LIMIT );
466 496
        _curr_length = _minor_count = 0;
467 497
        _candidates.resize(_list_length);
468 498
      }
469 499

	
470 500
      /// Find next entering arc
471 501
      bool findEnteringArc() {
472 502
        Cost min, c;
473 503
        int e, min_arc = _next_arc;
474 504
        if (_curr_length > 0 && _minor_count < _minor_limit) {
475 505
          // Minor iteration: select the best eligible arc from the
476 506
          // current candidate list
477 507
          ++_minor_count;
478 508
          min = 0;
479 509
          for (int i = 0; i < _curr_length; ++i) {
480 510
            e = _candidates[i];
481 511
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
482 512
            if (c < min) {
483 513
              min = c;
484 514
              min_arc = e;
485 515
            }
486 516
            if (c >= 0) {
487 517
              _candidates[i--] = _candidates[--_curr_length];
488 518
            }
489 519
          }
490 520
          if (min < 0) {
491 521
            _in_arc = min_arc;
492 522
            return true;
493 523
          }
494 524
        }
495 525

	
496 526
        // Major iteration: build a new candidate list
497 527
        min = 0;
498 528
        _curr_length = 0;
499 529
        for (e = _next_arc; e < _arc_num; ++e) {
500 530
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
501 531
          if (c < 0) {
502 532
            _candidates[_curr_length++] = e;
503 533
            if (c < min) {
504 534
              min = c;
505 535
              min_arc = e;
506 536
            }
507 537
            if (_curr_length == _list_length) break;
508 538
          }
509 539
        }
510 540
        if (_curr_length < _list_length) {
511 541
          for (e = 0; e < _next_arc; ++e) {
512 542
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
513 543
            if (c < 0) {
514 544
              _candidates[_curr_length++] = e;
515 545
              if (c < min) {
516 546
                min = c;
517 547
                min_arc = e;
518 548
              }
519 549
              if (_curr_length == _list_length) break;
520 550
            }
521 551
          }
522 552
        }
523 553
        if (_curr_length == 0) return false;
524 554
        _minor_count = 1;
525 555
        _in_arc = min_arc;
526 556
        _next_arc = e;
527 557
        return true;
528 558
      }
529 559

	
530 560
    }; //class CandidateListPivotRule
531 561

	
532 562

	
533 563
    // Implementation of the Altering Candidate List pivot rule
534 564
    class AlteringListPivotRule
535 565
    {
536 566
    private:
537 567

	
538 568
      // References to the NetworkSimplex class
539 569
      const IntVector  &_source;
540 570
      const IntVector  &_target;
541 571
      const CostVector &_cost;
542 572
      const IntVector  &_state;
543 573
      const CostVector &_pi;
544 574
      int &_in_arc;
545 575
      int _arc_num;
546 576

	
547 577
      // Pivot rule data
548 578
      int _block_size, _head_length, _curr_length;
549 579
      int _next_arc;
550 580
      IntVector _candidates;
551 581
      CostVector _cand_cost;
552 582

	
553 583
      // Functor class to compare arcs during sort of the candidate list
554 584
      class SortFunc
555 585
      {
556 586
      private:
557 587
        const CostVector &_map;
558 588
      public:
559 589
        SortFunc(const CostVector &map) : _map(map) {}
560 590
        bool operator()(int left, int right) {
561 591
          return _map[left] > _map[right];
562 592
        }
563 593
      };
564 594

	
565 595
      SortFunc _sort_func;
566 596

	
567 597
    public:
568 598

	
569 599
      // Constructor
570 600
      AlteringListPivotRule(NetworkSimplex &ns) :
571 601
        _source(ns._source), _target(ns._target),
572 602
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
573 603
        _in_arc(ns.in_arc), _arc_num(ns._arc_num),
574 604
        _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
575 605
      {
576 606
        // The main parameters of the pivot rule
577 607
        const double BLOCK_SIZE_FACTOR = 1.5;
578 608
        const int MIN_BLOCK_SIZE = 10;
579 609
        const double HEAD_LENGTH_FACTOR = 0.1;
580 610
        const int MIN_HEAD_LENGTH = 3;
581 611

	
582 612
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
583 613
                                    std::sqrt(double(_arc_num))),
584 614
                                MIN_BLOCK_SIZE );
585 615
        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
586 616
                                 MIN_HEAD_LENGTH );
587 617
        _candidates.resize(_head_length + _block_size);
588 618
        _curr_length = 0;
589 619
      }
590 620

	
591 621
      // Find next entering arc
592 622
      bool findEnteringArc() {
593 623
        // Check the current candidate list
594 624
        int e;
595 625
        for (int i = 0; i < _curr_length; ++i) {
596 626
          e = _candidates[i];
597 627
          _cand_cost[e] = _state[e] *
598 628
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
599 629
          if (_cand_cost[e] >= 0) {
600 630
            _candidates[i--] = _candidates[--_curr_length];
601 631
          }
602 632
        }
603 633

	
604 634
        // Extend the list
605 635
        int cnt = _block_size;
606 636
        int last_arc = 0;
607 637
        int limit = _head_length;
608 638

	
609 639
        for (int e = _next_arc; e < _arc_num; ++e) {
610 640
          _cand_cost[e] = _state[e] *
611 641
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
612 642
          if (_cand_cost[e] < 0) {
613 643
            _candidates[_curr_length++] = e;
614 644
            last_arc = e;
615 645
          }
616 646
          if (--cnt == 0) {
617 647
            if (_curr_length > limit) break;
618 648
            limit = 0;
619 649
            cnt = _block_size;
620 650
          }
621 651
        }
622 652
        if (_curr_length <= limit) {
623 653
          for (int e = 0; e < _next_arc; ++e) {
624 654
            _cand_cost[e] = _state[e] *
625 655
              (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
626 656
            if (_cand_cost[e] < 0) {
627 657
              _candidates[_curr_length++] = e;
628 658
              last_arc = e;
629 659
            }
630 660
            if (--cnt == 0) {
631 661
              if (_curr_length > limit) break;
632 662
              limit = 0;
633 663
              cnt = _block_size;
634 664
            }
635 665
          }
636 666
        }
637 667
        if (_curr_length == 0) return false;
638 668
        _next_arc = last_arc + 1;
639 669

	
640 670
        // Make heap of the candidate list (approximating a partial sort)
641 671
        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
642 672
                   _sort_func );
643 673

	
644 674
        // Pop the first element of the heap
645 675
        _in_arc = _candidates[0];
646 676
        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
647 677
                  _sort_func );
648 678
        _curr_length = std::min(_head_length, _curr_length - 1);
649 679
        return true;
650 680
      }
651 681

	
652 682
    }; //class AlteringListPivotRule
653 683

	
654 684
  public:
655 685

	
656 686
    /// \brief Constructor.
657 687
    ///
658 688
    /// The constructor of the class.
659 689
    ///
660 690
    /// \param graph The digraph the algorithm runs on.
661 691
    NetworkSimplex(const GR& graph) :
662 692
      _graph(graph),
663 693
      _plower(NULL), _pupper(NULL), _pcost(NULL),
664
      _psupply(NULL), _pstsup(false), _ptype(GEQ),
694
      _psupply(NULL), _pstsup(false), _stype(GEQ),
665 695
      _flow_map(NULL), _potential_map(NULL),
666 696
      _local_flow(false), _local_potential(false),
667
      _node_id(graph)
697
      _node_id(graph),
698
      INF(std::numeric_limits<Flow>::has_infinity ?
699
          std::numeric_limits<Flow>::infinity() :
700
          std::numeric_limits<Flow>::max())
668 701
    {
669
      LEMON_ASSERT(std::numeric_limits<Flow>::is_integer &&
670
                   std::numeric_limits<Flow>::is_signed,
671
        "The flow type of NetworkSimplex must be signed integer");
672
      LEMON_ASSERT(std::numeric_limits<Cost>::is_integer &&
673
                   std::numeric_limits<Cost>::is_signed,
674
        "The cost type of NetworkSimplex must be signed integer");
702
      // Check the value types
703
      LEMON_ASSERT(std::numeric_limits<Flow>::is_signed,
704
        "The flow type of NetworkSimplex must be signed");
705
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
706
        "The cost type of NetworkSimplex must be signed");
675 707
    }
676 708

	
677 709
    /// Destructor.
678 710
    ~NetworkSimplex() {
679 711
      if (_local_flow) delete _flow_map;
680 712
      if (_local_potential) delete _potential_map;
681 713
    }
682 714

	
683 715
    /// \name Parameters
684 716
    /// The parameters of the algorithm can be specified using these
685 717
    /// functions.
686 718

	
687 719
    /// @{
688 720

	
689 721
    /// \brief Set the lower bounds on the arcs.
690 722
    ///
691 723
    /// This function sets the lower bounds on the arcs.
692
    /// If neither this function nor \ref boundMaps() is used before
693
    /// calling \ref run(), the lower bounds will be set to zero
694
    /// on all arcs.
724
    /// If it is not used before calling \ref run(), the lower bounds
725
    /// will be set to zero on all arcs.
695 726
    ///
696 727
    /// \param map An arc map storing the lower bounds.
697 728
    /// Its \c Value type must be convertible to the \c Flow type
698 729
    /// of the algorithm.
699 730
    ///
700 731
    /// \return <tt>(*this)</tt>
701
    template <typename LOWER>
702
    NetworkSimplex& lowerMap(const LOWER& map) {
732
    template <typename LowerMap>
733
    NetworkSimplex& lowerMap(const LowerMap& map) {
703 734
      delete _plower;
704 735
      _plower = new FlowArcMap(_graph);
705 736
      for (ArcIt a(_graph); a != INVALID; ++a) {
706 737
        (*_plower)[a] = map[a];
707 738
      }
708 739
      return *this;
709 740
    }
710 741

	
711 742
    /// \brief Set the upper bounds (capacities) on the arcs.
712 743
    ///
713 744
    /// This function sets the upper bounds (capacities) on the arcs.
714
    /// If none of the functions \ref upperMap(), \ref capacityMap()
715
    /// and \ref boundMaps() is used before calling \ref run(),
716
    /// the upper bounds (capacities) will be set to
717
    /// \c std::numeric_limits<Flow>::max() on all arcs.
745
    /// If it is not used before calling \ref run(), the upper bounds
746
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
747
    /// unbounded from above on each arc).
718 748
    ///
719 749
    /// \param map An arc map storing the upper bounds.
720 750
    /// Its \c Value type must be convertible to the \c Flow type
721 751
    /// of the algorithm.
722 752
    ///
723 753
    /// \return <tt>(*this)</tt>
724
    template<typename UPPER>
725
    NetworkSimplex& upperMap(const UPPER& map) {
754
    template<typename UpperMap>
755
    NetworkSimplex& upperMap(const UpperMap& map) {
726 756
      delete _pupper;
727 757
      _pupper = new FlowArcMap(_graph);
728 758
      for (ArcIt a(_graph); a != INVALID; ++a) {
729 759
        (*_pupper)[a] = map[a];
730 760
      }
731 761
      return *this;
732 762
    }
733 763

	
734
    /// \brief Set the upper bounds (capacities) on the arcs.
735
    ///
736
    /// This function sets the upper bounds (capacities) on the arcs.
737
    /// It is just an alias for \ref upperMap().
738
    ///
739
    /// \return <tt>(*this)</tt>
740
    template<typename CAP>
741
    NetworkSimplex& capacityMap(const CAP& map) {
742
      return upperMap(map);
743
    }
744

	
745
    /// \brief Set the lower and upper bounds on the arcs.
746
    ///
747
    /// This function sets the lower and upper bounds on the arcs.
748
    /// If neither this function nor \ref lowerMap() is used before
749
    /// calling \ref run(), the lower bounds will be set to zero
750
    /// on all arcs.
751
    /// If none of the functions \ref upperMap(), \ref capacityMap()
752
    /// and \ref boundMaps() is used before calling \ref run(),
753
    /// the upper bounds (capacities) will be set to
754
    /// \c std::numeric_limits<Flow>::max() on all arcs.
755
    ///
756
    /// \param lower An arc map storing the lower bounds.
757
    /// \param upper An arc map storing the upper bounds.
758
    ///
759
    /// The \c Value type of the maps must be convertible to the
760
    /// \c Flow type of the algorithm.
761
    ///
762
    /// \note This function is just a shortcut of calling \ref lowerMap()
763
    /// and \ref upperMap() separately.
764
    ///
765
    /// \return <tt>(*this)</tt>
766
    template <typename LOWER, typename UPPER>
767
    NetworkSimplex& boundMaps(const LOWER& lower, const UPPER& upper) {
768
      return lowerMap(lower).upperMap(upper);
769
    }
770

	
771 764
    /// \brief Set the costs of the arcs.
772 765
    ///
773 766
    /// This function sets the costs of the arcs.
774 767
    /// If it is not used before calling \ref run(), the costs
775 768
    /// will be set to \c 1 on all arcs.
776 769
    ///
777 770
    /// \param map An arc map storing the costs.
778 771
    /// Its \c Value type must be convertible to the \c Cost type
779 772
    /// of the algorithm.
780 773
    ///
781 774
    /// \return <tt>(*this)</tt>
782
    template<typename COST>
783
    NetworkSimplex& costMap(const COST& map) {
775
    template<typename CostMap>
776
    NetworkSimplex& costMap(const CostMap& map) {
784 777
      delete _pcost;
785 778
      _pcost = new CostArcMap(_graph);
786 779
      for (ArcIt a(_graph); a != INVALID; ++a) {
787 780
        (*_pcost)[a] = map[a];
788 781
      }
789 782
      return *this;
790 783
    }
791 784

	
792 785
    /// \brief Set the supply values of the nodes.
793 786
    ///
794 787
    /// This function sets the supply values of the nodes.
795 788
    /// If neither this function nor \ref stSupply() is used before
796 789
    /// calling \ref run(), the supply of each node will be set to zero.
797 790
    /// (It makes sense only if non-zero lower bounds are given.)
798 791
    ///
799 792
    /// \param map A node map storing the supply values.
800 793
    /// Its \c Value type must be convertible to the \c Flow type
801 794
    /// of the algorithm.
802 795
    ///
803 796
    /// \return <tt>(*this)</tt>
804
    template<typename SUP>
805
    NetworkSimplex& supplyMap(const SUP& map) {
797
    template<typename SupplyMap>
798
    NetworkSimplex& supplyMap(const SupplyMap& map) {
806 799
      delete _psupply;
807 800
      _pstsup = false;
808 801
      _psupply = new FlowNodeMap(_graph);
809 802
      for (NodeIt n(_graph); n != INVALID; ++n) {
810 803
        (*_psupply)[n] = map[n];
811 804
      }
812 805
      return *this;
813 806
    }
814 807

	
815 808
    /// \brief Set single source and target nodes and a supply value.
816 809
    ///
817 810
    /// This function sets a single source node and a single target node
818 811
    /// and the required flow value.
819 812
    /// If neither this function nor \ref supplyMap() is used before
820 813
    /// calling \ref run(), the supply of each node will be set to zero.
821 814
    /// (It makes sense only if non-zero lower bounds are given.)
822 815
    ///
816
    /// Using this function has the same effect as using \ref supplyMap()
817
    /// with such a map in which \c k is assigned to \c s, \c -k is
818
    /// assigned to \c t and all other nodes have zero supply value.
819
    ///
823 820
    /// \param s The source node.
824 821
    /// \param t The target node.
825 822
    /// \param k The required amount of flow from node \c s to node \c t
826 823
    /// (i.e. the supply of \c s and the demand of \c t).
827 824
    ///
828 825
    /// \return <tt>(*this)</tt>
829 826
    NetworkSimplex& stSupply(const Node& s, const Node& t, Flow k) {
830 827
      delete _psupply;
831 828
      _psupply = NULL;
832 829
      _pstsup = true;
833 830
      _psource = s;
834 831
      _ptarget = t;
835 832
      _pstflow = k;
836 833
      return *this;
837 834
    }
838 835
    
839
    /// \brief Set the problem type.
836
    /// \brief Set the type of the supply constraints.
840 837
    ///
841
    /// This function sets the problem type for the algorithm.
842
    /// If it is not used before calling \ref run(), the \ref GEQ problem
838
    /// This function sets the type of the supply/demand constraints.
839
    /// If it is not used before calling \ref run(), the \ref GEQ supply
843 840
    /// type will be used.
844 841
    ///
845
    /// For more information see \ref ProblemType.
842
    /// For more information see \ref SupplyType.
846 843
    ///
847 844
    /// \return <tt>(*this)</tt>
848
    NetworkSimplex& problemType(ProblemType problem_type) {
849
      _ptype = problem_type;
845
    NetworkSimplex& supplyType(SupplyType supply_type) {
846
      _stype = supply_type;
850 847
      return *this;
851 848
    }
852 849

	
853 850
    /// \brief Set the flow map.
854 851
    ///
855 852
    /// This function sets the flow map.
856 853
    /// If it is not used before calling \ref run(), an instance will
857 854
    /// be allocated automatically. The destructor deallocates this
858 855
    /// automatically allocated map, of course.
859 856
    ///
860 857
    /// \return <tt>(*this)</tt>
861 858
    NetworkSimplex& flowMap(FlowMap& map) {
862 859
      if (_local_flow) {
863 860
        delete _flow_map;
864 861
        _local_flow = false;
865 862
      }
866 863
      _flow_map = &map;
867 864
      return *this;
868 865
    }
869 866

	
870 867
    /// \brief Set the potential map.
871 868
    ///
872 869
    /// This function sets the potential map, which is used for storing
873 870
    /// the dual solution.
874 871
    /// If it is not used before calling \ref run(), an instance will
875 872
    /// be allocated automatically. The destructor deallocates this
876 873
    /// automatically allocated map, of course.
877 874
    ///
878 875
    /// \return <tt>(*this)</tt>
879 876
    NetworkSimplex& potentialMap(PotentialMap& map) {
880 877
      if (_local_potential) {
881 878
        delete _potential_map;
882 879
        _local_potential = false;
883 880
      }
884 881
      _potential_map = &map;
885 882
      return *this;
886 883
    }
887 884
    
888 885
    /// @}
889 886

	
890 887
    /// \name Execution Control
891 888
    /// The algorithm can be executed using \ref run().
892 889

	
893 890
    /// @{
894 891

	
895 892
    /// \brief Run the algorithm.
896 893
    ///
897 894
    /// This function runs the algorithm.
898 895
    /// The paramters can be specified using functions \ref lowerMap(),
899
    /// \ref upperMap(), \ref capacityMap(), \ref boundMaps(),
900
    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), 
901
    /// \ref problemType(), \ref flowMap() and \ref potentialMap().
896
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(), 
897
    /// \ref supplyType(), \ref flowMap() and \ref potentialMap().
902 898
    /// For example,
903 899
    /// \code
904 900
    ///   NetworkSimplex<ListDigraph> ns(graph);
905
    ///   ns.boundMaps(lower, upper).costMap(cost)
901
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
906 902
    ///     .supplyMap(sup).run();
907 903
    /// \endcode
908 904
    ///
909 905
    /// This function can be called more than once. All the parameters
910 906
    /// that have been given are kept for the next call, unless
911 907
    /// \ref reset() is called, thus only the modified parameters
912 908
    /// have to be set again. See \ref reset() for examples.
913 909
    ///
914 910
    /// \param pivot_rule The pivot rule that will be used during the
915 911
    /// algorithm. For more information see \ref PivotRule.
916 912
    ///
917
    /// \return \c true if a feasible flow can be found.
918
    bool run(PivotRule pivot_rule = BLOCK_SEARCH) {
919
      return init() && start(pivot_rule);
913
    /// \return \c INFEASIBLE if no feasible flow exists,
914
    /// \n \c OPTIMAL if the problem has optimal solution
915
    /// (i.e. it is feasible and bounded), and the algorithm has found
916
    /// optimal flow and node potentials (primal and dual solutions),
917
    /// \n \c UNBOUNDED if the objective function of the problem is
918
    /// unbounded, i.e. there is a directed cycle having negative total
919
    /// cost and infinite upper bound.
920
    ///
921
    /// \see ProblemType, PivotRule
922
    ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
923
      if (!init()) return INFEASIBLE;
924
      return start(pivot_rule);
920 925
    }
921 926

	
922 927
    /// \brief Reset all the parameters that have been given before.
923 928
    ///
924 929
    /// This function resets all the paramaters that have been given
925 930
    /// before using functions \ref lowerMap(), \ref upperMap(),
926
    /// \ref capacityMap(), \ref boundMaps(), \ref costMap(),
927
    /// \ref supplyMap(), \ref stSupply(), \ref problemType(), 
931
    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType(),
928 932
    /// \ref flowMap() and \ref potentialMap().
929 933
    ///
930 934
    /// It is useful for multiple run() calls. If this function is not
931 935
    /// used, all the parameters given before are kept for the next
932 936
    /// \ref run() call.
933 937
    ///
934 938
    /// For example,
935 939
    /// \code
936 940
    ///   NetworkSimplex<ListDigraph> ns(graph);
937 941
    ///
938 942
    ///   // First run
939
    ///   ns.lowerMap(lower).capacityMap(cap).costMap(cost)
943
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
940 944
    ///     .supplyMap(sup).run();
941 945
    ///
942 946
    ///   // Run again with modified cost map (reset() is not called,
943 947
    ///   // so only the cost map have to be set again)
944 948
    ///   cost[e] += 100;
945 949
    ///   ns.costMap(cost).run();
946 950
    ///
947 951
    ///   // Run again from scratch using reset()
948 952
    ///   // (the lower bounds will be set to zero on all arcs)
949 953
    ///   ns.reset();
950
    ///   ns.capacityMap(cap).costMap(cost)
954
    ///   ns.upperMap(capacity).costMap(cost)
951 955
    ///     .supplyMap(sup).run();
952 956
    /// \endcode
953 957
    ///
954 958
    /// \return <tt>(*this)</tt>
955 959
    NetworkSimplex& reset() {
956 960
      delete _plower;
957 961
      delete _pupper;
958 962
      delete _pcost;
959 963
      delete _psupply;
960 964
      _plower = NULL;
961 965
      _pupper = NULL;
962 966
      _pcost = NULL;
963 967
      _psupply = NULL;
964 968
      _pstsup = false;
965
      _ptype = GEQ;
969
      _stype = GEQ;
966 970
      if (_local_flow) delete _flow_map;
967 971
      if (_local_potential) delete _potential_map;
968 972
      _flow_map = NULL;
969 973
      _potential_map = NULL;
970 974
      _local_flow = false;
971 975
      _local_potential = false;
972 976

	
973 977
      return *this;
974 978
    }
975 979

	
976 980
    /// @}
977 981

	
978 982
    /// \name Query Functions
979 983
    /// The results of the algorithm can be obtained using these
980 984
    /// functions.\n
981 985
    /// The \ref run() function must be called before using them.
982 986

	
983 987
    /// @{
984 988

	
985 989
    /// \brief Return the total cost of the found flow.
986 990
    ///
987 991
    /// This function returns the total cost of the found flow.
988
    /// The complexity of the function is O(e).
992
    /// Its complexity is O(e).
989 993
    ///
990 994
    /// \note The return type of the function can be specified as a
991 995
    /// template parameter. For example,
992 996
    /// \code
993 997
    ///   ns.totalCost<double>();
994 998
    /// \endcode
995 999
    /// It is useful if the total cost cannot be stored in the \c Cost
996 1000
    /// type of the algorithm, which is the default return type of the
997 1001
    /// function.
998 1002
    ///
999 1003
    /// \pre \ref run() must be called before using this function.
1000
    template <typename Num>
1001
    Num totalCost() const {
1002
      Num c = 0;
1004
    template <typename Value>
1005
    Value totalCost() const {
1006
      Value c = 0;
1003 1007
      if (_pcost) {
1004 1008
        for (ArcIt e(_graph); e != INVALID; ++e)
1005 1009
          c += (*_flow_map)[e] * (*_pcost)[e];
1006 1010
      } else {
1007 1011
        for (ArcIt e(_graph); e != INVALID; ++e)
1008 1012
          c += (*_flow_map)[e];
1009 1013
      }
1010 1014
      return c;
1011 1015
    }
1012 1016

	
1013 1017
#ifndef DOXYGEN
1014 1018
    Cost totalCost() const {
1015 1019
      return totalCost<Cost>();
1016 1020
    }
1017 1021
#endif
1018 1022

	
1019 1023
    /// \brief Return the flow on the given arc.
1020 1024
    ///
1021 1025
    /// This function returns the flow on the given arc.
1022 1026
    ///
1023 1027
    /// \pre \ref run() must be called before using this function.
1024 1028
    Flow flow(const Arc& a) const {
1025 1029
      return (*_flow_map)[a];
1026 1030
    }
1027 1031

	
1028 1032
    /// \brief Return a const reference to the flow map.
1029 1033
    ///
1030 1034
    /// This function returns a const reference to an arc map storing
1031 1035
    /// the found flow.
1032 1036
    ///
1033 1037
    /// \pre \ref run() must be called before using this function.
1034 1038
    const FlowMap& flowMap() const {
1035 1039
      return *_flow_map;
1036 1040
    }
1037 1041

	
1038 1042
    /// \brief Return the potential (dual value) of the given node.
1039 1043
    ///
1040 1044
    /// This function returns the potential (dual value) of the
1041 1045
    /// given node.
1042 1046
    ///
1043 1047
    /// \pre \ref run() must be called before using this function.
1044 1048
    Cost potential(const Node& n) const {
1045 1049
      return (*_potential_map)[n];
1046 1050
    }
1047 1051

	
1048 1052
    /// \brief Return a const reference to the potential map
1049 1053
    /// (the dual solution).
1050 1054
    ///
1051 1055
    /// This function returns a const reference to a node map storing
1052 1056
    /// the found potentials, which form the dual solution of the
1053
    /// \ref min_cost_flow "minimum cost flow" problem.
1057
    /// \ref min_cost_flow "minimum cost flow problem".
1054 1058
    ///
1055 1059
    /// \pre \ref run() must be called before using this function.
1056 1060
    const PotentialMap& potentialMap() const {
1057 1061
      return *_potential_map;
1058 1062
    }
1059 1063

	
1060 1064
    /// @}
1061 1065

	
1062 1066
  private:
1063 1067

	
1064 1068
    // Initialize internal data structures
1065 1069
    bool init() {
1066 1070
      // Initialize result maps
1067 1071
      if (!_flow_map) {
1068 1072
        _flow_map = new FlowMap(_graph);
1069 1073
        _local_flow = true;
1070 1074
      }
1071 1075
      if (!_potential_map) {
1072 1076
        _potential_map = new PotentialMap(_graph);
1073 1077
        _local_potential = true;
1074 1078
      }
1075 1079

	
1076 1080
      // Initialize vectors
1077 1081
      _node_num = countNodes(_graph);
1078 1082
      _arc_num = countArcs(_graph);
1079 1083
      int all_node_num = _node_num + 1;
1080 1084
      int all_arc_num = _arc_num + _node_num;
1081 1085
      if (_node_num == 0) return false;
1082 1086

	
1083 1087
      _arc_ref.resize(_arc_num);
1084 1088
      _source.resize(all_arc_num);
1085 1089
      _target.resize(all_arc_num);
1086 1090

	
1087 1091
      _cap.resize(all_arc_num);
1088 1092
      _cost.resize(all_arc_num);
1089 1093
      _supply.resize(all_node_num);
1090 1094
      _flow.resize(all_arc_num);
1091 1095
      _pi.resize(all_node_num);
1092 1096

	
1093 1097
      _parent.resize(all_node_num);
1094 1098
      _pred.resize(all_node_num);
1095 1099
      _forward.resize(all_node_num);
1096 1100
      _thread.resize(all_node_num);
1097 1101
      _rev_thread.resize(all_node_num);
1098 1102
      _succ_num.resize(all_node_num);
1099 1103
      _last_succ.resize(all_node_num);
1100 1104
      _state.resize(all_arc_num);
1101 1105

	
1102 1106
      // Initialize node related data
1103 1107
      bool valid_supply = true;
1104
      Flow sum_supply = 0;
1108
      _sum_supply = 0;
1105 1109
      if (!_pstsup && !_psupply) {
1106 1110
        _pstsup = true;
1107 1111
        _psource = _ptarget = NodeIt(_graph);
1108 1112
        _pstflow = 0;
1109 1113
      }
1110 1114
      if (_psupply) {
1111 1115
        int i = 0;
1112 1116
        for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1113 1117
          _node_id[n] = i;
1114 1118
          _supply[i] = (*_psupply)[n];
1115
          sum_supply += _supply[i];
1119
          _sum_supply += _supply[i];
1116 1120
        }
1117
        valid_supply = (_ptype == GEQ && sum_supply <= 0) ||
1118
                       (_ptype == LEQ && sum_supply >= 0);
1121
        valid_supply = (_stype == GEQ && _sum_supply <= 0) ||
1122
                       (_stype == LEQ && _sum_supply >= 0);
1119 1123
      } else {
1120 1124
        int i = 0;
1121 1125
        for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
1122 1126
          _node_id[n] = i;
1123 1127
          _supply[i] = 0;
1124 1128
        }
1125 1129
        _supply[_node_id[_psource]] =  _pstflow;
1126 1130
        _supply[_node_id[_ptarget]] = -_pstflow;
1127 1131
      }
1128 1132
      if (!valid_supply) return false;
1129 1133

	
1130
      // Infinite capacity value
1131
      Flow inf_cap =
1132
        std::numeric_limits<Flow>::has_infinity ?
1133
        std::numeric_limits<Flow>::infinity() :
1134
        std::numeric_limits<Flow>::max();
1135

	
1136 1134
      // Initialize artifical cost
1137
      Cost art_cost;
1135
      Cost ART_COST;
1138 1136
      if (std::numeric_limits<Cost>::is_exact) {
1139
        art_cost = std::numeric_limits<Cost>::max() / 4 + 1;
1137
        ART_COST = std::numeric_limits<Cost>::max() / 4 + 1;
1140 1138
      } else {
1141
        art_cost = std::numeric_limits<Cost>::min();
1139
        ART_COST = std::numeric_limits<Cost>::min();
1142 1140
        for (int i = 0; i != _arc_num; ++i) {
1143
          if (_cost[i] > art_cost) art_cost = _cost[i];
1141
          if (_cost[i] > ART_COST) ART_COST = _cost[i];
1144 1142
        }
1145
        art_cost = (art_cost + 1) * _node_num;
1143
        ART_COST = (ART_COST + 1) * _node_num;
1146 1144
      }
1147 1145

	
1148
      // Run Circulation to check if a feasible solution exists
1149
      typedef ConstMap<Arc, Flow> ConstArcMap;
1150
      ConstArcMap zero_arc_map(0), inf_arc_map(inf_cap);
1151
      FlowNodeMap *csup = NULL;
1152
      bool local_csup = false;
1153
      if (_psupply) {
1154
        csup = _psupply;
1155
      } else {
1156
        csup = new FlowNodeMap(_graph, 0);
1157
        (*csup)[_psource] =  _pstflow;
1158
        (*csup)[_ptarget] = -_pstflow;
1159
        local_csup = true;
1160
      }
1161
      bool circ_result = false;
1162
      if (_ptype == GEQ || (_ptype == LEQ && sum_supply == 0)) {
1163
        // GEQ problem type
1164
        if (_plower) {
1165
          if (_pupper) {
1166
            Circulation<GR, FlowArcMap, FlowArcMap, FlowNodeMap>
1167
              circ(_graph, *_plower, *_pupper, *csup);
1168
            circ_result = circ.run();
1169
          } else {
1170
            Circulation<GR, FlowArcMap, ConstArcMap, FlowNodeMap>
1171
              circ(_graph, *_plower, inf_arc_map, *csup);
1172
            circ_result = circ.run();
1173
          }
1174
        } else {
1175
          if (_pupper) {
1176
            Circulation<GR, ConstArcMap, FlowArcMap, FlowNodeMap>
1177
              circ(_graph, zero_arc_map, *_pupper, *csup);
1178
            circ_result = circ.run();
1179
          } else {
1180
            Circulation<GR, ConstArcMap, ConstArcMap, FlowNodeMap>
1181
              circ(_graph, zero_arc_map, inf_arc_map, *csup);
1182
            circ_result = circ.run();
1183
          }
1184
        }
1185
      } else {
1186
        // LEQ problem type
1187
        typedef ReverseDigraph<const GR> RevGraph;
1188
        typedef NegMap<FlowNodeMap> NegNodeMap;
1189
        RevGraph rgraph(_graph);
1190
        NegNodeMap neg_csup(*csup);
1191
        if (_plower) {
1192
          if (_pupper) {
1193
            Circulation<RevGraph, FlowArcMap, FlowArcMap, NegNodeMap>
1194
              circ(rgraph, *_plower, *_pupper, neg_csup);
1195
            circ_result = circ.run();
1196
          } else {
1197
            Circulation<RevGraph, FlowArcMap, ConstArcMap, NegNodeMap>
1198
              circ(rgraph, *_plower, inf_arc_map, neg_csup);
1199
            circ_result = circ.run();
1200
          }
1201
        } else {
1202
          if (_pupper) {
1203
            Circulation<RevGraph, ConstArcMap, FlowArcMap, NegNodeMap>
1204
              circ(rgraph, zero_arc_map, *_pupper, neg_csup);
1205
            circ_result = circ.run();
1206
          } else {
1207
            Circulation<RevGraph, ConstArcMap, ConstArcMap, NegNodeMap>
1208
              circ(rgraph, zero_arc_map, inf_arc_map, neg_csup);
1209
            circ_result = circ.run();
1210
          }
1211
        }
1212
      }
1213
      if (local_csup) delete csup;
1214
      if (!circ_result) return false;
1215

	
1216 1146
      // Set data for the artificial root node
1217 1147
      _root = _node_num;
1218 1148
      _parent[_root] = -1;
1219 1149
      _pred[_root] = -1;
1220 1150
      _thread[_root] = 0;
1221 1151
      _rev_thread[0] = _root;
1222 1152
      _succ_num[_root] = all_node_num;
1223 1153
      _last_succ[_root] = _root - 1;
1224
      _supply[_root] = -sum_supply;
1225
      if (sum_supply < 0) {
1226
        _pi[_root] = -art_cost;
1154
      _supply[_root] = -_sum_supply;
1155
      if (_sum_supply < 0) {
1156
        _pi[_root] = -ART_COST;
1227 1157
      } else {
1228
        _pi[_root] = art_cost;
1158
        _pi[_root] = ART_COST;
1229 1159
      }
1230 1160

	
1231 1161
      // Store the arcs in a mixed order
1232 1162
      int k = std::max(int(std::sqrt(double(_arc_num))), 10);
1233 1163
      int i = 0;
1234 1164
      for (ArcIt e(_graph); e != INVALID; ++e) {
1235 1165
        _arc_ref[i] = e;
1236 1166
        if ((i += k) >= _arc_num) i = (i % k) + 1;
1237 1167
      }
1238 1168

	
1239 1169
      // Initialize arc maps
1240 1170
      if (_pupper && _pcost) {
1241 1171
        for (int i = 0; i != _arc_num; ++i) {
1242 1172
          Arc e = _arc_ref[i];
1243 1173
          _source[i] = _node_id[_graph.source(e)];
1244 1174
          _target[i] = _node_id[_graph.target(e)];
1245 1175
          _cap[i] = (*_pupper)[e];
1246 1176
          _cost[i] = (*_pcost)[e];
1247 1177
          _flow[i] = 0;
1248 1178
          _state[i] = STATE_LOWER;
1249 1179
        }
1250 1180
      } else {
1251 1181
        for (int i = 0; i != _arc_num; ++i) {
1252 1182
          Arc e = _arc_ref[i];
1253 1183
          _source[i] = _node_id[_graph.source(e)];
1254 1184
          _target[i] = _node_id[_graph.target(e)];
1255 1185
          _flow[i] = 0;
1256 1186
          _state[i] = STATE_LOWER;
1257 1187
        }
1258 1188
        if (_pupper) {
1259 1189
          for (int i = 0; i != _arc_num; ++i)
1260 1190
            _cap[i] = (*_pupper)[_arc_ref[i]];
1261 1191
        } else {
1262 1192
          for (int i = 0; i != _arc_num; ++i)
1263
            _cap[i] = inf_cap;
1193
            _cap[i] = INF;
1264 1194
        }
1265 1195
        if (_pcost) {
1266 1196
          for (int i = 0; i != _arc_num; ++i)
1267 1197
            _cost[i] = (*_pcost)[_arc_ref[i]];
1268 1198
        } else {
1269 1199
          for (int i = 0; i != _arc_num; ++i)
1270 1200
            _cost[i] = 1;
1271 1201
        }
1272 1202
      }
1273 1203
      
1274 1204
      // Remove non-zero lower bounds
1275 1205
      if (_plower) {
1276 1206
        for (int i = 0; i != _arc_num; ++i) {
1277 1207
          Flow c = (*_plower)[_arc_ref[i]];
1278
          if (c != 0) {
1279
            _cap[i] -= c;
1208
          if (c > 0) {
1209
            if (_cap[i] < INF) _cap[i] -= c;
1210
            _supply[_source[i]] -= c;
1211
            _supply[_target[i]] += c;
1212
          }
1213
          else if (c < 0) {
1214
            if (_cap[i] < INF + c) {
1215
              _cap[i] -= c;
1216
            } else {
1217
              _cap[i] = INF;
1218
            }
1280 1219
            _supply[_source[i]] -= c;
1281 1220
            _supply[_target[i]] += c;
1282 1221
          }
1283 1222
        }
1284 1223
      }
1285 1224

	
1286 1225
      // Add artificial arcs and initialize the spanning tree data structure
1287 1226
      for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1288 1227
        _thread[u] = u + 1;
1289 1228
        _rev_thread[u + 1] = u;
1290 1229
        _succ_num[u] = 1;
1291 1230
        _last_succ[u] = u;
1292 1231
        _parent[u] = _root;
1293 1232
        _pred[u] = e;
1294
        _cost[e] = art_cost;
1295
        _cap[e] = inf_cap;
1233
        _cost[e] = ART_COST;
1234
        _cap[e] = INF;
1296 1235
        _state[e] = STATE_TREE;
1297
        if (_supply[u] > 0 || (_supply[u] == 0 && sum_supply <= 0)) {
1236
        if (_supply[u] > 0 || (_supply[u] == 0 && _sum_supply <= 0)) {
1298 1237
          _flow[e] = _supply[u];
1299 1238
          _forward[u] = true;
1300
          _pi[u] = -art_cost + _pi[_root];
1239
          _pi[u] = -ART_COST + _pi[_root];
1301 1240
        } else {
1302 1241
          _flow[e] = -_supply[u];
1303 1242
          _forward[u] = false;
1304
          _pi[u] = art_cost + _pi[_root];
1243
          _pi[u] = ART_COST + _pi[_root];
1305 1244
        }
1306 1245
      }
1307 1246

	
1308 1247
      return true;
1309 1248
    }
1310 1249

	
1311 1250
    // Find the join node
1312 1251
    void findJoinNode() {
1313 1252
      int u = _source[in_arc];
1314 1253
      int v = _target[in_arc];
1315 1254
      while (u != v) {
1316 1255
        if (_succ_num[u] < _succ_num[v]) {
1317 1256
          u = _parent[u];
1318 1257
        } else {
1319 1258
          v = _parent[v];
1320 1259
        }
1321 1260
      }
1322 1261
      join = u;
1323 1262
    }
1324 1263

	
1325 1264
    // Find the leaving arc of the cycle and returns true if the
1326 1265
    // leaving arc is not the same as the entering arc
1327 1266
    bool findLeavingArc() {
1328 1267
      // Initialize first and second nodes according to the direction
1329 1268
      // of the cycle
1330 1269
      if (_state[in_arc] == STATE_LOWER) {
1331 1270
        first  = _source[in_arc];
1332 1271
        second = _target[in_arc];
1333 1272
      } else {
1334 1273
        first  = _target[in_arc];
1335 1274
        second = _source[in_arc];
1336 1275
      }
1337 1276
      delta = _cap[in_arc];
1338 1277
      int result = 0;
1339 1278
      Flow d;
1340 1279
      int e;
1341 1280

	
1342 1281
      // Search the cycle along the path form the first node to the root
1343 1282
      for (int u = first; u != join; u = _parent[u]) {
1344 1283
        e = _pred[u];
1345
        d = _forward[u] ? _flow[e] : _cap[e] - _flow[e];
1284
        d = _forward[u] ?
1285
          _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1346 1286
        if (d < delta) {
1347 1287
          delta = d;
1348 1288
          u_out = u;
1349 1289
          result = 1;
1350 1290
        }
1351 1291
      }
1352 1292
      // Search the cycle along the path form the second node to the root
1353 1293
      for (int u = second; u != join; u = _parent[u]) {
1354 1294
        e = _pred[u];
1355
        d = _forward[u] ? _cap[e] - _flow[e] : _flow[e];
1295
        d = _forward[u] ? 
1296
          (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1356 1297
        if (d <= delta) {
1357 1298
          delta = d;
1358 1299
          u_out = u;
1359 1300
          result = 2;
1360 1301
        }
1361 1302
      }
1362 1303

	
1363 1304
      if (result == 1) {
1364 1305
        u_in = first;
1365 1306
        v_in = second;
1366 1307
      } else {
1367 1308
        u_in = second;
1368 1309
        v_in = first;
1369 1310
      }
1370 1311
      return result != 0;
1371 1312
    }
1372 1313

	
1373 1314
    // Change _flow and _state vectors
1374 1315
    void changeFlow(bool change) {
1375 1316
      // Augment along the cycle
1376 1317
      if (delta > 0) {
1377 1318
        Flow val = _state[in_arc] * delta;
1378 1319
        _flow[in_arc] += val;
1379 1320
        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1380 1321
          _flow[_pred[u]] += _forward[u] ? -val : val;
1381 1322
        }
1382 1323
        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1383 1324
          _flow[_pred[u]] += _forward[u] ? val : -val;
1384 1325
        }
1385 1326
      }
1386 1327
      // Update the state of the entering and leaving arcs
1387 1328
      if (change) {
1388 1329
        _state[in_arc] = STATE_TREE;
1389 1330
        _state[_pred[u_out]] =
1390 1331
          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1391 1332
      } else {
1392 1333
        _state[in_arc] = -_state[in_arc];
1393 1334
      }
1394 1335
    }
1395 1336

	
1396 1337
    // Update the tree structure
1397 1338
    void updateTreeStructure() {
1398 1339
      int u, w;
1399 1340
      int old_rev_thread = _rev_thread[u_out];
1400 1341
      int old_succ_num = _succ_num[u_out];
1401 1342
      int old_last_succ = _last_succ[u_out];
1402 1343
      v_out = _parent[u_out];
1403 1344

	
1404 1345
      u = _last_succ[u_in];  // the last successor of u_in
1405 1346
      right = _thread[u];    // the node after it
1406 1347

	
1407 1348
      // Handle the case when old_rev_thread equals to v_in
1408 1349
      // (it also means that join and v_out coincide)
1409 1350
      if (old_rev_thread == v_in) {
1410 1351
        last = _thread[_last_succ[u_out]];
1411 1352
      } else {
1412 1353
        last = _thread[v_in];
1413 1354
      }
1414 1355

	
1415 1356
      // Update _thread and _parent along the stem nodes (i.e. the nodes
1416 1357
      // between u_in and u_out, whose parent have to be changed)
1417 1358
      _thread[v_in] = stem = u_in;
1418 1359
      _dirty_revs.clear();
1419 1360
      _dirty_revs.push_back(v_in);
1420 1361
      par_stem = v_in;
1421 1362
      while (stem != u_out) {
1422 1363
        // Insert the next stem node into the thread list
1423 1364
        new_stem = _parent[stem];
1424 1365
        _thread[u] = new_stem;
1425 1366
        _dirty_revs.push_back(u);
1426 1367

	
1427 1368
        // Remove the subtree of stem from the thread list
1428 1369
        w = _rev_thread[stem];
1429 1370
        _thread[w] = right;
1430 1371
        _rev_thread[right] = w;
1431 1372

	
1432 1373
        // Change the parent node and shift stem nodes
1433 1374
        _parent[stem] = par_stem;
1434 1375
        par_stem = stem;
1435 1376
        stem = new_stem;
1436 1377

	
1437 1378
        // Update u and right
1438 1379
        u = _last_succ[stem] == _last_succ[par_stem] ?
1439 1380
          _rev_thread[par_stem] : _last_succ[stem];
1440 1381
        right = _thread[u];
1441 1382
      }
1442 1383
      _parent[u_out] = par_stem;
1443 1384
      _thread[u] = last;
1444 1385
      _rev_thread[last] = u;
1445 1386
      _last_succ[u_out] = u;
1446 1387

	
1447 1388
      // Remove the subtree of u_out from the thread list except for
1448 1389
      // the case when old_rev_thread equals to v_in
1449 1390
      // (it also means that join and v_out coincide)
1450 1391
      if (old_rev_thread != v_in) {
1451 1392
        _thread[old_rev_thread] = right;
1452 1393
        _rev_thread[right] = old_rev_thread;
1453 1394
      }
1454 1395

	
1455 1396
      // Update _rev_thread using the new _thread values
1456 1397
      for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1457 1398
        u = _dirty_revs[i];
1458 1399
        _rev_thread[_thread[u]] = u;
1459 1400
      }
1460 1401

	
1461 1402
      // Update _pred, _forward, _last_succ and _succ_num for the
1462 1403
      // stem nodes from u_out to u_in
1463 1404
      int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1464 1405
      u = u_out;
1465 1406
      while (u != u_in) {
1466 1407
        w = _parent[u];
1467 1408
        _pred[u] = _pred[w];
1468 1409
        _forward[u] = !_forward[w];
1469 1410
        tmp_sc += _succ_num[u] - _succ_num[w];
1470 1411
        _succ_num[u] = tmp_sc;
1471 1412
        _last_succ[w] = tmp_ls;
1472 1413
        u = w;
1473 1414
      }
1474 1415
      _pred[u_in] = in_arc;
1475 1416
      _forward[u_in] = (u_in == _source[in_arc]);
1476 1417
      _succ_num[u_in] = old_succ_num;
1477 1418

	
1478 1419
      // Set limits for updating _last_succ form v_in and v_out
1479 1420
      // towards the root
1480 1421
      int up_limit_in = -1;
1481 1422
      int up_limit_out = -1;
1482 1423
      if (_last_succ[join] == v_in) {
1483 1424
        up_limit_out = join;
1484 1425
      } else {
1485 1426
        up_limit_in = join;
1486 1427
      }
1487 1428

	
1488 1429
      // Update _last_succ from v_in towards the root
1489 1430
      for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1490 1431
           u = _parent[u]) {
1491 1432
        _last_succ[u] = _last_succ[u_out];
1492 1433
      }
1493 1434
      // Update _last_succ from v_out towards the root
1494 1435
      if (join != old_rev_thread && v_in != old_rev_thread) {
1495 1436
        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1496 1437
             u = _parent[u]) {
1497 1438
          _last_succ[u] = old_rev_thread;
1498 1439
        }
1499 1440
      } else {
1500 1441
        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1501 1442
             u = _parent[u]) {
1502 1443
          _last_succ[u] = _last_succ[u_out];
1503 1444
        }
1504 1445
      }
1505 1446

	
1506 1447
      // Update _succ_num from v_in to join
1507 1448
      for (u = v_in; u != join; u = _parent[u]) {
1508 1449
        _succ_num[u] += old_succ_num;
1509 1450
      }
1510 1451
      // Update _succ_num from v_out to join
1511 1452
      for (u = v_out; u != join; u = _parent[u]) {
1512 1453
        _succ_num[u] -= old_succ_num;
1513 1454
      }
1514 1455
    }
1515 1456

	
1516 1457
    // Update potentials
1517 1458
    void updatePotential() {
1518 1459
      Cost sigma = _forward[u_in] ?
1519 1460
        _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1520 1461
        _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1521 1462
      // Update potentials in the subtree, which has been moved
1522 1463
      int end = _thread[_last_succ[u_in]];
1523 1464
      for (int u = u_in; u != end; u = _thread[u]) {
1524 1465
        _pi[u] += sigma;
1525 1466
      }
1526 1467
    }
1527 1468

	
1528 1469
    // Execute the algorithm
1529
    bool start(PivotRule pivot_rule) {
1470
    ProblemType start(PivotRule pivot_rule) {
1530 1471
      // Select the pivot rule implementation
1531 1472
      switch (pivot_rule) {
1532 1473
        case FIRST_ELIGIBLE:
1533 1474
          return start<FirstEligiblePivotRule>();
1534 1475
        case BEST_ELIGIBLE:
1535 1476
          return start<BestEligiblePivotRule>();
1536 1477
        case BLOCK_SEARCH:
1537 1478
          return start<BlockSearchPivotRule>();
1538 1479
        case CANDIDATE_LIST:
1539 1480
          return start<CandidateListPivotRule>();
1540 1481
        case ALTERING_LIST:
1541 1482
          return start<AlteringListPivotRule>();
1542 1483
      }
1543
      return false;
1484
      return INFEASIBLE; // avoid warning
1544 1485
    }
1545 1486

	
1546 1487
    template <typename PivotRuleImpl>
1547
    bool start() {
1488
    ProblemType start() {
1548 1489
      PivotRuleImpl pivot(*this);
1549 1490

	
1550 1491
      // Execute the Network Simplex algorithm
1551 1492
      while (pivot.findEnteringArc()) {
1552 1493
        findJoinNode();
1553 1494
        bool change = findLeavingArc();
1495
        if (delta >= INF) return UNBOUNDED;
1554 1496
        changeFlow(change);
1555 1497
        if (change) {
1556 1498
          updateTreeStructure();
1557 1499
          updatePotential();
1558 1500
        }
1559 1501
      }
1502
      
1503
      // Check feasibility
1504
      if (_sum_supply < 0) {
1505
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1506
          if (_supply[u] >= 0 && _flow[e] != 0) return INFEASIBLE;
1507
        }
1508
      }
1509
      else if (_sum_supply > 0) {
1510
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1511
          if (_supply[u] <= 0 && _flow[e] != 0) return INFEASIBLE;
1512
        }
1513
      }
1514
      else {
1515
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1516
          if (_flow[e] != 0) return INFEASIBLE;
1517
        }
1518
      }
1560 1519

	
1561 1520
      // Copy flow values to _flow_map
1562 1521
      if (_plower) {
1563 1522
        for (int i = 0; i != _arc_num; ++i) {
1564 1523
          Arc e = _arc_ref[i];
1565 1524
          _flow_map->set(e, (*_plower)[e] + _flow[i]);
1566 1525
        }
1567 1526
      } else {
1568 1527
        for (int i = 0; i != _arc_num; ++i) {
1569 1528
          _flow_map->set(_arc_ref[i], _flow[i]);
1570 1529
        }
1571 1530
      }
1572 1531
      // Copy potential values to _potential_map
1573 1532
      for (NodeIt n(_graph); n != INVALID; ++n) {
1574 1533
        _potential_map->set(n, _pi[_node_id[n]]);
1575 1534
      }
1576 1535

	
1577
      return true;
1536
      return OPTIMAL;
1578 1537
    }
1579 1538

	
1580 1539
  }; //class NetworkSimplex
1581 1540

	
1582 1541
  ///@}
1583 1542

	
1584 1543
} //namespace lemon
1585 1544

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

	
19 19
#include <iostream>
20 20
#include <fstream>
21
#include <limits>
21 22

	
22 23
#include <lemon/list_graph.h>
23 24
#include <lemon/lgf_reader.h>
24 25

	
25 26
#include <lemon/network_simplex.h>
26 27

	
27 28
#include <lemon/concepts/digraph.h>
28 29
#include <lemon/concept_check.h>
29 30

	
30 31
#include "test_tools.h"
31 32

	
32 33
using namespace lemon;
33 34

	
34 35
char test_lgf[] =
35 36
  "@nodes\n"
36
  "label  sup1 sup2 sup3 sup4 sup5\n"
37
  "    1    20   27    0   20   30\n"
38
  "    2    -4    0    0   -8   -3\n"
39
  "    3     0    0    0    0    0\n"
40
  "    4     0    0    0    0    0\n"
41
  "    5     9    0    0    6   11\n"
42
  "    6    -6    0    0   -5   -6\n"
43
  "    7     0    0    0    0    0\n"
44
  "    8     0    0    0    0    3\n"
45
  "    9     3    0    0    0    0\n"
46
  "   10    -2    0    0   -7   -2\n"
47
  "   11     0    0    0  -10    0\n"
48
  "   12   -20  -27    0  -30  -20\n"
49
  "\n"
37
  "label  sup1 sup2 sup3 sup4 sup5 sup6\n"
38
  "    1    20   27    0   30   20   30\n"
39
  "    2    -4    0    0    0   -8   -3\n"
40
  "    3     0    0    0    0    0    0\n"
41
  "    4     0    0    0    0    0    0\n"
42
  "    5     9    0    0    0    6   11\n"
43
  "    6    -6    0    0    0   -5   -6\n"
44
  "    7     0    0    0    0    0    0\n"
45
  "    8     0    0    0    0    0    3\n"
46
  "    9     3    0    0    0    0    0\n"
47
  "   10    -2    0    0    0   -7   -2\n"
48
  "   11     0    0    0    0  -10    0\n"
49
  "   12   -20  -27    0  -30  -30  -20\n"
50
  "\n"                
50 51
  "@arcs\n"
51
  "       cost  cap low1 low2\n"
52
  " 1  2    70   11    0    8\n"
53
  " 1  3   150    3    0    1\n"
54
  " 1  4    80   15    0    2\n"
55
  " 2  8    80   12    0    0\n"
56
  " 3  5   140    5    0    3\n"
57
  " 4  6    60   10    0    1\n"
58
  " 4  7    80    2    0    0\n"
59
  " 4  8   110    3    0    0\n"
60
  " 5  7    60   14    0    0\n"
61
  " 5 11   120   12    0    0\n"
62
  " 6  3     0    3    0    0\n"
63
  " 6  9   140    4    0    0\n"
64
  " 6 10    90    8    0    0\n"
65
  " 7  1    30    5    0    0\n"
66
  " 8 12    60   16    0    4\n"
67
  " 9 12    50    6    0    0\n"
68
  "10 12    70   13    0    5\n"
69
  "10  2   100    7    0    0\n"
70
  "10  7    60   10    0    0\n"
71
  "11 10    20   14    0    6\n"
72
  "12 11    30   10    0    0\n"
52
  "       cost  cap low1 low2 low3\n"
53
  " 1  2    70   11    0    8    8\n"
54
  " 1  3   150    3    0    1    0\n"
55
  " 1  4    80   15    0    2    2\n"
56
  " 2  8    80   12    0    0    0\n"
57
  " 3  5   140    5    0    3    1\n"
58
  " 4  6    60   10    0    1    0\n"
59
  " 4  7    80    2    0    0    0\n"
60
  " 4  8   110    3    0    0    0\n"
61
  " 5  7    60   14    0    0    0\n"
62
  " 5 11   120   12    0    0    0\n"
63
  " 6  3     0    3    0    0    0\n"
64
  " 6  9   140    4    0    0    0\n"
65
  " 6 10    90    8    0    0    0\n"
66
  " 7  1    30    5    0    0   -5\n"
67
  " 8 12    60   16    0    4    3\n"
68
  " 9 12    50    6    0    0    0\n"
69
  "10 12    70   13    0    5    2\n"
70
  "10  2   100    7    0    0    0\n"
71
  "10  7    60   10    0    0   -3\n"
72
  "11 10    20   14    0    6  -20\n"
73
  "12 11    30   10    0    0  -10\n"
73 74
  "\n"
74 75
  "@attributes\n"
75 76
  "source 1\n"
76 77
  "target 12\n";
77 78

	
78 79

	
79
enum ProblemType {
80
enum SupplyType {
80 81
  EQ,
81 82
  GEQ,
82 83
  LEQ
83 84
};
84 85

	
85 86
// Check the interface of an MCF algorithm
86 87
template <typename GR, typename Flow, typename Cost>
87 88
class McfClassConcept
88 89
{
89 90
public:
90 91

	
91 92
  template <typename MCF>
92 93
  struct Constraints {
93 94
    void constraints() {
94 95
      checkConcept<concepts::Digraph, GR>();
95 96

	
96 97
      MCF mcf(g);
97 98

	
98 99
      b = mcf.reset()
99 100
             .lowerMap(lower)
100 101
             .upperMap(upper)
101
             .capacityMap(upper)
102
             .boundMaps(lower, upper)
103 102
             .costMap(cost)
104 103
             .supplyMap(sup)
105 104
             .stSupply(n, n, k)
106 105
             .flowMap(flow)
107 106
             .potentialMap(pot)
108 107
             .run();
109 108
      
110 109
      const MCF& const_mcf = mcf;
111 110

	
112 111
      const typename MCF::FlowMap &fm = const_mcf.flowMap();
113 112
      const typename MCF::PotentialMap &pm = const_mcf.potentialMap();
114 113

	
115
      v = const_mcf.totalCost();
114
      c = const_mcf.totalCost();
116 115
      double x = const_mcf.template totalCost<double>();
117 116
      v = const_mcf.flow(a);
118
      v = const_mcf.potential(n);
117
      c = const_mcf.potential(n);
118
      
119
      v = const_mcf.INF;
119 120

	
120 121
      ignore_unused_variable_warning(fm);
121 122
      ignore_unused_variable_warning(pm);
122 123
      ignore_unused_variable_warning(x);
123 124
    }
124 125

	
125 126
    typedef typename GR::Node Node;
126 127
    typedef typename GR::Arc Arc;
127 128
    typedef concepts::ReadMap<Node, Flow> NM;
128 129
    typedef concepts::ReadMap<Arc, Flow> FAM;
129 130
    typedef concepts::ReadMap<Arc, Cost> CAM;
130 131

	
131 132
    const GR &g;
132 133
    const FAM &lower;
133 134
    const FAM &upper;
134 135
    const CAM &cost;
135 136
    const NM &sup;
136 137
    const Node &n;
137 138
    const Arc &a;
138 139
    const Flow &k;
139 140
    Flow v;
141
    Cost c;
140 142
    bool b;
141 143

	
142 144
    typename MCF::FlowMap &flow;
143 145
    typename MCF::PotentialMap &pot;
144 146
  };
145 147

	
146 148
};
147 149

	
148 150

	
149 151
// Check the feasibility of the given flow (primal soluiton)
150 152
template < typename GR, typename LM, typename UM,
151 153
           typename SM, typename FM >
152 154
bool checkFlow( const GR& gr, const LM& lower, const UM& upper,
153 155
                const SM& supply, const FM& flow,
154
                ProblemType type = EQ )
156
                SupplyType type = EQ )
155 157
{
156 158
  TEMPLATE_DIGRAPH_TYPEDEFS(GR);
157 159

	
158 160
  for (ArcIt e(gr); e != INVALID; ++e) {
159 161
    if (flow[e] < lower[e] || flow[e] > upper[e]) return false;
160 162
  }
161 163

	
162 164
  for (NodeIt n(gr); n != INVALID; ++n) {
163 165
    typename SM::Value sum = 0;
164 166
    for (OutArcIt e(gr, n); e != INVALID; ++e)
165 167
      sum += flow[e];
166 168
    for (InArcIt e(gr, n); e != INVALID; ++e)
167 169
      sum -= flow[e];
168 170
    bool b = (type ==  EQ && sum == supply[n]) ||
169 171
             (type == GEQ && sum >= supply[n]) ||
170 172
             (type == LEQ && sum <= supply[n]);
171 173
    if (!b) return false;
172 174
  }
173 175

	
174 176
  return true;
175 177
}
176 178

	
177 179
// Check the feasibility of the given potentials (dual soluiton)
178 180
// using the "Complementary Slackness" optimality condition
179 181
template < typename GR, typename LM, typename UM,
180 182
           typename CM, typename SM, typename FM, typename PM >
181 183
bool checkPotential( const GR& gr, const LM& lower, const UM& upper,
182 184
                     const CM& cost, const SM& supply, const FM& flow, 
183 185
                     const PM& pi )
184 186
{
185 187
  TEMPLATE_DIGRAPH_TYPEDEFS(GR);
186 188

	
187 189
  bool opt = true;
188 190
  for (ArcIt e(gr); opt && e != INVALID; ++e) {
189 191
    typename CM::Value red_cost =
190 192
      cost[e] + pi[gr.source(e)] - pi[gr.target(e)];
191 193
    opt = red_cost == 0 ||
192 194
          (red_cost > 0 && flow[e] == lower[e]) ||
193 195
          (red_cost < 0 && flow[e] == upper[e]);
194 196
  }
195 197
  
196 198
  for (NodeIt n(gr); opt && n != INVALID; ++n) {
197 199
    typename SM::Value sum = 0;
198 200
    for (OutArcIt e(gr, n); e != INVALID; ++e)
199 201
      sum += flow[e];
200 202
    for (InArcIt e(gr, n); e != INVALID; ++e)
201 203
      sum -= flow[e];
202 204
    opt = (sum == supply[n]) || (pi[n] == 0);
203 205
  }
204 206
  
205 207
  return opt;
206 208
}
207 209

	
208 210
// Run a minimum cost flow algorithm and check the results
209 211
template < typename MCF, typename GR,
210 212
           typename LM, typename UM,
211
           typename CM, typename SM >
212
void checkMcf( const MCF& mcf, bool mcf_result,
213
           typename CM, typename SM,
214
           typename PT >
215
void checkMcf( const MCF& mcf, PT mcf_result,
213 216
               const GR& gr, const LM& lower, const UM& upper,
214 217
               const CM& cost, const SM& supply,
215
               bool result, typename CM::Value total,
218
               PT result, bool optimal, typename CM::Value total,
216 219
               const std::string &test_id = "",
217
               ProblemType type = EQ )
220
               SupplyType type = EQ )
218 221
{
219 222
  check(mcf_result == result, "Wrong result " + test_id);
220
  if (result) {
223
  if (optimal) {
221 224
    check(checkFlow(gr, lower, upper, supply, mcf.flowMap(), type),
222 225
          "The flow is not feasible " + test_id);
223 226
    check(mcf.totalCost() == total, "The flow is not optimal " + test_id);
224 227
    check(checkPotential(gr, lower, upper, cost, supply, mcf.flowMap(),
225 228
                         mcf.potentialMap()),
226 229
          "Wrong potentials " + test_id);
227 230
  }
228 231
}
229 232

	
230 233
int main()
231 234
{
232 235
  // Check the interfaces
233 236
  {
234 237
    typedef int Flow;
235 238
    typedef int Cost;
236 239
    typedef concepts::Digraph GR;
237 240
    checkConcept< McfClassConcept<GR, Flow, Cost>,
238 241
                  NetworkSimplex<GR, Flow, Cost> >();
239 242
  }
240 243

	
241 244
  // Run various MCF tests
242 245
  typedef ListDigraph Digraph;
243 246
  DIGRAPH_TYPEDEFS(ListDigraph);
244 247

	
245 248
  // Read the test digraph
246 249
  Digraph gr;
247
  Digraph::ArcMap<int> c(gr), l1(gr), l2(gr), u(gr);
248
  Digraph::NodeMap<int> s1(gr), s2(gr), s3(gr), s4(gr), s5(gr);
250
  Digraph::ArcMap<int> c(gr), l1(gr), l2(gr), l3(gr), u(gr);
251
  Digraph::NodeMap<int> s1(gr), s2(gr), s3(gr), s4(gr), s5(gr), s6(gr);
249 252
  ConstMap<Arc, int> cc(1), cu(std::numeric_limits<int>::max());
250 253
  Node v, w;
251 254

	
252 255
  std::istringstream input(test_lgf);
253 256
  DigraphReader<Digraph>(gr, input)
254 257
    .arcMap("cost", c)
255 258
    .arcMap("cap", u)
256 259
    .arcMap("low1", l1)
257 260
    .arcMap("low2", l2)
261
    .arcMap("low3", l3)
258 262
    .nodeMap("sup1", s1)
259 263
    .nodeMap("sup2", s2)
260 264
    .nodeMap("sup3", s3)
261 265
    .nodeMap("sup4", s4)
262 266
    .nodeMap("sup5", s5)
267
    .nodeMap("sup6", s6)
263 268
    .node("source", v)
264 269
    .node("target", w)
265 270
    .run();
271
  
272
  // Build a test digraph for testing negative costs
273
  Digraph ngr;
274
  Node n1 = ngr.addNode();
275
  Node n2 = ngr.addNode();
276
  Node n3 = ngr.addNode();
277
  Node n4 = ngr.addNode();
278
  Node n5 = ngr.addNode();
279
  Node n6 = ngr.addNode();
280
  Node n7 = ngr.addNode();
281
  
282
  Arc a1 = ngr.addArc(n1, n2);
283
  Arc a2 = ngr.addArc(n1, n3);
284
  Arc a3 = ngr.addArc(n2, n4);
285
  Arc a4 = ngr.addArc(n3, n4);
286
  Arc a5 = ngr.addArc(n3, n2);
287
  Arc a6 = ngr.addArc(n5, n3);
288
  Arc a7 = ngr.addArc(n5, n6);
289
  Arc a8 = ngr.addArc(n6, n7);
290
  Arc a9 = ngr.addArc(n7, n5);
291
  
292
  Digraph::ArcMap<int> nc(ngr), nl1(ngr, 0), nl2(ngr, 0);
293
  ConstMap<Arc, int> nu1(std::numeric_limits<int>::max()), nu2(5000);
294
  Digraph::NodeMap<int> ns(ngr, 0);
295
  
296
  nl2[a7] =  1000;
297
  nl2[a8] = -1000;
298
  
299
  ns[n1] =  100;
300
  ns[n4] = -100;
301
  
302
  nc[a1] =  100;
303
  nc[a2] =   30;
304
  nc[a3] =   20;
305
  nc[a4] =   80;
306
  nc[a5] =   50;
307
  nc[a6] =   10;
308
  nc[a7] =   80;
309
  nc[a8] =   30;
310
  nc[a9] = -120;
266 311

	
267 312
  // A. Test NetworkSimplex with the default pivot rule
268 313
  {
269 314
    NetworkSimplex<Digraph> mcf(gr);
270 315

	
271 316
    // Check the equality form
272 317
    mcf.upperMap(u).costMap(c);
273 318
    checkMcf(mcf, mcf.supplyMap(s1).run(),
274
             gr, l1, u, c, s1, true,  5240, "#A1");
319
             gr, l1, u, c, s1, mcf.OPTIMAL, true,   5240, "#A1");
275 320
    checkMcf(mcf, mcf.stSupply(v, w, 27).run(),
276
             gr, l1, u, c, s2, true,  7620, "#A2");
321
             gr, l1, u, c, s2, mcf.OPTIMAL, true,   7620, "#A2");
277 322
    mcf.lowerMap(l2);
278 323
    checkMcf(mcf, mcf.supplyMap(s1).run(),
279
             gr, l2, u, c, s1, true,  5970, "#A3");
324
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#A3");
280 325
    checkMcf(mcf, mcf.stSupply(v, w, 27).run(),
281
             gr, l2, u, c, s2, true,  8010, "#A4");
326
             gr, l2, u, c, s2, mcf.OPTIMAL, true,   8010, "#A4");
282 327
    mcf.reset();
283 328
    checkMcf(mcf, mcf.supplyMap(s1).run(),
284
             gr, l1, cu, cc, s1, true,  74, "#A5");
329
             gr, l1, cu, cc, s1, mcf.OPTIMAL, true,   74, "#A5");
285 330
    checkMcf(mcf, mcf.lowerMap(l2).stSupply(v, w, 27).run(),
286
             gr, l2, cu, cc, s2, true,  94, "#A6");
331
             gr, l2, cu, cc, s2, mcf.OPTIMAL, true,   94, "#A6");
287 332
    mcf.reset();
288 333
    checkMcf(mcf, mcf.run(),
289
             gr, l1, cu, cc, s3, true,   0, "#A7");
290
    checkMcf(mcf, mcf.boundMaps(l2, u).run(),
291
             gr, l2, u, cc, s3, false,   0, "#A8");
334
             gr, l1, cu, cc, s3, mcf.OPTIMAL, true,    0, "#A7");
335
    checkMcf(mcf, mcf.lowerMap(l2).upperMap(u).run(),
336
             gr, l2, u, cc, s3, mcf.INFEASIBLE, false, 0, "#A8");
337
    mcf.reset().lowerMap(l3).upperMap(u).costMap(c).supplyMap(s4);
338
    checkMcf(mcf, mcf.run(),
339
             gr, l3, u, c, s4, mcf.OPTIMAL, true,   6360, "#A9");
292 340

	
293 341
    // Check the GEQ form
294
    mcf.reset().upperMap(u).costMap(c).supplyMap(s4);
342
    mcf.reset().upperMap(u).costMap(c).supplyMap(s5);
295 343
    checkMcf(mcf, mcf.run(),
296
             gr, l1, u, c, s4, true,  3530, "#A9", GEQ);
297
    mcf.problemType(mcf.GEQ);
344
             gr, l1, u, c, s5, mcf.OPTIMAL, true,   3530, "#A10", GEQ);
345
    mcf.supplyType(mcf.GEQ);
298 346
    checkMcf(mcf, mcf.lowerMap(l2).run(),
299
             gr, l2, u, c, s4, true,  4540, "#A10", GEQ);
300
    mcf.problemType(mcf.CARRY_SUPPLIES).supplyMap(s5);
347
             gr, l2, u, c, s5, mcf.OPTIMAL, true,   4540, "#A11", GEQ);
348
    mcf.supplyType(mcf.CARRY_SUPPLIES).supplyMap(s6);
301 349
    checkMcf(mcf, mcf.run(),
302
             gr, l2, u, c, s5, false,    0, "#A11", GEQ);
350
             gr, l2, u, c, s6, mcf.INFEASIBLE, false,  0, "#A12", GEQ);
303 351

	
304 352
    // Check the LEQ form
305
    mcf.reset().problemType(mcf.LEQ);
306
    mcf.upperMap(u).costMap(c).supplyMap(s5);
353
    mcf.reset().supplyType(mcf.LEQ);
354
    mcf.upperMap(u).costMap(c).supplyMap(s6);
307 355
    checkMcf(mcf, mcf.run(),
308
             gr, l1, u, c, s5, true,  5080, "#A12", LEQ);
356
             gr, l1, u, c, s6, mcf.OPTIMAL, true,   5080, "#A13", LEQ);
309 357
    checkMcf(mcf, mcf.lowerMap(l2).run(),
310
             gr, l2, u, c, s5, true,  5930, "#A13", LEQ);
311
    mcf.problemType(mcf.SATISFY_DEMANDS).supplyMap(s4);
358
             gr, l2, u, c, s6, mcf.OPTIMAL, true,   5930, "#A14", LEQ);
359
    mcf.supplyType(mcf.SATISFY_DEMANDS).supplyMap(s5);
312 360
    checkMcf(mcf, mcf.run(),
313
             gr, l2, u, c, s4, false,    0, "#A14", LEQ);
361
             gr, l2, u, c, s5, mcf.INFEASIBLE, false,  0, "#A15", LEQ);
362

	
363
    // Check negative costs
364
    NetworkSimplex<Digraph> nmcf(ngr);
365
    nmcf.lowerMap(nl1).costMap(nc).supplyMap(ns);
366
    checkMcf(nmcf, nmcf.run(),
367
      ngr, nl1, nu1, nc, ns, nmcf.UNBOUNDED, false,    0, "#A16");
368
    checkMcf(nmcf, nmcf.upperMap(nu2).run(),
369
      ngr, nl1, nu2, nc, ns, nmcf.OPTIMAL, true,  -40000, "#A17");
370
    nmcf.reset().lowerMap(nl2).costMap(nc).supplyMap(ns);
371
    checkMcf(nmcf, nmcf.run(),
372
      ngr, nl2, nu1, nc, ns, nmcf.UNBOUNDED, false,    0, "#A18");
314 373
  }
315 374

	
316 375
  // B. Test NetworkSimplex with each pivot rule
317 376
  {
318 377
    NetworkSimplex<Digraph> mcf(gr);
319
    mcf.supplyMap(s1).costMap(c).capacityMap(u).lowerMap(l2);
378
    mcf.supplyMap(s1).costMap(c).upperMap(u).lowerMap(l2);
320 379

	
321 380
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::FIRST_ELIGIBLE),
322
             gr, l2, u, c, s1, true,  5970, "#B1");
381
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B1");
323 382
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::BEST_ELIGIBLE),
324
             gr, l2, u, c, s1, true,  5970, "#B2");
383
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B2");
325 384
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::BLOCK_SEARCH),
326
             gr, l2, u, c, s1, true,  5970, "#B3");
385
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B3");
327 386
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::CANDIDATE_LIST),
328
             gr, l2, u, c, s1, true,  5970, "#B4");
387
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B4");
329 388
    checkMcf(mcf, mcf.run(NetworkSimplex<Digraph>::ALTERING_LIST),
330
             gr, l2, u, c, s1, true,  5970, "#B5");
389
             gr, l2, u, c, s1, mcf.OPTIMAL, true,   5970, "#B5");
331 390
  }
332 391

	
333 392
  return 0;
334 393
}
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 21
///\brief DIMACS problem solver.
22 22
///
23 23
/// This program solves various problems given in DIMACS format.
24 24
///
25 25
/// See
26 26
/// \code
27 27
///   dimacs-solver --help
28 28
/// \endcode
29 29
/// for more info on usage.
30 30

	
31 31
#include <iostream>
32 32
#include <fstream>
33 33
#include <cstring>
34 34

	
35 35
#include <lemon/smart_graph.h>
36 36
#include <lemon/dimacs.h>
37 37
#include <lemon/lgf_writer.h>
38 38
#include <lemon/time_measure.h>
39 39

	
40 40
#include <lemon/arg_parser.h>
41 41
#include <lemon/error.h>
42 42

	
43 43
#include <lemon/dijkstra.h>
44 44
#include <lemon/preflow.h>
45 45
#include <lemon/matching.h>
46 46
#include <lemon/network_simplex.h>
47 47

	
48 48
using namespace lemon;
49 49
typedef SmartDigraph Digraph;
50 50
DIGRAPH_TYPEDEFS(Digraph);
51 51
typedef SmartGraph Graph;
52 52

	
53 53
template<class Value>
54 54
void solve_sp(ArgParser &ap, std::istream &is, std::ostream &,
55 55
              DimacsDescriptor &desc)
56 56
{
57 57
  bool report = !ap.given("q");
58 58
  Digraph g;
59 59
  Node s;
60 60
  Digraph::ArcMap<Value> len(g);
61 61
  Timer t;
62 62
  t.restart();
63 63
  readDimacsSp(is, g, len, s, desc);
64 64
  if(report) std::cerr << "Read the file: " << t << '\n';
65 65
  t.restart();
66 66
  Dijkstra<Digraph, Digraph::ArcMap<Value> > dij(g,len);
67 67
  if(report) std::cerr << "Setup Dijkstra class: " << t << '\n';
68 68
  t.restart();
69 69
  dij.run(s);
70 70
  if(report) std::cerr << "Run Dijkstra: " << t << '\n';
71 71
}
72 72

	
73 73
template<class Value>
74 74
void solve_max(ArgParser &ap, std::istream &is, std::ostream &,
75 75
               Value infty, DimacsDescriptor &desc)
76 76
{
77 77
  bool report = !ap.given("q");
78 78
  Digraph g;
79 79
  Node s,t;
80 80
  Digraph::ArcMap<Value> cap(g);
81 81
  Timer ti;
82 82
  ti.restart();
83 83
  readDimacsMax(is, g, cap, s, t, infty, desc);
84 84
  if(report) std::cerr << "Read the file: " << ti << '\n';
85 85
  ti.restart();
86 86
  Preflow<Digraph, Digraph::ArcMap<Value> > pre(g,cap,s,t);
87 87
  if(report) std::cerr << "Setup Preflow class: " << ti << '\n';
88 88
  ti.restart();
89 89
  pre.run();
90 90
  if(report) std::cerr << "Run Preflow: " << ti << '\n';
91 91
  if(report) std::cerr << "\nMax flow value: " << pre.flowValue() << '\n';  
92 92
}
93 93

	
94 94
template<class Value>
95 95
void solve_min(ArgParser &ap, std::istream &is, std::ostream &,
96 96
               Value infty, DimacsDescriptor &desc)
97 97
{
98 98
  bool report = !ap.given("q");
99 99
  Digraph g;
100 100
  Digraph::ArcMap<Value> lower(g), cap(g), cost(g);
101 101
  Digraph::NodeMap<Value> sup(g);
102 102
  Timer ti;
103 103

	
104 104
  ti.restart();
105 105
  readDimacsMin(is, g, lower, cap, cost, sup, infty, desc);
106 106
  ti.stop();
107 107
  Value sum_sup = 0;
108 108
  for (Digraph::NodeIt n(g); n != INVALID; ++n) {
109 109
    sum_sup += sup[n];
110 110
  }
111 111
  if (report) {
112 112
    std::cerr << "Sum of supply values: " << sum_sup << "\n";
113 113
    if (sum_sup <= 0)
114 114
      std::cerr << "GEQ supply contraints are used for NetworkSimplex\n\n";
115 115
    else
116 116
      std::cerr << "LEQ supply contraints are used for NetworkSimplex\n\n";
117 117
  }
118 118
  if (report) std::cerr << "Read the file: " << ti << '\n';
119 119

	
120 120
  ti.restart();
121 121
  NetworkSimplex<Digraph, Value> ns(g);
122
  ns.lowerMap(lower).capacityMap(cap).costMap(cost).supplyMap(sup);
123
  if (sum_sup > 0) ns.problemType(ns.LEQ);
122
  ns.lowerMap(lower).upperMap(cap).costMap(cost).supplyMap(sup);
123
  if (sum_sup > 0) ns.supplyType(ns.LEQ);
124 124
  if (report) std::cerr << "Setup NetworkSimplex class: " << ti << '\n';
125 125
  ti.restart();
126 126
  bool res = ns.run();
127 127
  if (report) {
128 128
    std::cerr << "Run NetworkSimplex: " << ti << "\n\n";
129 129
    std::cerr << "Feasible flow: " << (res ? "found" : "not found") << '\n';
130 130
    if (res) std::cerr << "Min flow cost: " << ns.totalCost() << '\n';
131 131
  }
132 132
}
133 133

	
134 134
void solve_mat(ArgParser &ap, std::istream &is, std::ostream &,
135 135
              DimacsDescriptor &desc)
136 136
{
137 137
  bool report = !ap.given("q");
138 138
  Graph g;
139 139
  Timer ti;
140 140
  ti.restart();
141 141
  readDimacsMat(is, g, desc);
142 142
  if(report) std::cerr << "Read the file: " << ti << '\n';
143 143
  ti.restart();
144 144
  MaxMatching<Graph> mat(g);
145 145
  if(report) std::cerr << "Setup MaxMatching class: " << ti << '\n';
146 146
  ti.restart();
147 147
  mat.run();
148 148
  if(report) std::cerr << "Run MaxMatching: " << ti << '\n';
149 149
  if(report) std::cerr << "\nCardinality of max matching: "
150 150
                       << mat.matchingSize() << '\n';  
151 151
}
152 152

	
153 153

	
154 154
template<class Value>
155 155
void solve(ArgParser &ap, std::istream &is, std::ostream &os,
156 156
           DimacsDescriptor &desc)
157 157
{
158 158
  std::stringstream iss(static_cast<std::string>(ap["infcap"]));
159 159
  Value infty;
160 160
  iss >> infty;
161 161
  if(iss.fail())
162 162
    {
163 163
      std::cerr << "Cannot interpret '"
164 164
                << static_cast<std::string>(ap["infcap"]) << "' as infinite"
165 165
                << std::endl;
166 166
      exit(1);
167 167
    }
168 168
  
169 169
  switch(desc.type)
170 170
    {
171 171
    case DimacsDescriptor::MIN:
172 172
      solve_min<Value>(ap,is,os,infty,desc);
173 173
      break;
174 174
    case DimacsDescriptor::MAX:
175 175
      solve_max<Value>(ap,is,os,infty,desc);
176 176
      break;
177 177
    case DimacsDescriptor::SP:
178 178
      solve_sp<Value>(ap,is,os,desc);
179 179
      break;
180 180
    case DimacsDescriptor::MAT:
181 181
      solve_mat(ap,is,os,desc);
182 182
      break;
183 183
    default:
184 184
      break;
185 185
    }
186 186
}
187 187

	
188 188
int main(int argc, const char *argv[]) {
189 189
  typedef SmartDigraph Digraph;
190 190

	
191 191
  typedef Digraph::Arc Arc;
192 192

	
193 193
  std::string inputName;
194 194
  std::string outputName;
195 195

	
196 196
  ArgParser ap(argc, argv);
197 197
  ap.other("[INFILE [OUTFILE]]",
198 198
           "If either the INFILE or OUTFILE file is missing the standard\n"
199 199
           "     input/output will be used instead.")
200 200
    .boolOption("q", "Do not print any report")
201 201
    .boolOption("int","Use 'int' for capacities, costs etc. (default)")
202 202
    .optionGroup("datatype","int")
203 203
#ifdef HAVE_LONG_LONG
204 204
    .boolOption("long","Use 'long long' for capacities, costs etc.")
205 205
    .optionGroup("datatype","long")
206 206
#endif
207 207
    .boolOption("double","Use 'double' for capacities, costs etc.")
208 208
    .optionGroup("datatype","double")
209 209
    .boolOption("ldouble","Use 'long double' for capacities, costs etc.")
210 210
    .optionGroup("datatype","ldouble")
211 211
    .onlyOneGroup("datatype")
212 212
    .stringOption("infcap","Value used for 'very high' capacities","0")
213 213
    .run();
214 214

	
215 215
  std::ifstream input;
216 216
  std::ofstream output;
217 217

	
218 218
  switch(ap.files().size())
219 219
    {
220 220
    case 2:
221 221
      output.open(ap.files()[1].c_str());
222 222
      if (!output) {
223 223
        throw IoError("Cannot open the file for writing", ap.files()[1]);
224 224
      }
225 225
    case 1:
226 226
      input.open(ap.files()[0].c_str());
227 227
      if (!input) {
228 228
        throw IoError("File cannot be found", ap.files()[0]);
229 229
      }
230 230
    case 0:
231 231
      break;
232 232
    default:
233 233
      std::cerr << ap.commandName() << ": too many arguments\n";
234 234
      return 1;
235 235
    }
236 236
  std::istream& is = (ap.files().size()<1 ? std::cin : input);
237 237
  std::ostream& os = (ap.files().size()<2 ? std::cout : output);
238 238

	
239 239
  DimacsDescriptor desc = dimacsType(is);
240 240
  
241 241
  if(!ap.given("q"))
242 242
    {
243 243
      std::cout << "Problem type: ";
244 244
      switch(desc.type)
245 245
        {
246 246
        case DimacsDescriptor::MIN:
247 247
          std::cout << "min";
248 248
          break;
249 249
        case DimacsDescriptor::MAX:
250 250
          std::cout << "max";
251 251
          break;
252 252
        case DimacsDescriptor::SP:
253 253
          std::cout << "sp";
254 254
        case DimacsDescriptor::MAT:
255 255
          std::cout << "mat";
256 256
          break;
257 257
        default:
258 258
          exit(1);
259 259
          break;
260 260
        }
261 261
      std::cout << "\nNum of nodes: " << desc.nodeNum;
262 262
      std::cout << "\nNum of arcs:  " << desc.edgeNum;
263 263
      std::cout << "\n\n";
264 264
    }
265 265
    
266 266
  if(ap.given("double"))
267 267
    solve<double>(ap,is,os,desc);
268 268
  else if(ap.given("ldouble"))
269 269
    solve<long double>(ap,is,os,desc);
270 270
#ifdef HAVE_LONG_LONG
271 271
  else if(ap.given("long"))
272 272
    solve<long long>(ap,is,os,desc);
273 273
#endif
274 274
  else solve<int>(ap,is,os,desc);
275 275

	
276 276
  return 0;
277 277
}
0 comments (0 inline)