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

	
19 19
#ifndef LEMON_CAPACITY_SCALING_H
20 20
#define LEMON_CAPACITY_SCALING_H
21 21

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

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

	
32 32
namespace lemon {
33 33

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

	
52 52
    /// \brief The type of the heap used for internal Dijkstra computations.
53 53
    ///
54 54
    /// The type of the heap used for internal Dijkstra computations.
55 55
    /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
56 56
    /// its priority type must be \c Cost and its cross reference type
57 57
    /// must be \ref RangeMap "RangeMap<int>".
58 58
    typedef BinHeap<Cost, RangeMap<int> > Heap;
59 59
  };
60 60

	
61 61
  /// \addtogroup min_cost_flow_algs
62 62
  /// @{
63 63

	
64 64
  /// \brief Implementation of the Capacity Scaling algorithm for
65 65
  /// finding a \ref min_cost_flow "minimum cost flow".
66 66
  ///
67 67
  /// \ref CapacityScaling implements the capacity scaling version
68 68
  /// of the successive shortest path algorithm for finding a
69 69
  /// \ref min_cost_flow "minimum cost flow" \ref amo93networkflows,
70 70
  /// \ref edmondskarp72theoretical. It is an efficient dual
71 71
  /// solution method.
72 72
  ///
73 73
  /// Most of the parameters of the problem (except for the digraph)
74 74
  /// can be given using separate functions, and the algorithm can be
75 75
  /// executed using the \ref run() function. If some parameters are not
76 76
  /// specified, then default values will be used.
77 77
  ///
78 78
  /// \tparam GR The digraph type the algorithm runs on.
79 79
  /// \tparam V The number type used for flow amounts, capacity bounds
80 80
  /// and supply values in the algorithm. By default, it is \c int.
81 81
  /// \tparam C The number type used for costs and potentials in the
82 82
  /// algorithm. By default, it is the same as \c V.
83 83
  /// \tparam TR The traits class that defines various types used by the
84 84
  /// algorithm. By default, it is \ref CapacityScalingDefaultTraits
85 85
  /// "CapacityScalingDefaultTraits<GR, V, C>".
86 86
  /// In most cases, this parameter should not be set directly,
87 87
  /// consider to use the named template parameters instead.
88 88
  ///
89
  /// \warning Both number types must be signed and all input data must
89
  /// \warning Both \c V and \c C must be signed number types.
90
  /// \warning All input data (capacities, supply values, and costs) must
90 91
  /// be integer.
91 92
  /// \warning This algorithm does not support negative costs for such
92 93
  /// arcs that have infinite upper bound.
93 94
#ifdef DOXYGEN
94 95
  template <typename GR, typename V, typename C, typename TR>
95 96
#else
96 97
  template < typename GR, typename V = int, typename C = V,
97 98
             typename TR = CapacityScalingDefaultTraits<GR, V, C> >
98 99
#endif
99 100
  class CapacityScaling
100 101
  {
101 102
  public:
102 103

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

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

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

	
116 117
  public:
117 118

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

	
137 138
  private:
138 139

	
139 140
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
140 141

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

	
147 148
  private:
148 149

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

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

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

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

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

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

	
186 187
  public:
187 188

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

	
195 196
  private:
196 197

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

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

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

	
218 219
    public:
219 220

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

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

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

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

	
266 267
        // Update potentials of processed nodes
267 268
        int t = heap.top();
268 269
        Cost dt = heap.prio();
269 270
        for (int i = 0; i < int(_proc_nodes.size()); ++i) {
270 271
          _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt;
271 272
        }
272 273

	
273 274
        return t;
274 275
      }
275 276

	
276 277
    }; //class ResidualDijkstra
277 278

	
278 279
  public:
279 280

	
280 281
    /// \name Named Template Parameters
281 282
    /// @{
282 283

	
283 284
    template <typename T>
284 285
    struct SetHeapTraits : public Traits {
285 286
      typedef T Heap;
286 287
    };
287 288

	
288 289
    /// \brief \ref named-templ-param "Named parameter" for setting
289 290
    /// \c Heap type.
290 291
    ///
291 292
    /// \ref named-templ-param "Named parameter" for setting \c Heap
292 293
    /// type, which is used for internal Dijkstra computations.
293 294
    /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
294 295
    /// its priority type must be \c Cost and its cross reference type
295 296
    /// must be \ref RangeMap "RangeMap<int>".
296 297
    template <typename T>
297 298
    struct SetHeap
298 299
      : public CapacityScaling<GR, V, C, SetHeapTraits<T> > {
299 300
      typedef  CapacityScaling<GR, V, C, SetHeapTraits<T> > Create;
300 301
    };
301 302

	
302 303
    /// @}
303 304

	
304 305
  protected:
305 306

	
306 307
    CapacityScaling() {}
307 308

	
308 309
  public:
309 310

	
310 311
    /// \brief Constructor.
311 312
    ///
312 313
    /// The constructor of the class.
313 314
    ///
314 315
    /// \param graph The digraph the algorithm runs on.
315 316
    CapacityScaling(const GR& graph) :
316 317
      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
317 318
      INF(std::numeric_limits<Value>::has_infinity ?
318 319
          std::numeric_limits<Value>::infinity() :
319 320
          std::numeric_limits<Value>::max())
320 321
    {
321 322
      // Check the number types
322 323
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
323 324
        "The flow type of CapacityScaling must be signed");
324 325
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
325 326
        "The cost type of CapacityScaling must be signed");
326 327

	
327 328
      // Reset data structures
328 329
      reset();
329 330
    }
330 331

	
331 332
    /// \name Parameters
332 333
    /// The parameters of the algorithm can be specified using these
333 334
    /// functions.
334 335

	
335 336
    /// @{
336 337

	
337 338
    /// \brief Set the lower bounds on the arcs.
338 339
    ///
339 340
    /// This function sets the lower bounds on the arcs.
340 341
    /// If it is not used before calling \ref run(), the lower bounds
341 342
    /// will be set to zero on all arcs.
342 343
    ///
343 344
    /// \param map An arc map storing the lower bounds.
344 345
    /// Its \c Value type must be convertible to the \c Value type
345 346
    /// of the algorithm.
346 347
    ///
347 348
    /// \return <tt>(*this)</tt>
348 349
    template <typename LowerMap>
349 350
    CapacityScaling& lowerMap(const LowerMap& map) {
350 351
      _have_lower = true;
351 352
      for (ArcIt a(_graph); a != INVALID; ++a) {
352 353
        _lower[_arc_idf[a]] = map[a];
353 354
        _lower[_arc_idb[a]] = map[a];
354 355
      }
355 356
      return *this;
356 357
    }
357 358

	
358 359
    /// \brief Set the upper bounds (capacities) on the arcs.
359 360
    ///
360 361
    /// This function sets the upper bounds (capacities) on the arcs.
361 362
    /// If it is not used before calling \ref run(), the upper bounds
362 363
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
363 364
    /// unbounded from above).
364 365
    ///
365 366
    /// \param map An arc map storing the upper bounds.
366 367
    /// Its \c Value type must be convertible to the \c Value type
367 368
    /// of the algorithm.
368 369
    ///
369 370
    /// \return <tt>(*this)</tt>
370 371
    template<typename UpperMap>
371 372
    CapacityScaling& upperMap(const UpperMap& map) {
372 373
      for (ArcIt a(_graph); a != INVALID; ++a) {
373 374
        _upper[_arc_idf[a]] = map[a];
374 375
      }
375 376
      return *this;
376 377
    }
377 378

	
378 379
    /// \brief Set the costs of the arcs.
379 380
    ///
380 381
    /// This function sets the costs of the arcs.
381 382
    /// If it is not used before calling \ref run(), the costs
382 383
    /// will be set to \c 1 on all arcs.
383 384
    ///
384 385
    /// \param map An arc map storing the costs.
385 386
    /// Its \c Value type must be convertible to the \c Cost type
386 387
    /// of the algorithm.
387 388
    ///
388 389
    /// \return <tt>(*this)</tt>
389 390
    template<typename CostMap>
390 391
    CapacityScaling& costMap(const CostMap& map) {
391 392
      for (ArcIt a(_graph); a != INVALID; ++a) {
392 393
        _cost[_arc_idf[a]] =  map[a];
393 394
        _cost[_arc_idb[a]] = -map[a];
394 395
      }
395 396
      return *this;
396 397
    }
397 398

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

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

	
443 444
    /// @}
444 445

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

	
448 449
    /// @{
449 450

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

	
492 493
    /// \brief Reset all the parameters that have been given before.
493 494
    ///
494 495
    /// This function resets all the paramaters that have been given
495 496
    /// before using functions \ref lowerMap(), \ref upperMap(),
496 497
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
497 498
    ///
498 499
    /// It is useful for multiple \ref run() calls. Basically, all the given
499 500
    /// parameters are kept for the next \ref run() call, unless
500 501
    /// \ref resetParams() or \ref reset() is used.
501 502
    /// If the underlying digraph was also modified after the construction
502 503
    /// of the class or the last \ref reset() call, then the \ref reset()
503 504
    /// function must be used, otherwise \ref resetParams() is sufficient.
504 505
    ///
505 506
    /// For example,
506 507
    /// \code
507 508
    ///   CapacityScaling<ListDigraph> cs(graph);
508 509
    ///
509 510
    ///   // First run
510 511
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
511 512
    ///     .supplyMap(sup).run();
512 513
    ///
513 514
    ///   // Run again with modified cost map (resetParams() is not called,
514 515
    ///   // so only the cost map have to be set again)
515 516
    ///   cost[e] += 100;
516 517
    ///   cs.costMap(cost).run();
517 518
    ///
518 519
    ///   // Run again from scratch using resetParams()
519 520
    ///   // (the lower bounds will be set to zero on all arcs)
520 521
    ///   cs.resetParams();
521 522
    ///   cs.upperMap(capacity).costMap(cost)
522 523
    ///     .supplyMap(sup).run();
523 524
    /// \endcode
524 525
    ///
525 526
    /// \return <tt>(*this)</tt>
526 527
    ///
527 528
    /// \see reset(), run()
528 529
    CapacityScaling& resetParams() {
529 530
      for (int i = 0; i != _node_num; ++i) {
530 531
        _supply[i] = 0;
531 532
      }
532 533
      for (int j = 0; j != _res_arc_num; ++j) {
533 534
        _lower[j] = 0;
534 535
        _upper[j] = INF;
535 536
        _cost[j] = _forward[j] ? 1 : -1;
536 537
      }
537 538
      _have_lower = false;
538 539
      return *this;
539 540
    }
540 541

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

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

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

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

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

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

	
628 629
    /// @}
629 630

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

	
635 636
    /// @{
636 637

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

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

	
669 670
    /// \brief Return the flow on the given arc.
670 671
    ///
671 672
    /// This function returns the flow on the given arc.
672 673
    ///
673 674
    /// \pre \ref run() must be called before using this function.
674 675
    Value flow(const Arc& a) const {
675 676
      return _res_cap[_arc_idb[a]];
676 677
    }
677 678

	
678 679
    /// \brief Return the flow map (the primal solution).
679 680
    ///
680 681
    /// This function copies the flow value on each arc into the given
681 682
    /// map. The \c Value type of the algorithm must be convertible to
682 683
    /// the \c Value type of the map.
683 684
    ///
684 685
    /// \pre \ref run() must be called before using this function.
685 686
    template <typename FlowMap>
686 687
    void flowMap(FlowMap &map) const {
687 688
      for (ArcIt a(_graph); a != INVALID; ++a) {
688 689
        map.set(a, _res_cap[_arc_idb[a]]);
689 690
      }
690 691
    }
691 692

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

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

	
717 718
    /// @}
718 719

	
719 720
  private:
720 721

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

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

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

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

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

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

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

	
823 824
      return OPTIMAL;
824 825
    }
825 826

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

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

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

	
850 851
      return pt;
851 852
    }
852 853

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

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

	
887 888
        // Find augmenting shortest paths
888 889
        while (next_node < int(_excess_nodes.size())) {
889 890
          // Check deficit nodes
890 891
          if (_delta > 1) {
891 892
            bool delta_deficit = false;
892 893
            for ( ; next_def_node < int(_deficit_nodes.size());
893 894
                    ++next_def_node ) {
894 895
              if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
895 896
                delta_deficit = true;
896 897
                break;
897 898
              }
898 899
            }
899 900
            if (!delta_deficit) break;
900 901
          }
901 902

	
902 903
          // Run Dijkstra in the residual network
903 904
          s = _excess_nodes[next_node];
904 905
          if ((t = _dijkstra.run(s, _delta)) == -1) {
905 906
            if (_delta > 1) {
906 907
              ++next_node;
907 908
              continue;
908 909
            }
909 910
            return INFEASIBLE;
910 911
          }
911 912

	
912 913
          // Augment along a shortest path from s to t
913 914
          Value d = std::min(_excess[s], -_excess[t]);
914 915
          int u = t;
915 916
          int a;
916 917
          if (d > _delta) {
917 918
            while ((a = _pred[u]) != -1) {
918 919
              if (_res_cap[a] < d) d = _res_cap[a];
919 920
              u = _source[a];
920 921
            }
921 922
          }
922 923
          u = t;
923 924
          while ((a = _pred[u]) != -1) {
924 925
            _res_cap[a] -= d;
925 926
            _res_cap[_reverse[a]] += d;
926 927
            u = _source[a];
927 928
          }
928 929
          _excess[s] -= d;
929 930
          _excess[t] += d;
930 931

	
931 932
          if (_excess[s] < _delta) ++next_node;
932 933
        }
933 934

	
934 935
        if (_delta == 1) break;
935 936
        _delta = _delta <= _factor ? 1 : _delta / _factor;
936 937
      }
937 938

	
938 939
      return OPTIMAL;
939 940
    }
940 941

	
941 942
    // Execute the successive shortest path algorithm
942 943
    ProblemType startWithoutScaling() {
943 944
      // Find excess nodes
944 945
      _excess_nodes.clear();
945 946
      for (int i = 0; i != _node_num; ++i) {
946 947
        if (_excess[i] > 0) _excess_nodes.push_back(i);
947 948
      }
948 949
      if (_excess_nodes.size() == 0) return OPTIMAL;
949 950
      int next_node = 0;
950 951

	
951 952
      // Find shortest paths
952 953
      int s, t;
953 954
      ResidualDijkstra _dijkstra(*this);
954 955
      while ( _excess[_excess_nodes[next_node]] > 0 ||
955 956
              ++next_node < int(_excess_nodes.size()) )
956 957
      {
957 958
        // Run Dijkstra in the residual network
958 959
        s = _excess_nodes[next_node];
959 960
        if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
960 961

	
961 962
        // Augment along a shortest path from s to t
962 963
        Value d = std::min(_excess[s], -_excess[t]);
963 964
        int u = t;
964 965
        int a;
965 966
        if (d > 1) {
966 967
          while ((a = _pred[u]) != -1) {
967 968
            if (_res_cap[a] < d) d = _res_cap[a];
968 969
            u = _source[a];
969 970
          }
970 971
        }
971 972
        u = t;
972 973
        while ((a = _pred[u]) != -1) {
973 974
          _res_cap[a] -= d;
974 975
          _res_cap[_reverse[a]] += d;
975 976
          u = _source[a];
976 977
        }
977 978
        _excess[s] -= d;
978 979
        _excess[t] += d;
979 980
      }
980 981

	
981 982
      return OPTIMAL;
982 983
    }
983 984

	
984 985
  }; //class CapacityScaling
985 986

	
986 987
  ///@}
987 988

	
988 989
} //namespace lemon
989 990

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

	
19 19
#ifndef LEMON_COST_SCALING_H
20 20
#define LEMON_COST_SCALING_H
21 21

	
22 22
/// \ingroup min_cost_flow_algs
23 23
/// \file
24 24
/// \brief Cost scaling algorithm for finding a minimum cost flow.
25 25

	
26 26
#include <vector>
27 27
#include <deque>
28 28
#include <limits>
29 29

	
30 30
#include <lemon/core.h>
31 31
#include <lemon/maps.h>
32 32
#include <lemon/math.h>
33 33
#include <lemon/static_graph.h>
34 34
#include <lemon/circulation.h>
35 35
#include <lemon/bellman_ford.h>
36 36

	
37 37
namespace lemon {
38 38

	
39 39
  /// \brief Default traits class of CostScaling algorithm.
40 40
  ///
41 41
  /// Default traits class of CostScaling algorithm.
42 42
  /// \tparam GR Digraph type.
43 43
  /// \tparam V The number type used for flow amounts, capacity bounds
44 44
  /// and supply values. By default it is \c int.
45 45
  /// \tparam C The number type used for costs and potentials.
46 46
  /// By default it is the same as \c V.
47 47
#ifdef DOXYGEN
48 48
  template <typename GR, typename V = int, typename C = V>
49 49
#else
50 50
  template < typename GR, typename V = int, typename C = V,
51 51
             bool integer = std::numeric_limits<C>::is_integer >
52 52
#endif
53 53
  struct CostScalingDefaultTraits
54 54
  {
55 55
    /// The type of the digraph
56 56
    typedef GR Digraph;
57 57
    /// The type of the flow amounts, capacity bounds and supply values
58 58
    typedef V Value;
59 59
    /// The type of the arc costs
60 60
    typedef C Cost;
61 61

	
62 62
    /// \brief The large cost type used for internal computations
63 63
    ///
64 64
    /// The large cost type used for internal computations.
65 65
    /// It is \c long \c long if the \c Cost type is integer,
66 66
    /// otherwise it is \c double.
67 67
    /// \c Cost must be convertible to \c LargeCost.
68 68
    typedef double LargeCost;
69 69
  };
70 70

	
71 71
  // Default traits class for integer cost types
72 72
  template <typename GR, typename V, typename C>
73 73
  struct CostScalingDefaultTraits<GR, V, C, true>
74 74
  {
75 75
    typedef GR Digraph;
76 76
    typedef V Value;
77 77
    typedef C Cost;
78 78
#ifdef LEMON_HAVE_LONG_LONG
79 79
    typedef long long LargeCost;
80 80
#else
81 81
    typedef long LargeCost;
82 82
#endif
83 83
  };
84 84

	
85 85

	
86 86
  /// \addtogroup min_cost_flow_algs
87 87
  /// @{
88 88

	
89 89
  /// \brief Implementation of the Cost Scaling algorithm for
90 90
  /// finding a \ref min_cost_flow "minimum cost flow".
91 91
  ///
92 92
  /// \ref CostScaling implements a cost scaling algorithm that performs
93 93
  /// push/augment and relabel operations for finding a \ref min_cost_flow
94 94
  /// "minimum cost flow" \ref amo93networkflows, \ref goldberg90approximation,
95 95
  /// \ref goldberg97efficient, \ref bunnagel98efficient.
96 96
  /// It is a highly efficient primal-dual solution method, which
97 97
  /// can be viewed as the generalization of the \ref Preflow
98 98
  /// "preflow push-relabel" algorithm for the maximum flow problem.
99 99
  ///
100 100
  /// Most of the parameters of the problem (except for the digraph)
101 101
  /// can be given using separate functions, and the algorithm can be
102 102
  /// executed using the \ref run() function. If some parameters are not
103 103
  /// specified, then default values will be used.
104 104
  ///
105 105
  /// \tparam GR The digraph type the algorithm runs on.
106 106
  /// \tparam V The number type used for flow amounts, capacity bounds
107 107
  /// and supply values in the algorithm. By default, it is \c int.
108 108
  /// \tparam C The number type used for costs and potentials in the
109 109
  /// algorithm. By default, it is the same as \c V.
110 110
  /// \tparam TR The traits class that defines various types used by the
111 111
  /// algorithm. By default, it is \ref CostScalingDefaultTraits
112 112
  /// "CostScalingDefaultTraits<GR, V, C>".
113 113
  /// In most cases, this parameter should not be set directly,
114 114
  /// consider to use the named template parameters instead.
115 115
  ///
116
  /// \warning Both number types must be signed and all input data must
116
  /// \warning Both \c V and \c C must be signed number types.
117
  /// \warning All input data (capacities, supply values, and costs) must
117 118
  /// be integer.
118 119
  /// \warning This algorithm does not support negative costs for such
119 120
  /// arcs that have infinite upper bound.
120 121
  ///
121 122
  /// \note %CostScaling provides three different internal methods,
122 123
  /// from which the most efficient one is used by default.
123 124
  /// For more information, see \ref Method.
124 125
#ifdef DOXYGEN
125 126
  template <typename GR, typename V, typename C, typename TR>
126 127
#else
127 128
  template < typename GR, typename V = int, typename C = V,
128 129
             typename TR = CostScalingDefaultTraits<GR, V, C> >
129 130
#endif
130 131
  class CostScaling
131 132
  {
132 133
  public:
133 134

	
134 135
    /// The type of the digraph
135 136
    typedef typename TR::Digraph Digraph;
136 137
    /// The type of the flow amounts, capacity bounds and supply values
137 138
    typedef typename TR::Value Value;
138 139
    /// The type of the arc costs
139 140
    typedef typename TR::Cost Cost;
140 141

	
141 142
    /// \brief The large cost type
142 143
    ///
143 144
    /// The large cost type used for internal computations.
144 145
    /// By default, it is \c long \c long if the \c Cost type is integer,
145 146
    /// otherwise it is \c double.
146 147
    typedef typename TR::LargeCost LargeCost;
147 148

	
148 149
    /// The \ref CostScalingDefaultTraits "traits class" of the algorithm
149 150
    typedef TR Traits;
150 151

	
151 152
  public:
152 153

	
153 154
    /// \brief Problem type constants for the \c run() function.
154 155
    ///
155 156
    /// Enum type containing the problem type constants that can be
156 157
    /// returned by the \ref run() function of the algorithm.
157 158
    enum ProblemType {
158 159
      /// The problem has no feasible solution (flow).
159 160
      INFEASIBLE,
160 161
      /// The problem has optimal solution (i.e. it is feasible and
161 162
      /// bounded), and the algorithm has found optimal flow and node
162 163
      /// potentials (primal and dual solutions).
163 164
      OPTIMAL,
164 165
      /// The digraph contains an arc of negative cost and infinite
165 166
      /// upper bound. It means that the objective function is unbounded
166 167
      /// on that arc, however, note that it could actually be bounded
167 168
      /// over the feasible flows, but this algroithm cannot handle
168 169
      /// these cases.
169 170
      UNBOUNDED
170 171
    };
171 172

	
172 173
    /// \brief Constants for selecting the internal method.
173 174
    ///
174 175
    /// Enum type containing constants for selecting the internal method
175 176
    /// for the \ref run() function.
176 177
    ///
177 178
    /// \ref CostScaling provides three internal methods that differ mainly
178 179
    /// in their base operations, which are used in conjunction with the
179 180
    /// relabel operation.
180 181
    /// By default, the so called \ref PARTIAL_AUGMENT
181 182
    /// "Partial Augment-Relabel" method is used, which proved to be
182 183
    /// the most efficient and the most robust on various test inputs.
183 184
    /// However, the other methods can be selected using the \ref run()
184 185
    /// function with the proper parameter.
185 186
    enum Method {
186 187
      /// Local push operations are used, i.e. flow is moved only on one
187 188
      /// admissible arc at once.
188 189
      PUSH,
189 190
      /// Augment operations are used, i.e. flow is moved on admissible
190 191
      /// paths from a node with excess to a node with deficit.
191 192
      AUGMENT,
192 193
      /// Partial augment operations are used, i.e. flow is moved on
193 194
      /// admissible paths started from a node with excess, but the
194 195
      /// lengths of these paths are limited. This method can be viewed
195 196
      /// as a combined version of the previous two operations.
196 197
      PARTIAL_AUGMENT
197 198
    };
198 199

	
199 200
  private:
200 201

	
201 202
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
202 203

	
203 204
    typedef std::vector<int> IntVector;
204 205
    typedef std::vector<Value> ValueVector;
205 206
    typedef std::vector<Cost> CostVector;
206 207
    typedef std::vector<LargeCost> LargeCostVector;
207 208
    typedef std::vector<char> BoolVector;
208 209
    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
209 210

	
210 211
  private:
211 212

	
212 213
    template <typename KT, typename VT>
213 214
    class StaticVectorMap {
214 215
    public:
215 216
      typedef KT Key;
216 217
      typedef VT Value;
217 218

	
218 219
      StaticVectorMap(std::vector<Value>& v) : _v(v) {}
219 220

	
220 221
      const Value& operator[](const Key& key) const {
221 222
        return _v[StaticDigraph::id(key)];
222 223
      }
223 224

	
224 225
      Value& operator[](const Key& key) {
225 226
        return _v[StaticDigraph::id(key)];
226 227
      }
227 228

	
228 229
      void set(const Key& key, const Value& val) {
229 230
        _v[StaticDigraph::id(key)] = val;
230 231
      }
231 232

	
232 233
    private:
233 234
      std::vector<Value>& _v;
234 235
    };
235 236

	
236 237
    typedef StaticVectorMap<StaticDigraph::Node, LargeCost> LargeCostNodeMap;
237 238
    typedef StaticVectorMap<StaticDigraph::Arc, LargeCost> LargeCostArcMap;
238 239

	
239 240
  private:
240 241

	
241 242
    // Data related to the underlying digraph
242 243
    const GR &_graph;
243 244
    int _node_num;
244 245
    int _arc_num;
245 246
    int _res_node_num;
246 247
    int _res_arc_num;
247 248
    int _root;
248 249

	
249 250
    // Parameters of the problem
250 251
    bool _have_lower;
251 252
    Value _sum_supply;
252 253
    int _sup_node_num;
253 254

	
254 255
    // Data structures for storing the digraph
255 256
    IntNodeMap _node_id;
256 257
    IntArcMap _arc_idf;
257 258
    IntArcMap _arc_idb;
258 259
    IntVector _first_out;
259 260
    BoolVector _forward;
260 261
    IntVector _source;
261 262
    IntVector _target;
262 263
    IntVector _reverse;
263 264

	
264 265
    // Node and arc data
265 266
    ValueVector _lower;
266 267
    ValueVector _upper;
267 268
    CostVector _scost;
268 269
    ValueVector _supply;
269 270

	
270 271
    ValueVector _res_cap;
271 272
    LargeCostVector _cost;
272 273
    LargeCostVector _pi;
273 274
    ValueVector _excess;
274 275
    IntVector _next_out;
275 276
    std::deque<int> _active_nodes;
276 277

	
277 278
    // Data for scaling
278 279
    LargeCost _epsilon;
279 280
    int _alpha;
280 281

	
281 282
    IntVector _buckets;
282 283
    IntVector _bucket_next;
283 284
    IntVector _bucket_prev;
284 285
    IntVector _rank;
285 286
    int _max_rank;
286 287

	
287 288
    // Data for a StaticDigraph structure
288 289
    typedef std::pair<int, int> IntPair;
289 290
    StaticDigraph _sgr;
290 291
    std::vector<IntPair> _arc_vec;
291 292
    std::vector<LargeCost> _cost_vec;
292 293
    LargeCostArcMap _cost_map;
293 294
    LargeCostNodeMap _pi_map;
294 295

	
295 296
  public:
296 297

	
297 298
    /// \brief Constant for infinite upper bounds (capacities).
298 299
    ///
299 300
    /// Constant for infinite upper bounds (capacities).
300 301
    /// It is \c std::numeric_limits<Value>::infinity() if available,
301 302
    /// \c std::numeric_limits<Value>::max() otherwise.
302 303
    const Value INF;
303 304

	
304 305
  public:
305 306

	
306 307
    /// \name Named Template Parameters
307 308
    /// @{
308 309

	
309 310
    template <typename T>
310 311
    struct SetLargeCostTraits : public Traits {
311 312
      typedef T LargeCost;
312 313
    };
313 314

	
314 315
    /// \brief \ref named-templ-param "Named parameter" for setting
315 316
    /// \c LargeCost type.
316 317
    ///
317 318
    /// \ref named-templ-param "Named parameter" for setting \c LargeCost
318 319
    /// type, which is used for internal computations in the algorithm.
319 320
    /// \c Cost must be convertible to \c LargeCost.
320 321
    template <typename T>
321 322
    struct SetLargeCost
322 323
      : public CostScaling<GR, V, C, SetLargeCostTraits<T> > {
323 324
      typedef  CostScaling<GR, V, C, SetLargeCostTraits<T> > Create;
324 325
    };
325 326

	
326 327
    /// @}
327 328

	
328 329
  protected:
329 330

	
330 331
    CostScaling() {}
331 332

	
332 333
  public:
333 334

	
334 335
    /// \brief Constructor.
335 336
    ///
336 337
    /// The constructor of the class.
337 338
    ///
338 339
    /// \param graph The digraph the algorithm runs on.
339 340
    CostScaling(const GR& graph) :
340 341
      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
341 342
      _cost_map(_cost_vec), _pi_map(_pi),
342 343
      INF(std::numeric_limits<Value>::has_infinity ?
343 344
          std::numeric_limits<Value>::infinity() :
344 345
          std::numeric_limits<Value>::max())
345 346
    {
346 347
      // Check the number types
347 348
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
348 349
        "The flow type of CostScaling must be signed");
349 350
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
350 351
        "The cost type of CostScaling must be signed");
351 352

	
352 353
      // Reset data structures
353 354
      reset();
354 355
    }
355 356

	
356 357
    /// \name Parameters
357 358
    /// The parameters of the algorithm can be specified using these
358 359
    /// functions.
359 360

	
360 361
    /// @{
361 362

	
362 363
    /// \brief Set the lower bounds on the arcs.
363 364
    ///
364 365
    /// This function sets the lower bounds on the arcs.
365 366
    /// If it is not used before calling \ref run(), the lower bounds
366 367
    /// will be set to zero on all arcs.
367 368
    ///
368 369
    /// \param map An arc map storing the lower bounds.
369 370
    /// Its \c Value type must be convertible to the \c Value type
370 371
    /// of the algorithm.
371 372
    ///
372 373
    /// \return <tt>(*this)</tt>
373 374
    template <typename LowerMap>
374 375
    CostScaling& lowerMap(const LowerMap& map) {
375 376
      _have_lower = true;
376 377
      for (ArcIt a(_graph); a != INVALID; ++a) {
377 378
        _lower[_arc_idf[a]] = map[a];
378 379
        _lower[_arc_idb[a]] = map[a];
379 380
      }
380 381
      return *this;
381 382
    }
382 383

	
383 384
    /// \brief Set the upper bounds (capacities) on the arcs.
384 385
    ///
385 386
    /// This function sets the upper bounds (capacities) on the arcs.
386 387
    /// If it is not used before calling \ref run(), the upper bounds
387 388
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
388 389
    /// unbounded from above).
389 390
    ///
390 391
    /// \param map An arc map storing the upper bounds.
391 392
    /// Its \c Value type must be convertible to the \c Value type
392 393
    /// of the algorithm.
393 394
    ///
394 395
    /// \return <tt>(*this)</tt>
395 396
    template<typename UpperMap>
396 397
    CostScaling& upperMap(const UpperMap& map) {
397 398
      for (ArcIt a(_graph); a != INVALID; ++a) {
398 399
        _upper[_arc_idf[a]] = map[a];
399 400
      }
400 401
      return *this;
401 402
    }
402 403

	
403 404
    /// \brief Set the costs of the arcs.
404 405
    ///
405 406
    /// This function sets the costs of the arcs.
406 407
    /// If it is not used before calling \ref run(), the costs
407 408
    /// will be set to \c 1 on all arcs.
408 409
    ///
409 410
    /// \param map An arc map storing the costs.
410 411
    /// Its \c Value type must be convertible to the \c Cost type
411 412
    /// of the algorithm.
412 413
    ///
413 414
    /// \return <tt>(*this)</tt>
414 415
    template<typename CostMap>
415 416
    CostScaling& costMap(const CostMap& map) {
416 417
      for (ArcIt a(_graph); a != INVALID; ++a) {
417 418
        _scost[_arc_idf[a]] =  map[a];
418 419
        _scost[_arc_idb[a]] = -map[a];
419 420
      }
420 421
      return *this;
421 422
    }
422 423

	
423 424
    /// \brief Set the supply values of the nodes.
424 425
    ///
425 426
    /// This function sets the supply values of the nodes.
426 427
    /// If neither this function nor \ref stSupply() is used before
427 428
    /// calling \ref run(), the supply of each node will be set to zero.
428 429
    ///
429 430
    /// \param map A node map storing the supply values.
430 431
    /// Its \c Value type must be convertible to the \c Value type
431 432
    /// of the algorithm.
432 433
    ///
433 434
    /// \return <tt>(*this)</tt>
434 435
    template<typename SupplyMap>
435 436
    CostScaling& supplyMap(const SupplyMap& map) {
436 437
      for (NodeIt n(_graph); n != INVALID; ++n) {
437 438
        _supply[_node_id[n]] = map[n];
438 439
      }
439 440
      return *this;
440 441
    }
441 442

	
442 443
    /// \brief Set single source and target nodes and a supply value.
443 444
    ///
444 445
    /// This function sets a single source node and a single target node
445 446
    /// and the required flow value.
446 447
    /// If neither this function nor \ref supplyMap() is used before
447 448
    /// calling \ref run(), the supply of each node will be set to zero.
448 449
    ///
449 450
    /// Using this function has the same effect as using \ref supplyMap()
450 451
    /// with such a map in which \c k is assigned to \c s, \c -k is
451 452
    /// assigned to \c t and all other nodes have zero supply value.
452 453
    ///
453 454
    /// \param s The source node.
454 455
    /// \param t The target node.
455 456
    /// \param k The required amount of flow from node \c s to node \c t
456 457
    /// (i.e. the supply of \c s and the demand of \c t).
457 458
    ///
458 459
    /// \return <tt>(*this)</tt>
459 460
    CostScaling& stSupply(const Node& s, const Node& t, Value k) {
460 461
      for (int i = 0; i != _res_node_num; ++i) {
461 462
        _supply[i] = 0;
462 463
      }
463 464
      _supply[_node_id[s]] =  k;
464 465
      _supply[_node_id[t]] = -k;
465 466
      return *this;
466 467
    }
467 468

	
468 469
    /// @}
469 470

	
470 471
    /// \name Execution control
471 472
    /// The algorithm can be executed using \ref run().
472 473

	
473 474
    /// @{
474 475

	
475 476
    /// \brief Run the algorithm.
476 477
    ///
477 478
    /// This function runs the algorithm.
478 479
    /// The paramters can be specified using functions \ref lowerMap(),
479 480
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
480 481
    /// For example,
481 482
    /// \code
482 483
    ///   CostScaling<ListDigraph> cs(graph);
483 484
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
484 485
    ///     .supplyMap(sup).run();
485 486
    /// \endcode
486 487
    ///
487 488
    /// This function can be called more than once. All the given parameters
488 489
    /// are kept for the next call, unless \ref resetParams() or \ref reset()
489 490
    /// is used, thus only the modified parameters have to be set again.
490 491
    /// If the underlying digraph was also modified after the construction
491 492
    /// of the class (or the last \ref reset() call), then the \ref reset()
492 493
    /// function must be called.
493 494
    ///
494 495
    /// \param method The internal method that will be used in the
495 496
    /// algorithm. For more information, see \ref Method.
496 497
    /// \param factor The cost scaling factor. It must be larger than one.
497 498
    ///
498 499
    /// \return \c INFEASIBLE if no feasible flow exists,
499 500
    /// \n \c OPTIMAL if the problem has optimal solution
500 501
    /// (i.e. it is feasible and bounded), and the algorithm has found
501 502
    /// optimal flow and node potentials (primal and dual solutions),
502 503
    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
503 504
    /// and infinite upper bound. It means that the objective function
504 505
    /// is unbounded on that arc, however, note that it could actually be
505 506
    /// bounded over the feasible flows, but this algroithm cannot handle
506 507
    /// these cases.
507 508
    ///
508 509
    /// \see ProblemType, Method
509 510
    /// \see resetParams(), reset()
510 511
    ProblemType run(Method method = PARTIAL_AUGMENT, int factor = 8) {
511 512
      _alpha = factor;
512 513
      ProblemType pt = init();
513 514
      if (pt != OPTIMAL) return pt;
514 515
      start(method);
515 516
      return OPTIMAL;
516 517
    }
517 518

	
518 519
    /// \brief Reset all the parameters that have been given before.
519 520
    ///
520 521
    /// This function resets all the paramaters that have been given
521 522
    /// before using functions \ref lowerMap(), \ref upperMap(),
522 523
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
523 524
    ///
524 525
    /// It is useful for multiple \ref run() calls. Basically, all the given
525 526
    /// parameters are kept for the next \ref run() call, unless
526 527
    /// \ref resetParams() or \ref reset() is used.
527 528
    /// If the underlying digraph was also modified after the construction
528 529
    /// of the class or the last \ref reset() call, then the \ref reset()
529 530
    /// function must be used, otherwise \ref resetParams() is sufficient.
530 531
    ///
531 532
    /// For example,
532 533
    /// \code
533 534
    ///   CostScaling<ListDigraph> cs(graph);
534 535
    ///
535 536
    ///   // First run
536 537
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
537 538
    ///     .supplyMap(sup).run();
538 539
    ///
539 540
    ///   // Run again with modified cost map (resetParams() is not called,
540 541
    ///   // so only the cost map have to be set again)
541 542
    ///   cost[e] += 100;
542 543
    ///   cs.costMap(cost).run();
543 544
    ///
544 545
    ///   // Run again from scratch using resetParams()
545 546
    ///   // (the lower bounds will be set to zero on all arcs)
546 547
    ///   cs.resetParams();
547 548
    ///   cs.upperMap(capacity).costMap(cost)
548 549
    ///     .supplyMap(sup).run();
549 550
    /// \endcode
550 551
    ///
551 552
    /// \return <tt>(*this)</tt>
552 553
    ///
553 554
    /// \see reset(), run()
554 555
    CostScaling& resetParams() {
555 556
      for (int i = 0; i != _res_node_num; ++i) {
556 557
        _supply[i] = 0;
557 558
      }
558 559
      int limit = _first_out[_root];
559 560
      for (int j = 0; j != limit; ++j) {
560 561
        _lower[j] = 0;
561 562
        _upper[j] = INF;
562 563
        _scost[j] = _forward[j] ? 1 : -1;
563 564
      }
564 565
      for (int j = limit; j != _res_arc_num; ++j) {
565 566
        _lower[j] = 0;
566 567
        _upper[j] = INF;
567 568
        _scost[j] = 0;
568 569
        _scost[_reverse[j]] = 0;
569 570
      }
570 571
      _have_lower = false;
571 572
      return *this;
572 573
    }
573 574

	
574 575
    /// \brief Reset all the parameters that have been given before.
575 576
    ///
576 577
    /// This function resets all the paramaters that have been given
577 578
    /// before using functions \ref lowerMap(), \ref upperMap(),
578 579
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
579 580
    ///
580 581
    /// It is useful for multiple run() calls. If this function is not
581 582
    /// used, all the parameters given before are kept for the next
582 583
    /// \ref run() call.
583 584
    /// However, the underlying digraph must not be modified after this
584 585
    /// class have been constructed, since it copies and extends the graph.
585 586
    /// \return <tt>(*this)</tt>
586 587
    CostScaling& reset() {
587 588
      // Resize vectors
588 589
      _node_num = countNodes(_graph);
589 590
      _arc_num = countArcs(_graph);
590 591
      _res_node_num = _node_num + 1;
591 592
      _res_arc_num = 2 * (_arc_num + _node_num);
592 593
      _root = _node_num;
593 594

	
594 595
      _first_out.resize(_res_node_num + 1);
595 596
      _forward.resize(_res_arc_num);
596 597
      _source.resize(_res_arc_num);
597 598
      _target.resize(_res_arc_num);
598 599
      _reverse.resize(_res_arc_num);
599 600

	
600 601
      _lower.resize(_res_arc_num);
601 602
      _upper.resize(_res_arc_num);
602 603
      _scost.resize(_res_arc_num);
603 604
      _supply.resize(_res_node_num);
604 605

	
605 606
      _res_cap.resize(_res_arc_num);
606 607
      _cost.resize(_res_arc_num);
607 608
      _pi.resize(_res_node_num);
608 609
      _excess.resize(_res_node_num);
609 610
      _next_out.resize(_res_node_num);
610 611

	
611 612
      _arc_vec.reserve(_res_arc_num);
612 613
      _cost_vec.reserve(_res_arc_num);
613 614

	
614 615
      // Copy the graph
615 616
      int i = 0, j = 0, k = 2 * _arc_num + _node_num;
616 617
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
617 618
        _node_id[n] = i;
618 619
      }
619 620
      i = 0;
620 621
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
621 622
        _first_out[i] = j;
622 623
        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
623 624
          _arc_idf[a] = j;
624 625
          _forward[j] = true;
625 626
          _source[j] = i;
626 627
          _target[j] = _node_id[_graph.runningNode(a)];
627 628
        }
628 629
        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
629 630
          _arc_idb[a] = j;
630 631
          _forward[j] = false;
631 632
          _source[j] = i;
632 633
          _target[j] = _node_id[_graph.runningNode(a)];
633 634
        }
634 635
        _forward[j] = false;
635 636
        _source[j] = i;
636 637
        _target[j] = _root;
637 638
        _reverse[j] = k;
638 639
        _forward[k] = true;
639 640
        _source[k] = _root;
640 641
        _target[k] = i;
641 642
        _reverse[k] = j;
642 643
        ++j; ++k;
643 644
      }
644 645
      _first_out[i] = j;
645 646
      _first_out[_res_node_num] = k;
646 647
      for (ArcIt a(_graph); a != INVALID; ++a) {
647 648
        int fi = _arc_idf[a];
648 649
        int bi = _arc_idb[a];
649 650
        _reverse[fi] = bi;
650 651
        _reverse[bi] = fi;
651 652
      }
652 653

	
653 654
      // Reset parameters
654 655
      resetParams();
655 656
      return *this;
656 657
    }
657 658

	
658 659
    /// @}
659 660

	
660 661
    /// \name Query Functions
661 662
    /// The results of the algorithm can be obtained using these
662 663
    /// functions.\n
663 664
    /// The \ref run() function must be called before using them.
664 665

	
665 666
    /// @{
666 667

	
667 668
    /// \brief Return the total cost of the found flow.
668 669
    ///
669 670
    /// This function returns the total cost of the found flow.
670 671
    /// Its complexity is O(e).
671 672
    ///
672 673
    /// \note The return type of the function can be specified as a
673 674
    /// template parameter. For example,
674 675
    /// \code
675 676
    ///   cs.totalCost<double>();
676 677
    /// \endcode
677 678
    /// It is useful if the total cost cannot be stored in the \c Cost
678 679
    /// type of the algorithm, which is the default return type of the
679 680
    /// function.
680 681
    ///
681 682
    /// \pre \ref run() must be called before using this function.
682 683
    template <typename Number>
683 684
    Number totalCost() const {
684 685
      Number c = 0;
685 686
      for (ArcIt a(_graph); a != INVALID; ++a) {
686 687
        int i = _arc_idb[a];
687 688
        c += static_cast<Number>(_res_cap[i]) *
688 689
             (-static_cast<Number>(_scost[i]));
689 690
      }
690 691
      return c;
691 692
    }
692 693

	
693 694
#ifndef DOXYGEN
694 695
    Cost totalCost() const {
695 696
      return totalCost<Cost>();
696 697
    }
697 698
#endif
698 699

	
699 700
    /// \brief Return the flow on the given arc.
700 701
    ///
701 702
    /// This function returns the flow on the given arc.
702 703
    ///
703 704
    /// \pre \ref run() must be called before using this function.
704 705
    Value flow(const Arc& a) const {
705 706
      return _res_cap[_arc_idb[a]];
706 707
    }
707 708

	
708 709
    /// \brief Return the flow map (the primal solution).
709 710
    ///
710 711
    /// This function copies the flow value on each arc into the given
711 712
    /// map. The \c Value type of the algorithm must be convertible to
712 713
    /// the \c Value type of the map.
713 714
    ///
714 715
    /// \pre \ref run() must be called before using this function.
715 716
    template <typename FlowMap>
716 717
    void flowMap(FlowMap &map) const {
717 718
      for (ArcIt a(_graph); a != INVALID; ++a) {
718 719
        map.set(a, _res_cap[_arc_idb[a]]);
719 720
      }
720 721
    }
721 722

	
722 723
    /// \brief Return the potential (dual value) of the given node.
723 724
    ///
724 725
    /// This function returns the potential (dual value) of the
725 726
    /// given node.
726 727
    ///
727 728
    /// \pre \ref run() must be called before using this function.
728 729
    Cost potential(const Node& n) const {
729 730
      return static_cast<Cost>(_pi[_node_id[n]]);
730 731
    }
731 732

	
732 733
    /// \brief Return the potential map (the dual solution).
733 734
    ///
734 735
    /// This function copies the potential (dual value) of each node
735 736
    /// into the given map.
736 737
    /// The \c Cost type of the algorithm must be convertible to the
737 738
    /// \c Value type of the map.
738 739
    ///
739 740
    /// \pre \ref run() must be called before using this function.
740 741
    template <typename PotentialMap>
741 742
    void potentialMap(PotentialMap &map) const {
742 743
      for (NodeIt n(_graph); n != INVALID; ++n) {
743 744
        map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
744 745
      }
745 746
    }
746 747

	
747 748
    /// @}
748 749

	
749 750
  private:
750 751

	
751 752
    // Initialize the algorithm
752 753
    ProblemType init() {
753 754
      if (_res_node_num <= 1) return INFEASIBLE;
754 755

	
755 756
      // Check the sum of supply values
756 757
      _sum_supply = 0;
757 758
      for (int i = 0; i != _root; ++i) {
758 759
        _sum_supply += _supply[i];
759 760
      }
760 761
      if (_sum_supply > 0) return INFEASIBLE;
761 762

	
762 763

	
763 764
      // Initialize vectors
764 765
      for (int i = 0; i != _res_node_num; ++i) {
765 766
        _pi[i] = 0;
766 767
        _excess[i] = _supply[i];
767 768
      }
768 769

	
769 770
      // Remove infinite upper bounds and check negative arcs
770 771
      const Value MAX = std::numeric_limits<Value>::max();
771 772
      int last_out;
772 773
      if (_have_lower) {
773 774
        for (int i = 0; i != _root; ++i) {
774 775
          last_out = _first_out[i+1];
775 776
          for (int j = _first_out[i]; j != last_out; ++j) {
776 777
            if (_forward[j]) {
777 778
              Value c = _scost[j] < 0 ? _upper[j] : _lower[j];
778 779
              if (c >= MAX) return UNBOUNDED;
779 780
              _excess[i] -= c;
780 781
              _excess[_target[j]] += c;
781 782
            }
782 783
          }
783 784
        }
784 785
      } else {
785 786
        for (int i = 0; i != _root; ++i) {
786 787
          last_out = _first_out[i+1];
787 788
          for (int j = _first_out[i]; j != last_out; ++j) {
788 789
            if (_forward[j] && _scost[j] < 0) {
789 790
              Value c = _upper[j];
790 791
              if (c >= MAX) return UNBOUNDED;
791 792
              _excess[i] -= c;
792 793
              _excess[_target[j]] += c;
793 794
            }
794 795
          }
795 796
        }
796 797
      }
797 798
      Value ex, max_cap = 0;
798 799
      for (int i = 0; i != _res_node_num; ++i) {
799 800
        ex = _excess[i];
800 801
        _excess[i] = 0;
801 802
        if (ex < 0) max_cap -= ex;
802 803
      }
803 804
      for (int j = 0; j != _res_arc_num; ++j) {
804 805
        if (_upper[j] >= MAX) _upper[j] = max_cap;
805 806
      }
806 807

	
807 808
      // Initialize the large cost vector and the epsilon parameter
808 809
      _epsilon = 0;
809 810
      LargeCost lc;
810 811
      for (int i = 0; i != _root; ++i) {
811 812
        last_out = _first_out[i+1];
812 813
        for (int j = _first_out[i]; j != last_out; ++j) {
813 814
          lc = static_cast<LargeCost>(_scost[j]) * _res_node_num * _alpha;
814 815
          _cost[j] = lc;
815 816
          if (lc > _epsilon) _epsilon = lc;
816 817
        }
817 818
      }
818 819
      _epsilon /= _alpha;
819 820

	
820 821
      // Initialize maps for Circulation and remove non-zero lower bounds
821 822
      ConstMap<Arc, Value> low(0);
822 823
      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
823 824
      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
824 825
      ValueArcMap cap(_graph), flow(_graph);
825 826
      ValueNodeMap sup(_graph);
826 827
      for (NodeIt n(_graph); n != INVALID; ++n) {
827 828
        sup[n] = _supply[_node_id[n]];
828 829
      }
829 830
      if (_have_lower) {
830 831
        for (ArcIt a(_graph); a != INVALID; ++a) {
831 832
          int j = _arc_idf[a];
832 833
          Value c = _lower[j];
833 834
          cap[a] = _upper[j] - c;
834 835
          sup[_graph.source(a)] -= c;
835 836
          sup[_graph.target(a)] += c;
836 837
        }
837 838
      } else {
838 839
        for (ArcIt a(_graph); a != INVALID; ++a) {
839 840
          cap[a] = _upper[_arc_idf[a]];
840 841
        }
841 842
      }
842 843

	
843 844
      _sup_node_num = 0;
844 845
      for (NodeIt n(_graph); n != INVALID; ++n) {
845 846
        if (sup[n] > 0) ++_sup_node_num;
846 847
      }
847 848

	
848 849
      // Find a feasible flow using Circulation
849 850
      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
850 851
        circ(_graph, low, cap, sup);
851 852
      if (!circ.flowMap(flow).run()) return INFEASIBLE;
852 853

	
853 854
      // Set residual capacities and handle GEQ supply type
854 855
      if (_sum_supply < 0) {
855 856
        for (ArcIt a(_graph); a != INVALID; ++a) {
856 857
          Value fa = flow[a];
857 858
          _res_cap[_arc_idf[a]] = cap[a] - fa;
858 859
          _res_cap[_arc_idb[a]] = fa;
859 860
          sup[_graph.source(a)] -= fa;
860 861
          sup[_graph.target(a)] += fa;
861 862
        }
862 863
        for (NodeIt n(_graph); n != INVALID; ++n) {
863 864
          _excess[_node_id[n]] = sup[n];
864 865
        }
865 866
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
866 867
          int u = _target[a];
867 868
          int ra = _reverse[a];
868 869
          _res_cap[a] = -_sum_supply + 1;
869 870
          _res_cap[ra] = -_excess[u];
870 871
          _cost[a] = 0;
871 872
          _cost[ra] = 0;
872 873
          _excess[u] = 0;
873 874
        }
874 875
      } else {
875 876
        for (ArcIt a(_graph); a != INVALID; ++a) {
876 877
          Value fa = flow[a];
877 878
          _res_cap[_arc_idf[a]] = cap[a] - fa;
878 879
          _res_cap[_arc_idb[a]] = fa;
879 880
        }
880 881
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
881 882
          int ra = _reverse[a];
882 883
          _res_cap[a] = 0;
883 884
          _res_cap[ra] = 0;
884 885
          _cost[a] = 0;
885 886
          _cost[ra] = 0;
886 887
        }
887 888
      }
888 889

	
889 890
      return OPTIMAL;
890 891
    }
891 892

	
892 893
    // Execute the algorithm and transform the results
893 894
    void start(Method method) {
894 895
      // Maximum path length for partial augment
895 896
      const int MAX_PATH_LENGTH = 4;
896 897

	
897 898
      // Initialize data structures for buckets
898 899
      _max_rank = _alpha * _res_node_num;
899 900
      _buckets.resize(_max_rank);
900 901
      _bucket_next.resize(_res_node_num + 1);
901 902
      _bucket_prev.resize(_res_node_num + 1);
902 903
      _rank.resize(_res_node_num + 1);
903 904

	
904 905
      // Execute the algorithm
905 906
      switch (method) {
906 907
        case PUSH:
907 908
          startPush();
908 909
          break;
909 910
        case AUGMENT:
910 911
          startAugment();
911 912
          break;
912 913
        case PARTIAL_AUGMENT:
913 914
          startAugment(MAX_PATH_LENGTH);
914 915
          break;
915 916
      }
916 917

	
917 918
      // Compute node potentials for the original costs
918 919
      _arc_vec.clear();
919 920
      _cost_vec.clear();
920 921
      for (int j = 0; j != _res_arc_num; ++j) {
921 922
        if (_res_cap[j] > 0) {
922 923
          _arc_vec.push_back(IntPair(_source[j], _target[j]));
923 924
          _cost_vec.push_back(_scost[j]);
924 925
        }
925 926
      }
926 927
      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
927 928

	
928 929
      typename BellmanFord<StaticDigraph, LargeCostArcMap>
929 930
        ::template SetDistMap<LargeCostNodeMap>::Create bf(_sgr, _cost_map);
930 931
      bf.distMap(_pi_map);
931 932
      bf.init(0);
932 933
      bf.start();
933 934

	
934 935
      // Handle non-zero lower bounds
935 936
      if (_have_lower) {
936 937
        int limit = _first_out[_root];
937 938
        for (int j = 0; j != limit; ++j) {
938 939
          if (!_forward[j]) _res_cap[j] += _lower[j];
939 940
        }
940 941
      }
941 942
    }
942 943

	
943 944
    // Initialize a cost scaling phase
944 945
    void initPhase() {
945 946
      // Saturate arcs not satisfying the optimality condition
946 947
      for (int u = 0; u != _res_node_num; ++u) {
947 948
        int last_out = _first_out[u+1];
948 949
        LargeCost pi_u = _pi[u];
949 950
        for (int a = _first_out[u]; a != last_out; ++a) {
950 951
          int v = _target[a];
951 952
          if (_res_cap[a] > 0 && _cost[a] + pi_u - _pi[v] < 0) {
952 953
            Value delta = _res_cap[a];
953 954
            _excess[u] -= delta;
954 955
            _excess[v] += delta;
955 956
            _res_cap[a] = 0;
956 957
            _res_cap[_reverse[a]] += delta;
957 958
          }
958 959
        }
959 960
      }
960 961

	
961 962
      // Find active nodes (i.e. nodes with positive excess)
962 963
      for (int u = 0; u != _res_node_num; ++u) {
963 964
        if (_excess[u] > 0) _active_nodes.push_back(u);
964 965
      }
965 966

	
966 967
      // Initialize the next arcs
967 968
      for (int u = 0; u != _res_node_num; ++u) {
968 969
        _next_out[u] = _first_out[u];
969 970
      }
970 971
    }
971 972

	
972 973
    // Early termination heuristic
973 974
    bool earlyTermination() {
974 975
      const double EARLY_TERM_FACTOR = 3.0;
975 976

	
976 977
      // Build a static residual graph
977 978
      _arc_vec.clear();
978 979
      _cost_vec.clear();
979 980
      for (int j = 0; j != _res_arc_num; ++j) {
980 981
        if (_res_cap[j] > 0) {
981 982
          _arc_vec.push_back(IntPair(_source[j], _target[j]));
982 983
          _cost_vec.push_back(_cost[j] + 1);
983 984
        }
984 985
      }
985 986
      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
986 987

	
987 988
      // Run Bellman-Ford algorithm to check if the current flow is optimal
988 989
      BellmanFord<StaticDigraph, LargeCostArcMap> bf(_sgr, _cost_map);
989 990
      bf.init(0);
990 991
      bool done = false;
991 992
      int K = int(EARLY_TERM_FACTOR * std::sqrt(double(_res_node_num)));
992 993
      for (int i = 0; i < K && !done; ++i) {
993 994
        done = bf.processNextWeakRound();
994 995
      }
995 996
      return done;
996 997
    }
997 998

	
998 999
    // Global potential update heuristic
999 1000
    void globalUpdate() {
1000 1001
      int bucket_end = _root + 1;
1001 1002

	
1002 1003
      // Initialize buckets
1003 1004
      for (int r = 0; r != _max_rank; ++r) {
1004 1005
        _buckets[r] = bucket_end;
1005 1006
      }
1006 1007
      Value total_excess = 0;
1007 1008
      for (int i = 0; i != _res_node_num; ++i) {
1008 1009
        if (_excess[i] < 0) {
1009 1010
          _rank[i] = 0;
1010 1011
          _bucket_next[i] = _buckets[0];
1011 1012
          _bucket_prev[_buckets[0]] = i;
1012 1013
          _buckets[0] = i;
1013 1014
        } else {
1014 1015
          total_excess += _excess[i];
1015 1016
          _rank[i] = _max_rank;
1016 1017
        }
1017 1018
      }
1018 1019
      if (total_excess == 0) return;
1019 1020

	
1020 1021
      // Search the buckets
1021 1022
      int r = 0;
1022 1023
      for ( ; r != _max_rank; ++r) {
1023 1024
        while (_buckets[r] != bucket_end) {
1024 1025
          // Remove the first node from the current bucket
1025 1026
          int u = _buckets[r];
1026 1027
          _buckets[r] = _bucket_next[u];
1027 1028

	
1028 1029
          // Search the incomming arcs of u
1029 1030
          LargeCost pi_u = _pi[u];
1030 1031
          int last_out = _first_out[u+1];
1031 1032
          for (int a = _first_out[u]; a != last_out; ++a) {
1032 1033
            int ra = _reverse[a];
1033 1034
            if (_res_cap[ra] > 0) {
1034 1035
              int v = _source[ra];
1035 1036
              int old_rank_v = _rank[v];
1036 1037
              if (r < old_rank_v) {
1037 1038
                // Compute the new rank of v
1038 1039
                LargeCost nrc = (_cost[ra] + _pi[v] - pi_u) / _epsilon;
1039 1040
                int new_rank_v = old_rank_v;
1040 1041
                if (nrc < LargeCost(_max_rank))
1041 1042
                  new_rank_v = r + 1 + int(nrc);
1042 1043

	
1043 1044
                // Change the rank of v
1044 1045
                if (new_rank_v < old_rank_v) {
1045 1046
                  _rank[v] = new_rank_v;
1046 1047
                  _next_out[v] = _first_out[v];
1047 1048

	
1048 1049
                  // Remove v from its old bucket
1049 1050
                  if (old_rank_v < _max_rank) {
1050 1051
                    if (_buckets[old_rank_v] == v) {
1051 1052
                      _buckets[old_rank_v] = _bucket_next[v];
1052 1053
                    } else {
1053 1054
                      _bucket_next[_bucket_prev[v]] = _bucket_next[v];
1054 1055
                      _bucket_prev[_bucket_next[v]] = _bucket_prev[v];
1055 1056
                    }
1056 1057
                  }
1057 1058

	
1058 1059
                  // Insert v to its new bucket
1059 1060
                  _bucket_next[v] = _buckets[new_rank_v];
1060 1061
                  _bucket_prev[_buckets[new_rank_v]] = v;
1061 1062
                  _buckets[new_rank_v] = v;
1062 1063
                }
1063 1064
              }
1064 1065
            }
1065 1066
          }
1066 1067

	
1067 1068
          // Finish search if there are no more active nodes
1068 1069
          if (_excess[u] > 0) {
1069 1070
            total_excess -= _excess[u];
1070 1071
            if (total_excess <= 0) break;
1071 1072
          }
1072 1073
        }
1073 1074
        if (total_excess <= 0) break;
1074 1075
      }
1075 1076

	
1076 1077
      // Relabel nodes
1077 1078
      for (int u = 0; u != _res_node_num; ++u) {
1078 1079
        int k = std::min(_rank[u], r);
1079 1080
        if (k > 0) {
1080 1081
          _pi[u] -= _epsilon * k;
1081 1082
          _next_out[u] = _first_out[u];
1082 1083
        }
1083 1084
      }
1084 1085
    }
1085 1086

	
1086 1087
    /// Execute the algorithm performing augment and relabel operations
1087 1088
    void startAugment(int max_length = std::numeric_limits<int>::max()) {
1088 1089
      // Paramters for heuristics
1089 1090
      const int EARLY_TERM_EPSILON_LIMIT = 1000;
1090 1091
      const double GLOBAL_UPDATE_FACTOR = 3.0;
1091 1092

	
1092 1093
      const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1093 1094
        (_res_node_num + _sup_node_num * _sup_node_num));
1094 1095
      int next_update_limit = global_update_freq;
1095 1096

	
1096 1097
      int relabel_cnt = 0;
1097 1098

	
1098 1099
      // Perform cost scaling phases
1099 1100
      std::vector<int> path;
1100 1101
      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1101 1102
                                        1 : _epsilon / _alpha )
1102 1103
      {
1103 1104
        // Early termination heuristic
1104 1105
        if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1105 1106
          if (earlyTermination()) break;
1106 1107
        }
1107 1108

	
1108 1109
        // Initialize current phase
1109 1110
        initPhase();
1110 1111

	
1111 1112
        // Perform partial augment and relabel operations
1112 1113
        while (true) {
1113 1114
          // Select an active node (FIFO selection)
1114 1115
          while (_active_nodes.size() > 0 &&
1115 1116
                 _excess[_active_nodes.front()] <= 0) {
1116 1117
            _active_nodes.pop_front();
1117 1118
          }
1118 1119
          if (_active_nodes.size() == 0) break;
1119 1120
          int start = _active_nodes.front();
1120 1121

	
1121 1122
          // Find an augmenting path from the start node
1122 1123
          path.clear();
1123 1124
          int tip = start;
1124 1125
          while (_excess[tip] >= 0 && int(path.size()) < max_length) {
1125 1126
            int u;
1126 1127
            LargeCost min_red_cost, rc, pi_tip = _pi[tip];
1127 1128
            int last_out = _first_out[tip+1];
1128 1129
            for (int a = _next_out[tip]; a != last_out; ++a) {
1129 1130
              u = _target[a];
1130 1131
              if (_res_cap[a] > 0 && _cost[a] + pi_tip - _pi[u] < 0) {
1131 1132
                path.push_back(a);
1132 1133
                _next_out[tip] = a;
1133 1134
                tip = u;
1134 1135
                goto next_step;
1135 1136
              }
1136 1137
            }
1137 1138

	
1138 1139
            // Relabel tip node
1139 1140
            min_red_cost = std::numeric_limits<LargeCost>::max();
1140 1141
            if (tip != start) {
1141 1142
              int ra = _reverse[path.back()];
1142 1143
              min_red_cost = _cost[ra] + pi_tip - _pi[_target[ra]];
1143 1144
            }
1144 1145
            for (int a = _first_out[tip]; a != last_out; ++a) {
1145 1146
              rc = _cost[a] + pi_tip - _pi[_target[a]];
1146 1147
              if (_res_cap[a] > 0 && rc < min_red_cost) {
1147 1148
                min_red_cost = rc;
1148 1149
              }
1149 1150
            }
1150 1151
            _pi[tip] -= min_red_cost + _epsilon;
1151 1152
            _next_out[tip] = _first_out[tip];
1152 1153
            ++relabel_cnt;
1153 1154

	
1154 1155
            // Step back
1155 1156
            if (tip != start) {
1156 1157
              tip = _source[path.back()];
1157 1158
              path.pop_back();
1158 1159
            }
1159 1160

	
1160 1161
          next_step: ;
1161 1162
          }
1162 1163

	
1163 1164
          // Augment along the found path (as much flow as possible)
1164 1165
          Value delta;
1165 1166
          int pa, u, v = start;
1166 1167
          for (int i = 0; i != int(path.size()); ++i) {
1167 1168
            pa = path[i];
1168 1169
            u = v;
1169 1170
            v = _target[pa];
1170 1171
            delta = std::min(_res_cap[pa], _excess[u]);
1171 1172
            _res_cap[pa] -= delta;
1172 1173
            _res_cap[_reverse[pa]] += delta;
1173 1174
            _excess[u] -= delta;
1174 1175
            _excess[v] += delta;
1175 1176
            if (_excess[v] > 0 && _excess[v] <= delta)
1176 1177
              _active_nodes.push_back(v);
1177 1178
          }
1178 1179

	
1179 1180
          // Global update heuristic
1180 1181
          if (relabel_cnt >= next_update_limit) {
1181 1182
            globalUpdate();
1182 1183
            next_update_limit += global_update_freq;
1183 1184
          }
1184 1185
        }
1185 1186
      }
1186 1187
    }
1187 1188

	
1188 1189
    /// Execute the algorithm performing push and relabel operations
1189 1190
    void startPush() {
1190 1191
      // Paramters for heuristics
1191 1192
      const int EARLY_TERM_EPSILON_LIMIT = 1000;
1192 1193
      const double GLOBAL_UPDATE_FACTOR = 2.0;
1193 1194

	
1194 1195
      const int global_update_freq = int(GLOBAL_UPDATE_FACTOR *
1195 1196
        (_res_node_num + _sup_node_num * _sup_node_num));
1196 1197
      int next_update_limit = global_update_freq;
1197 1198

	
1198 1199
      int relabel_cnt = 0;
1199 1200

	
1200 1201
      // Perform cost scaling phases
1201 1202
      BoolVector hyper(_res_node_num, false);
1202 1203
      LargeCostVector hyper_cost(_res_node_num);
1203 1204
      for ( ; _epsilon >= 1; _epsilon = _epsilon < _alpha && _epsilon > 1 ?
1204 1205
                                        1 : _epsilon / _alpha )
1205 1206
      {
1206 1207
        // Early termination heuristic
1207 1208
        if (_epsilon <= EARLY_TERM_EPSILON_LIMIT) {
1208 1209
          if (earlyTermination()) break;
1209 1210
        }
1210 1211

	
1211 1212
        // Initialize current phase
1212 1213
        initPhase();
1213 1214

	
1214 1215
        // Perform push and relabel operations
1215 1216
        while (_active_nodes.size() > 0) {
1216 1217
          LargeCost min_red_cost, rc, pi_n;
1217 1218
          Value delta;
1218 1219
          int n, t, a, last_out = _res_arc_num;
1219 1220

	
1220 1221
        next_node:
1221 1222
          // Select an active node (FIFO selection)
1222 1223
          n = _active_nodes.front();
1223 1224
          last_out = _first_out[n+1];
1224 1225
          pi_n = _pi[n];
1225 1226

	
1226 1227
          // Perform push operations if there are admissible arcs
1227 1228
          if (_excess[n] > 0) {
1228 1229
            for (a = _next_out[n]; a != last_out; ++a) {
1229 1230
              if (_res_cap[a] > 0 &&
1230 1231
                  _cost[a] + pi_n - _pi[_target[a]] < 0) {
1231 1232
                delta = std::min(_res_cap[a], _excess[n]);
1232 1233
                t = _target[a];
1233 1234

	
1234 1235
                // Push-look-ahead heuristic
1235 1236
                Value ahead = -_excess[t];
1236 1237
                int last_out_t = _first_out[t+1];
1237 1238
                LargeCost pi_t = _pi[t];
1238 1239
                for (int ta = _next_out[t]; ta != last_out_t; ++ta) {
1239 1240
                  if (_res_cap[ta] > 0 &&
1240 1241
                      _cost[ta] + pi_t - _pi[_target[ta]] < 0)
1241 1242
                    ahead += _res_cap[ta];
1242 1243
                  if (ahead >= delta) break;
1243 1244
                }
1244 1245
                if (ahead < 0) ahead = 0;
1245 1246

	
1246 1247
                // Push flow along the arc
1247 1248
                if (ahead < delta && !hyper[t]) {
1248 1249
                  _res_cap[a] -= ahead;
1249 1250
                  _res_cap[_reverse[a]] += ahead;
1250 1251
                  _excess[n] -= ahead;
1251 1252
                  _excess[t] += ahead;
1252 1253
                  _active_nodes.push_front(t);
1253 1254
                  hyper[t] = true;
1254 1255
                  hyper_cost[t] = _cost[a] + pi_n - pi_t;
1255 1256
                  _next_out[n] = a;
1256 1257
                  goto next_node;
1257 1258
                } else {
1258 1259
                  _res_cap[a] -= delta;
1259 1260
                  _res_cap[_reverse[a]] += delta;
1260 1261
                  _excess[n] -= delta;
1261 1262
                  _excess[t] += delta;
1262 1263
                  if (_excess[t] > 0 && _excess[t] <= delta)
1263 1264
                    _active_nodes.push_back(t);
1264 1265
                }
1265 1266

	
1266 1267
                if (_excess[n] == 0) {
1267 1268
                  _next_out[n] = a;
1268 1269
                  goto remove_nodes;
1269 1270
                }
1270 1271
              }
1271 1272
            }
1272 1273
            _next_out[n] = a;
1273 1274
          }
1274 1275

	
1275 1276
          // Relabel the node if it is still active (or hyper)
1276 1277
          if (_excess[n] > 0 || hyper[n]) {
1277 1278
             min_red_cost = hyper[n] ? -hyper_cost[n] :
1278 1279
               std::numeric_limits<LargeCost>::max();
1279 1280
            for (int a = _first_out[n]; a != last_out; ++a) {
1280 1281
              rc = _cost[a] + pi_n - _pi[_target[a]];
1281 1282
              if (_res_cap[a] > 0 && rc < min_red_cost) {
1282 1283
                min_red_cost = rc;
1283 1284
              }
1284 1285
            }
1285 1286
            _pi[n] -= min_red_cost + _epsilon;
1286 1287
            _next_out[n] = _first_out[n];
1287 1288
            hyper[n] = false;
1288 1289
            ++relabel_cnt;
1289 1290
          }
1290 1291

	
1291 1292
          // Remove nodes that are not active nor hyper
1292 1293
        remove_nodes:
1293 1294
          while ( _active_nodes.size() > 0 &&
1294 1295
                  _excess[_active_nodes.front()] <= 0 &&
1295 1296
                  !hyper[_active_nodes.front()] ) {
1296 1297
            _active_nodes.pop_front();
1297 1298
          }
1298 1299

	
1299 1300
          // Global update heuristic
1300 1301
          if (relabel_cnt >= next_update_limit) {
1301 1302
            globalUpdate();
1302 1303
            for (int u = 0; u != _res_node_num; ++u)
1303 1304
              hyper[u] = false;
1304 1305
            next_update_limit += global_update_freq;
1305 1306
          }
1306 1307
        }
1307 1308
      }
1308 1309
    }
1309 1310

	
1310 1311
  }; //class CostScaling
1311 1312

	
1312 1313
  ///@}
1313 1314

	
1314 1315
} //namespace lemon
1315 1316

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

	
19 19
#ifndef LEMON_CYCLE_CANCELING_H
20 20
#define LEMON_CYCLE_CANCELING_H
21 21

	
22 22
/// \ingroup min_cost_flow_algs
23 23
/// \file
24 24
/// \brief Cycle-canceling algorithms for finding a minimum cost flow.
25 25

	
26 26
#include <vector>
27 27
#include <limits>
28 28

	
29 29
#include <lemon/core.h>
30 30
#include <lemon/maps.h>
31 31
#include <lemon/path.h>
32 32
#include <lemon/math.h>
33 33
#include <lemon/static_graph.h>
34 34
#include <lemon/adaptors.h>
35 35
#include <lemon/circulation.h>
36 36
#include <lemon/bellman_ford.h>
37 37
#include <lemon/howard_mmc.h>
38 38

	
39 39
namespace lemon {
40 40

	
41 41
  /// \addtogroup min_cost_flow_algs
42 42
  /// @{
43 43

	
44 44
  /// \brief Implementation of cycle-canceling algorithms for
45 45
  /// finding a \ref min_cost_flow "minimum cost flow".
46 46
  ///
47 47
  /// \ref CycleCanceling implements three different cycle-canceling
48 48
  /// algorithms for finding a \ref min_cost_flow "minimum cost flow"
49 49
  /// \ref amo93networkflows, \ref klein67primal,
50 50
  /// \ref goldberg89cyclecanceling.
51 51
  /// The most efficent one (both theoretically and practically)
52 52
  /// is the \ref CANCEL_AND_TIGHTEN "Cancel and Tighten" algorithm,
53 53
  /// thus it is the default method.
54 54
  /// It is strongly polynomial, but in practice, it is typically much
55 55
  /// slower than the scaling algorithms and NetworkSimplex.
56 56
  ///
57 57
  /// Most of the parameters of the problem (except for the digraph)
58 58
  /// can be given using separate functions, and the algorithm can be
59 59
  /// executed using the \ref run() function. If some parameters are not
60 60
  /// specified, then default values will be used.
61 61
  ///
62 62
  /// \tparam GR The digraph type the algorithm runs on.
63 63
  /// \tparam V The number type used for flow amounts, capacity bounds
64 64
  /// and supply values in the algorithm. By default, it is \c int.
65 65
  /// \tparam C The number type used for costs and potentials in the
66 66
  /// algorithm. By default, it is the same as \c V.
67 67
  ///
68
  /// \warning Both number types must be signed and all input data must
68
  /// \warning Both \c V and \c C must be signed number types.
69
  /// \warning All input data (capacities, supply values, and costs) must
69 70
  /// be integer.
70 71
  /// \warning This algorithm does not support negative costs for such
71 72
  /// arcs that have infinite upper bound.
72 73
  ///
73 74
  /// \note For more information about the three available methods,
74 75
  /// see \ref Method.
75 76
#ifdef DOXYGEN
76 77
  template <typename GR, typename V, typename C>
77 78
#else
78 79
  template <typename GR, typename V = int, typename C = V>
79 80
#endif
80 81
  class CycleCanceling
81 82
  {
82 83
  public:
83 84

	
84 85
    /// The type of the digraph
85 86
    typedef GR Digraph;
86 87
    /// The type of the flow amounts, capacity bounds and supply values
87 88
    typedef V Value;
88 89
    /// The type of the arc costs
89 90
    typedef C Cost;
90 91

	
91 92
  public:
92 93

	
93 94
    /// \brief Problem type constants for the \c run() function.
94 95
    ///
95 96
    /// Enum type containing the problem type constants that can be
96 97
    /// returned by the \ref run() function of the algorithm.
97 98
    enum ProblemType {
98 99
      /// The problem has no feasible solution (flow).
99 100
      INFEASIBLE,
100 101
      /// The problem has optimal solution (i.e. it is feasible and
101 102
      /// bounded), and the algorithm has found optimal flow and node
102 103
      /// potentials (primal and dual solutions).
103 104
      OPTIMAL,
104 105
      /// The digraph contains an arc of negative cost and infinite
105 106
      /// upper bound. It means that the objective function is unbounded
106 107
      /// on that arc, however, note that it could actually be bounded
107 108
      /// over the feasible flows, but this algroithm cannot handle
108 109
      /// these cases.
109 110
      UNBOUNDED
110 111
    };
111 112

	
112 113
    /// \brief Constants for selecting the used method.
113 114
    ///
114 115
    /// Enum type containing constants for selecting the used method
115 116
    /// for the \ref run() function.
116 117
    ///
117 118
    /// \ref CycleCanceling provides three different cycle-canceling
118 119
    /// methods. By default, \ref CANCEL_AND_TIGHTEN "Cancel and Tighten"
119 120
    /// is used, which proved to be the most efficient and the most robust
120 121
    /// on various test inputs.
121 122
    /// However, the other methods can be selected using the \ref run()
122 123
    /// function with the proper parameter.
123 124
    enum Method {
124 125
      /// A simple cycle-canceling method, which uses the
125 126
      /// \ref BellmanFord "Bellman-Ford" algorithm with limited iteration
126 127
      /// number for detecting negative cycles in the residual network.
127 128
      SIMPLE_CYCLE_CANCELING,
128 129
      /// The "Minimum Mean Cycle-Canceling" algorithm, which is a
129 130
      /// well-known strongly polynomial method
130 131
      /// \ref goldberg89cyclecanceling. It improves along a
131 132
      /// \ref min_mean_cycle "minimum mean cycle" in each iteration.
132 133
      /// Its running time complexity is O(n<sup>2</sup>m<sup>3</sup>log(n)).
133 134
      MINIMUM_MEAN_CYCLE_CANCELING,
134 135
      /// The "Cancel And Tighten" algorithm, which can be viewed as an
135 136
      /// improved version of the previous method
136 137
      /// \ref goldberg89cyclecanceling.
137 138
      /// It is faster both in theory and in practice, its running time
138 139
      /// complexity is O(n<sup>2</sup>m<sup>2</sup>log(n)).
139 140
      CANCEL_AND_TIGHTEN
140 141
    };
141 142

	
142 143
  private:
143 144

	
144 145
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
145 146

	
146 147
    typedef std::vector<int> IntVector;
147 148
    typedef std::vector<double> DoubleVector;
148 149
    typedef std::vector<Value> ValueVector;
149 150
    typedef std::vector<Cost> CostVector;
150 151
    typedef std::vector<char> BoolVector;
151 152
    // Note: vector<char> is used instead of vector<bool> for efficiency reasons
152 153

	
153 154
  private:
154 155

	
155 156
    template <typename KT, typename VT>
156 157
    class StaticVectorMap {
157 158
    public:
158 159
      typedef KT Key;
159 160
      typedef VT Value;
160 161

	
161 162
      StaticVectorMap(std::vector<Value>& v) : _v(v) {}
162 163

	
163 164
      const Value& operator[](const Key& key) const {
164 165
        return _v[StaticDigraph::id(key)];
165 166
      }
166 167

	
167 168
      Value& operator[](const Key& key) {
168 169
        return _v[StaticDigraph::id(key)];
169 170
      }
170 171

	
171 172
      void set(const Key& key, const Value& val) {
172 173
        _v[StaticDigraph::id(key)] = val;
173 174
      }
174 175

	
175 176
    private:
176 177
      std::vector<Value>& _v;
177 178
    };
178 179

	
179 180
    typedef StaticVectorMap<StaticDigraph::Node, Cost> CostNodeMap;
180 181
    typedef StaticVectorMap<StaticDigraph::Arc, Cost> CostArcMap;
181 182

	
182 183
  private:
183 184

	
184 185

	
185 186
    // Data related to the underlying digraph
186 187
    const GR &_graph;
187 188
    int _node_num;
188 189
    int _arc_num;
189 190
    int _res_node_num;
190 191
    int _res_arc_num;
191 192
    int _root;
192 193

	
193 194
    // Parameters of the problem
194 195
    bool _have_lower;
195 196
    Value _sum_supply;
196 197

	
197 198
    // Data structures for storing the digraph
198 199
    IntNodeMap _node_id;
199 200
    IntArcMap _arc_idf;
200 201
    IntArcMap _arc_idb;
201 202
    IntVector _first_out;
202 203
    BoolVector _forward;
203 204
    IntVector _source;
204 205
    IntVector _target;
205 206
    IntVector _reverse;
206 207

	
207 208
    // Node and arc data
208 209
    ValueVector _lower;
209 210
    ValueVector _upper;
210 211
    CostVector _cost;
211 212
    ValueVector _supply;
212 213

	
213 214
    ValueVector _res_cap;
214 215
    CostVector _pi;
215 216

	
216 217
    // Data for a StaticDigraph structure
217 218
    typedef std::pair<int, int> IntPair;
218 219
    StaticDigraph _sgr;
219 220
    std::vector<IntPair> _arc_vec;
220 221
    std::vector<Cost> _cost_vec;
221 222
    IntVector _id_vec;
222 223
    CostArcMap _cost_map;
223 224
    CostNodeMap _pi_map;
224 225

	
225 226
  public:
226 227

	
227 228
    /// \brief Constant for infinite upper bounds (capacities).
228 229
    ///
229 230
    /// Constant for infinite upper bounds (capacities).
230 231
    /// It is \c std::numeric_limits<Value>::infinity() if available,
231 232
    /// \c std::numeric_limits<Value>::max() otherwise.
232 233
    const Value INF;
233 234

	
234 235
  public:
235 236

	
236 237
    /// \brief Constructor.
237 238
    ///
238 239
    /// The constructor of the class.
239 240
    ///
240 241
    /// \param graph The digraph the algorithm runs on.
241 242
    CycleCanceling(const GR& graph) :
242 243
      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
243 244
      _cost_map(_cost_vec), _pi_map(_pi),
244 245
      INF(std::numeric_limits<Value>::has_infinity ?
245 246
          std::numeric_limits<Value>::infinity() :
246 247
          std::numeric_limits<Value>::max())
247 248
    {
248 249
      // Check the number types
249 250
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
250 251
        "The flow type of CycleCanceling must be signed");
251 252
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
252 253
        "The cost type of CycleCanceling must be signed");
253 254

	
254 255
      // Reset data structures
255 256
      reset();
256 257
    }
257 258

	
258 259
    /// \name Parameters
259 260
    /// The parameters of the algorithm can be specified using these
260 261
    /// functions.
261 262

	
262 263
    /// @{
263 264

	
264 265
    /// \brief Set the lower bounds on the arcs.
265 266
    ///
266 267
    /// This function sets the lower bounds on the arcs.
267 268
    /// If it is not used before calling \ref run(), the lower bounds
268 269
    /// will be set to zero on all arcs.
269 270
    ///
270 271
    /// \param map An arc map storing the lower bounds.
271 272
    /// Its \c Value type must be convertible to the \c Value type
272 273
    /// of the algorithm.
273 274
    ///
274 275
    /// \return <tt>(*this)</tt>
275 276
    template <typename LowerMap>
276 277
    CycleCanceling& lowerMap(const LowerMap& map) {
277 278
      _have_lower = true;
278 279
      for (ArcIt a(_graph); a != INVALID; ++a) {
279 280
        _lower[_arc_idf[a]] = map[a];
280 281
        _lower[_arc_idb[a]] = map[a];
281 282
      }
282 283
      return *this;
283 284
    }
284 285

	
285 286
    /// \brief Set the upper bounds (capacities) on the arcs.
286 287
    ///
287 288
    /// This function sets the upper bounds (capacities) on the arcs.
288 289
    /// If it is not used before calling \ref run(), the upper bounds
289 290
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
290 291
    /// unbounded from above).
291 292
    ///
292 293
    /// \param map An arc map storing the upper bounds.
293 294
    /// Its \c Value type must be convertible to the \c Value type
294 295
    /// of the algorithm.
295 296
    ///
296 297
    /// \return <tt>(*this)</tt>
297 298
    template<typename UpperMap>
298 299
    CycleCanceling& upperMap(const UpperMap& map) {
299 300
      for (ArcIt a(_graph); a != INVALID; ++a) {
300 301
        _upper[_arc_idf[a]] = map[a];
301 302
      }
302 303
      return *this;
303 304
    }
304 305

	
305 306
    /// \brief Set the costs of the arcs.
306 307
    ///
307 308
    /// This function sets the costs of the arcs.
308 309
    /// If it is not used before calling \ref run(), the costs
309 310
    /// will be set to \c 1 on all arcs.
310 311
    ///
311 312
    /// \param map An arc map storing the costs.
312 313
    /// Its \c Value type must be convertible to the \c Cost type
313 314
    /// of the algorithm.
314 315
    ///
315 316
    /// \return <tt>(*this)</tt>
316 317
    template<typename CostMap>
317 318
    CycleCanceling& costMap(const CostMap& map) {
318 319
      for (ArcIt a(_graph); a != INVALID; ++a) {
319 320
        _cost[_arc_idf[a]] =  map[a];
320 321
        _cost[_arc_idb[a]] = -map[a];
321 322
      }
322 323
      return *this;
323 324
    }
324 325

	
325 326
    /// \brief Set the supply values of the nodes.
326 327
    ///
327 328
    /// This function sets the supply values of the nodes.
328 329
    /// If neither this function nor \ref stSupply() is used before
329 330
    /// calling \ref run(), the supply of each node will be set to zero.
330 331
    ///
331 332
    /// \param map A node map storing the supply values.
332 333
    /// Its \c Value type must be convertible to the \c Value type
333 334
    /// of the algorithm.
334 335
    ///
335 336
    /// \return <tt>(*this)</tt>
336 337
    template<typename SupplyMap>
337 338
    CycleCanceling& supplyMap(const SupplyMap& map) {
338 339
      for (NodeIt n(_graph); n != INVALID; ++n) {
339 340
        _supply[_node_id[n]] = map[n];
340 341
      }
341 342
      return *this;
342 343
    }
343 344

	
344 345
    /// \brief Set single source and target nodes and a supply value.
345 346
    ///
346 347
    /// This function sets a single source node and a single target node
347 348
    /// and the required flow value.
348 349
    /// If neither this function nor \ref supplyMap() is used before
349 350
    /// calling \ref run(), the supply of each node will be set to zero.
350 351
    ///
351 352
    /// Using this function has the same effect as using \ref supplyMap()
352 353
    /// with such a map in which \c k is assigned to \c s, \c -k is
353 354
    /// assigned to \c t and all other nodes have zero supply value.
354 355
    ///
355 356
    /// \param s The source node.
356 357
    /// \param t The target node.
357 358
    /// \param k The required amount of flow from node \c s to node \c t
358 359
    /// (i.e. the supply of \c s and the demand of \c t).
359 360
    ///
360 361
    /// \return <tt>(*this)</tt>
361 362
    CycleCanceling& stSupply(const Node& s, const Node& t, Value k) {
362 363
      for (int i = 0; i != _res_node_num; ++i) {
363 364
        _supply[i] = 0;
364 365
      }
365 366
      _supply[_node_id[s]] =  k;
366 367
      _supply[_node_id[t]] = -k;
367 368
      return *this;
368 369
    }
369 370

	
370 371
    /// @}
371 372

	
372 373
    /// \name Execution control
373 374
    /// The algorithm can be executed using \ref run().
374 375

	
375 376
    /// @{
376 377

	
377 378
    /// \brief Run the algorithm.
378 379
    ///
379 380
    /// This function runs the algorithm.
380 381
    /// The paramters can be specified using functions \ref lowerMap(),
381 382
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
382 383
    /// For example,
383 384
    /// \code
384 385
    ///   CycleCanceling<ListDigraph> cc(graph);
385 386
    ///   cc.lowerMap(lower).upperMap(upper).costMap(cost)
386 387
    ///     .supplyMap(sup).run();
387 388
    /// \endcode
388 389
    ///
389 390
    /// This function can be called more than once. All the given parameters
390 391
    /// are kept for the next call, unless \ref resetParams() or \ref reset()
391 392
    /// is used, thus only the modified parameters have to be set again.
392 393
    /// If the underlying digraph was also modified after the construction
393 394
    /// of the class (or the last \ref reset() call), then the \ref reset()
394 395
    /// function must be called.
395 396
    ///
396 397
    /// \param method The cycle-canceling method that will be used.
397 398
    /// For more information, see \ref Method.
398 399
    ///
399 400
    /// \return \c INFEASIBLE if no feasible flow exists,
400 401
    /// \n \c OPTIMAL if the problem has optimal solution
401 402
    /// (i.e. it is feasible and bounded), and the algorithm has found
402 403
    /// optimal flow and node potentials (primal and dual solutions),
403 404
    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
404 405
    /// and infinite upper bound. It means that the objective function
405 406
    /// is unbounded on that arc, however, note that it could actually be
406 407
    /// bounded over the feasible flows, but this algroithm cannot handle
407 408
    /// these cases.
408 409
    ///
409 410
    /// \see ProblemType, Method
410 411
    /// \see resetParams(), reset()
411 412
    ProblemType run(Method method = CANCEL_AND_TIGHTEN) {
412 413
      ProblemType pt = init();
413 414
      if (pt != OPTIMAL) return pt;
414 415
      start(method);
415 416
      return OPTIMAL;
416 417
    }
417 418

	
418 419
    /// \brief Reset all the parameters that have been given before.
419 420
    ///
420 421
    /// This function resets all the paramaters that have been given
421 422
    /// before using functions \ref lowerMap(), \ref upperMap(),
422 423
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
423 424
    ///
424 425
    /// It is useful for multiple \ref run() calls. Basically, all the given
425 426
    /// parameters are kept for the next \ref run() call, unless
426 427
    /// \ref resetParams() or \ref reset() is used.
427 428
    /// If the underlying digraph was also modified after the construction
428 429
    /// of the class or the last \ref reset() call, then the \ref reset()
429 430
    /// function must be used, otherwise \ref resetParams() is sufficient.
430 431
    ///
431 432
    /// For example,
432 433
    /// \code
433 434
    ///   CycleCanceling<ListDigraph> cs(graph);
434 435
    ///
435 436
    ///   // First run
436 437
    ///   cc.lowerMap(lower).upperMap(upper).costMap(cost)
437 438
    ///     .supplyMap(sup).run();
438 439
    ///
439 440
    ///   // Run again with modified cost map (resetParams() is not called,
440 441
    ///   // so only the cost map have to be set again)
441 442
    ///   cost[e] += 100;
442 443
    ///   cc.costMap(cost).run();
443 444
    ///
444 445
    ///   // Run again from scratch using resetParams()
445 446
    ///   // (the lower bounds will be set to zero on all arcs)
446 447
    ///   cc.resetParams();
447 448
    ///   cc.upperMap(capacity).costMap(cost)
448 449
    ///     .supplyMap(sup).run();
449 450
    /// \endcode
450 451
    ///
451 452
    /// \return <tt>(*this)</tt>
452 453
    ///
453 454
    /// \see reset(), run()
454 455
    CycleCanceling& resetParams() {
455 456
      for (int i = 0; i != _res_node_num; ++i) {
456 457
        _supply[i] = 0;
457 458
      }
458 459
      int limit = _first_out[_root];
459 460
      for (int j = 0; j != limit; ++j) {
460 461
        _lower[j] = 0;
461 462
        _upper[j] = INF;
462 463
        _cost[j] = _forward[j] ? 1 : -1;
463 464
      }
464 465
      for (int j = limit; j != _res_arc_num; ++j) {
465 466
        _lower[j] = 0;
466 467
        _upper[j] = INF;
467 468
        _cost[j] = 0;
468 469
        _cost[_reverse[j]] = 0;
469 470
      }
470 471
      _have_lower = false;
471 472
      return *this;
472 473
    }
473 474

	
474 475
    /// \brief Reset the internal data structures and all the parameters
475 476
    /// that have been given before.
476 477
    ///
477 478
    /// This function resets the internal data structures and all the
478 479
    /// paramaters that have been given before using functions \ref lowerMap(),
479 480
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
480 481
    ///
481 482
    /// It is useful for multiple \ref run() calls. Basically, all the given
482 483
    /// parameters are kept for the next \ref run() call, unless
483 484
    /// \ref resetParams() or \ref reset() is used.
484 485
    /// If the underlying digraph was also modified after the construction
485 486
    /// of the class or the last \ref reset() call, then the \ref reset()
486 487
    /// function must be used, otherwise \ref resetParams() is sufficient.
487 488
    ///
488 489
    /// See \ref resetParams() for examples.
489 490
    ///
490 491
    /// \return <tt>(*this)</tt>
491 492
    ///
492 493
    /// \see resetParams(), run()
493 494
    CycleCanceling& reset() {
494 495
      // Resize vectors
495 496
      _node_num = countNodes(_graph);
496 497
      _arc_num = countArcs(_graph);
497 498
      _res_node_num = _node_num + 1;
498 499
      _res_arc_num = 2 * (_arc_num + _node_num);
499 500
      _root = _node_num;
500 501

	
501 502
      _first_out.resize(_res_node_num + 1);
502 503
      _forward.resize(_res_arc_num);
503 504
      _source.resize(_res_arc_num);
504 505
      _target.resize(_res_arc_num);
505 506
      _reverse.resize(_res_arc_num);
506 507

	
507 508
      _lower.resize(_res_arc_num);
508 509
      _upper.resize(_res_arc_num);
509 510
      _cost.resize(_res_arc_num);
510 511
      _supply.resize(_res_node_num);
511 512

	
512 513
      _res_cap.resize(_res_arc_num);
513 514
      _pi.resize(_res_node_num);
514 515

	
515 516
      _arc_vec.reserve(_res_arc_num);
516 517
      _cost_vec.reserve(_res_arc_num);
517 518
      _id_vec.reserve(_res_arc_num);
518 519

	
519 520
      // Copy the graph
520 521
      int i = 0, j = 0, k = 2 * _arc_num + _node_num;
521 522
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
522 523
        _node_id[n] = i;
523 524
      }
524 525
      i = 0;
525 526
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
526 527
        _first_out[i] = j;
527 528
        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
528 529
          _arc_idf[a] = j;
529 530
          _forward[j] = true;
530 531
          _source[j] = i;
531 532
          _target[j] = _node_id[_graph.runningNode(a)];
532 533
        }
533 534
        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
534 535
          _arc_idb[a] = j;
535 536
          _forward[j] = false;
536 537
          _source[j] = i;
537 538
          _target[j] = _node_id[_graph.runningNode(a)];
538 539
        }
539 540
        _forward[j] = false;
540 541
        _source[j] = i;
541 542
        _target[j] = _root;
542 543
        _reverse[j] = k;
543 544
        _forward[k] = true;
544 545
        _source[k] = _root;
545 546
        _target[k] = i;
546 547
        _reverse[k] = j;
547 548
        ++j; ++k;
548 549
      }
549 550
      _first_out[i] = j;
550 551
      _first_out[_res_node_num] = k;
551 552
      for (ArcIt a(_graph); a != INVALID; ++a) {
552 553
        int fi = _arc_idf[a];
553 554
        int bi = _arc_idb[a];
554 555
        _reverse[fi] = bi;
555 556
        _reverse[bi] = fi;
556 557
      }
557 558

	
558 559
      // Reset parameters
559 560
      resetParams();
560 561
      return *this;
561 562
    }
562 563

	
563 564
    /// @}
564 565

	
565 566
    /// \name Query Functions
566 567
    /// The results of the algorithm can be obtained using these
567 568
    /// functions.\n
568 569
    /// The \ref run() function must be called before using them.
569 570

	
570 571
    /// @{
571 572

	
572 573
    /// \brief Return the total cost of the found flow.
573 574
    ///
574 575
    /// This function returns the total cost of the found flow.
575 576
    /// Its complexity is O(e).
576 577
    ///
577 578
    /// \note The return type of the function can be specified as a
578 579
    /// template parameter. For example,
579 580
    /// \code
580 581
    ///   cc.totalCost<double>();
581 582
    /// \endcode
582 583
    /// It is useful if the total cost cannot be stored in the \c Cost
583 584
    /// type of the algorithm, which is the default return type of the
584 585
    /// function.
585 586
    ///
586 587
    /// \pre \ref run() must be called before using this function.
587 588
    template <typename Number>
588 589
    Number totalCost() const {
589 590
      Number c = 0;
590 591
      for (ArcIt a(_graph); a != INVALID; ++a) {
591 592
        int i = _arc_idb[a];
592 593
        c += static_cast<Number>(_res_cap[i]) *
593 594
             (-static_cast<Number>(_cost[i]));
594 595
      }
595 596
      return c;
596 597
    }
597 598

	
598 599
#ifndef DOXYGEN
599 600
    Cost totalCost() const {
600 601
      return totalCost<Cost>();
601 602
    }
602 603
#endif
603 604

	
604 605
    /// \brief Return the flow on the given arc.
605 606
    ///
606 607
    /// This function returns the flow on the given arc.
607 608
    ///
608 609
    /// \pre \ref run() must be called before using this function.
609 610
    Value flow(const Arc& a) const {
610 611
      return _res_cap[_arc_idb[a]];
611 612
    }
612 613

	
613 614
    /// \brief Return the flow map (the primal solution).
614 615
    ///
615 616
    /// This function copies the flow value on each arc into the given
616 617
    /// map. The \c Value type of the algorithm must be convertible to
617 618
    /// the \c Value type of the map.
618 619
    ///
619 620
    /// \pre \ref run() must be called before using this function.
620 621
    template <typename FlowMap>
621 622
    void flowMap(FlowMap &map) const {
622 623
      for (ArcIt a(_graph); a != INVALID; ++a) {
623 624
        map.set(a, _res_cap[_arc_idb[a]]);
624 625
      }
625 626
    }
626 627

	
627 628
    /// \brief Return the potential (dual value) of the given node.
628 629
    ///
629 630
    /// This function returns the potential (dual value) of the
630 631
    /// given node.
631 632
    ///
632 633
    /// \pre \ref run() must be called before using this function.
633 634
    Cost potential(const Node& n) const {
634 635
      return static_cast<Cost>(_pi[_node_id[n]]);
635 636
    }
636 637

	
637 638
    /// \brief Return the potential map (the dual solution).
638 639
    ///
639 640
    /// This function copies the potential (dual value) of each node
640 641
    /// into the given map.
641 642
    /// The \c Cost type of the algorithm must be convertible to the
642 643
    /// \c Value type of the map.
643 644
    ///
644 645
    /// \pre \ref run() must be called before using this function.
645 646
    template <typename PotentialMap>
646 647
    void potentialMap(PotentialMap &map) const {
647 648
      for (NodeIt n(_graph); n != INVALID; ++n) {
648 649
        map.set(n, static_cast<Cost>(_pi[_node_id[n]]));
649 650
      }
650 651
    }
651 652

	
652 653
    /// @}
653 654

	
654 655
  private:
655 656

	
656 657
    // Initialize the algorithm
657 658
    ProblemType init() {
658 659
      if (_res_node_num <= 1) return INFEASIBLE;
659 660

	
660 661
      // Check the sum of supply values
661 662
      _sum_supply = 0;
662 663
      for (int i = 0; i != _root; ++i) {
663 664
        _sum_supply += _supply[i];
664 665
      }
665 666
      if (_sum_supply > 0) return INFEASIBLE;
666 667

	
667 668

	
668 669
      // Initialize vectors
669 670
      for (int i = 0; i != _res_node_num; ++i) {
670 671
        _pi[i] = 0;
671 672
      }
672 673
      ValueVector excess(_supply);
673 674

	
674 675
      // Remove infinite upper bounds and check negative arcs
675 676
      const Value MAX = std::numeric_limits<Value>::max();
676 677
      int last_out;
677 678
      if (_have_lower) {
678 679
        for (int i = 0; i != _root; ++i) {
679 680
          last_out = _first_out[i+1];
680 681
          for (int j = _first_out[i]; j != last_out; ++j) {
681 682
            if (_forward[j]) {
682 683
              Value c = _cost[j] < 0 ? _upper[j] : _lower[j];
683 684
              if (c >= MAX) return UNBOUNDED;
684 685
              excess[i] -= c;
685 686
              excess[_target[j]] += c;
686 687
            }
687 688
          }
688 689
        }
689 690
      } else {
690 691
        for (int i = 0; i != _root; ++i) {
691 692
          last_out = _first_out[i+1];
692 693
          for (int j = _first_out[i]; j != last_out; ++j) {
693 694
            if (_forward[j] && _cost[j] < 0) {
694 695
              Value c = _upper[j];
695 696
              if (c >= MAX) return UNBOUNDED;
696 697
              excess[i] -= c;
697 698
              excess[_target[j]] += c;
698 699
            }
699 700
          }
700 701
        }
701 702
      }
702 703
      Value ex, max_cap = 0;
703 704
      for (int i = 0; i != _res_node_num; ++i) {
704 705
        ex = excess[i];
705 706
        if (ex < 0) max_cap -= ex;
706 707
      }
707 708
      for (int j = 0; j != _res_arc_num; ++j) {
708 709
        if (_upper[j] >= MAX) _upper[j] = max_cap;
709 710
      }
710 711

	
711 712
      // Initialize maps for Circulation and remove non-zero lower bounds
712 713
      ConstMap<Arc, Value> low(0);
713 714
      typedef typename Digraph::template ArcMap<Value> ValueArcMap;
714 715
      typedef typename Digraph::template NodeMap<Value> ValueNodeMap;
715 716
      ValueArcMap cap(_graph), flow(_graph);
716 717
      ValueNodeMap sup(_graph);
717 718
      for (NodeIt n(_graph); n != INVALID; ++n) {
718 719
        sup[n] = _supply[_node_id[n]];
719 720
      }
720 721
      if (_have_lower) {
721 722
        for (ArcIt a(_graph); a != INVALID; ++a) {
722 723
          int j = _arc_idf[a];
723 724
          Value c = _lower[j];
724 725
          cap[a] = _upper[j] - c;
725 726
          sup[_graph.source(a)] -= c;
726 727
          sup[_graph.target(a)] += c;
727 728
        }
728 729
      } else {
729 730
        for (ArcIt a(_graph); a != INVALID; ++a) {
730 731
          cap[a] = _upper[_arc_idf[a]];
731 732
        }
732 733
      }
733 734

	
734 735
      // Find a feasible flow using Circulation
735 736
      Circulation<Digraph, ConstMap<Arc, Value>, ValueArcMap, ValueNodeMap>
736 737
        circ(_graph, low, cap, sup);
737 738
      if (!circ.flowMap(flow).run()) return INFEASIBLE;
738 739

	
739 740
      // Set residual capacities and handle GEQ supply type
740 741
      if (_sum_supply < 0) {
741 742
        for (ArcIt a(_graph); a != INVALID; ++a) {
742 743
          Value fa = flow[a];
743 744
          _res_cap[_arc_idf[a]] = cap[a] - fa;
744 745
          _res_cap[_arc_idb[a]] = fa;
745 746
          sup[_graph.source(a)] -= fa;
746 747
          sup[_graph.target(a)] += fa;
747 748
        }
748 749
        for (NodeIt n(_graph); n != INVALID; ++n) {
749 750
          excess[_node_id[n]] = sup[n];
750 751
        }
751 752
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
752 753
          int u = _target[a];
753 754
          int ra = _reverse[a];
754 755
          _res_cap[a] = -_sum_supply + 1;
755 756
          _res_cap[ra] = -excess[u];
756 757
          _cost[a] = 0;
757 758
          _cost[ra] = 0;
758 759
        }
759 760
      } else {
760 761
        for (ArcIt a(_graph); a != INVALID; ++a) {
761 762
          Value fa = flow[a];
762 763
          _res_cap[_arc_idf[a]] = cap[a] - fa;
763 764
          _res_cap[_arc_idb[a]] = fa;
764 765
        }
765 766
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
766 767
          int ra = _reverse[a];
767 768
          _res_cap[a] = 1;
768 769
          _res_cap[ra] = 0;
769 770
          _cost[a] = 0;
770 771
          _cost[ra] = 0;
771 772
        }
772 773
      }
773 774

	
774 775
      return OPTIMAL;
775 776
    }
776 777

	
777 778
    // Build a StaticDigraph structure containing the current
778 779
    // residual network
779 780
    void buildResidualNetwork() {
780 781
      _arc_vec.clear();
781 782
      _cost_vec.clear();
782 783
      _id_vec.clear();
783 784
      for (int j = 0; j != _res_arc_num; ++j) {
784 785
        if (_res_cap[j] > 0) {
785 786
          _arc_vec.push_back(IntPair(_source[j], _target[j]));
786 787
          _cost_vec.push_back(_cost[j]);
787 788
          _id_vec.push_back(j);
788 789
        }
789 790
      }
790 791
      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
791 792
    }
792 793

	
793 794
    // Execute the algorithm and transform the results
794 795
    void start(Method method) {
795 796
      // Execute the algorithm
796 797
      switch (method) {
797 798
        case SIMPLE_CYCLE_CANCELING:
798 799
          startSimpleCycleCanceling();
799 800
          break;
800 801
        case MINIMUM_MEAN_CYCLE_CANCELING:
801 802
          startMinMeanCycleCanceling();
802 803
          break;
803 804
        case CANCEL_AND_TIGHTEN:
804 805
          startCancelAndTighten();
805 806
          break;
806 807
      }
807 808

	
808 809
      // Compute node potentials
809 810
      if (method != SIMPLE_CYCLE_CANCELING) {
810 811
        buildResidualNetwork();
811 812
        typename BellmanFord<StaticDigraph, CostArcMap>
812 813
          ::template SetDistMap<CostNodeMap>::Create bf(_sgr, _cost_map);
813 814
        bf.distMap(_pi_map);
814 815
        bf.init(0);
815 816
        bf.start();
816 817
      }
817 818

	
818 819
      // Handle non-zero lower bounds
819 820
      if (_have_lower) {
820 821
        int limit = _first_out[_root];
821 822
        for (int j = 0; j != limit; ++j) {
822 823
          if (!_forward[j]) _res_cap[j] += _lower[j];
823 824
        }
824 825
      }
825 826
    }
826 827

	
827 828
    // Execute the "Simple Cycle Canceling" method
828 829
    void startSimpleCycleCanceling() {
829 830
      // Constants for computing the iteration limits
830 831
      const int BF_FIRST_LIMIT  = 2;
831 832
      const double BF_LIMIT_FACTOR = 1.5;
832 833

	
833 834
      typedef StaticVectorMap<StaticDigraph::Arc, Value> FilterMap;
834 835
      typedef FilterArcs<StaticDigraph, FilterMap> ResDigraph;
835 836
      typedef StaticVectorMap<StaticDigraph::Node, StaticDigraph::Arc> PredMap;
836 837
      typedef typename BellmanFord<ResDigraph, CostArcMap>
837 838
        ::template SetDistMap<CostNodeMap>
838 839
        ::template SetPredMap<PredMap>::Create BF;
839 840

	
840 841
      // Build the residual network
841 842
      _arc_vec.clear();
842 843
      _cost_vec.clear();
843 844
      for (int j = 0; j != _res_arc_num; ++j) {
844 845
        _arc_vec.push_back(IntPair(_source[j], _target[j]));
845 846
        _cost_vec.push_back(_cost[j]);
846 847
      }
847 848
      _sgr.build(_res_node_num, _arc_vec.begin(), _arc_vec.end());
848 849

	
849 850
      FilterMap filter_map(_res_cap);
850 851
      ResDigraph rgr(_sgr, filter_map);
851 852
      std::vector<int> cycle;
852 853
      std::vector<StaticDigraph::Arc> pred(_res_arc_num);
853 854
      PredMap pred_map(pred);
854 855
      BF bf(rgr, _cost_map);
855 856
      bf.distMap(_pi_map).predMap(pred_map);
856 857

	
857 858
      int length_bound = BF_FIRST_LIMIT;
858 859
      bool optimal = false;
859 860
      while (!optimal) {
860 861
        bf.init(0);
861 862
        int iter_num = 0;
862 863
        bool cycle_found = false;
863 864
        while (!cycle_found) {
864 865
          // Perform some iterations of the Bellman-Ford algorithm
865 866
          int curr_iter_num = iter_num + length_bound <= _node_num ?
866 867
            length_bound : _node_num - iter_num;
867 868
          iter_num += curr_iter_num;
868 869
          int real_iter_num = curr_iter_num;
869 870
          for (int i = 0; i < curr_iter_num; ++i) {
870 871
            if (bf.processNextWeakRound()) {
871 872
              real_iter_num = i;
872 873
              break;
873 874
            }
874 875
          }
875 876
          if (real_iter_num < curr_iter_num) {
876 877
            // Optimal flow is found
877 878
            optimal = true;
878 879
            break;
879 880
          } else {
880 881
            // Search for node disjoint negative cycles
881 882
            std::vector<int> state(_res_node_num, 0);
882 883
            int id = 0;
883 884
            for (int u = 0; u != _res_node_num; ++u) {
884 885
              if (state[u] != 0) continue;
885 886
              ++id;
886 887
              int v = u;
887 888
              for (; v != -1 && state[v] == 0; v = pred[v] == INVALID ?
888 889
                   -1 : rgr.id(rgr.source(pred[v]))) {
889 890
                state[v] = id;
890 891
              }
891 892
              if (v != -1 && state[v] == id) {
892 893
                // A negative cycle is found
893 894
                cycle_found = true;
894 895
                cycle.clear();
895 896
                StaticDigraph::Arc a = pred[v];
896 897
                Value d, delta = _res_cap[rgr.id(a)];
897 898
                cycle.push_back(rgr.id(a));
898 899
                while (rgr.id(rgr.source(a)) != v) {
899 900
                  a = pred_map[rgr.source(a)];
900 901
                  d = _res_cap[rgr.id(a)];
901 902
                  if (d < delta) delta = d;
902 903
                  cycle.push_back(rgr.id(a));
903 904
                }
904 905

	
905 906
                // Augment along the cycle
906 907
                for (int i = 0; i < int(cycle.size()); ++i) {
907 908
                  int j = cycle[i];
908 909
                  _res_cap[j] -= delta;
909 910
                  _res_cap[_reverse[j]] += delta;
910 911
                }
911 912
              }
912 913
            }
913 914
          }
914 915

	
915 916
          // Increase iteration limit if no cycle is found
916 917
          if (!cycle_found) {
917 918
            length_bound = static_cast<int>(length_bound * BF_LIMIT_FACTOR);
918 919
          }
919 920
        }
920 921
      }
921 922
    }
922 923

	
923 924
    // Execute the "Minimum Mean Cycle Canceling" method
924 925
    void startMinMeanCycleCanceling() {
925 926
      typedef SimplePath<StaticDigraph> SPath;
926 927
      typedef typename SPath::ArcIt SPathArcIt;
927 928
      typedef typename HowardMmc<StaticDigraph, CostArcMap>
928 929
        ::template SetPath<SPath>::Create MMC;
929 930

	
930 931
      SPath cycle;
931 932
      MMC mmc(_sgr, _cost_map);
932 933
      mmc.cycle(cycle);
933 934
      buildResidualNetwork();
934 935
      while (mmc.findCycleMean() && mmc.cycleCost() < 0) {
935 936
        // Find the cycle
936 937
        mmc.findCycle();
937 938

	
938 939
        // Compute delta value
939 940
        Value delta = INF;
940 941
        for (SPathArcIt a(cycle); a != INVALID; ++a) {
941 942
          Value d = _res_cap[_id_vec[_sgr.id(a)]];
942 943
          if (d < delta) delta = d;
943 944
        }
944 945

	
945 946
        // Augment along the cycle
946 947
        for (SPathArcIt a(cycle); a != INVALID; ++a) {
947 948
          int j = _id_vec[_sgr.id(a)];
948 949
          _res_cap[j] -= delta;
949 950
          _res_cap[_reverse[j]] += delta;
950 951
        }
951 952

	
952 953
        // Rebuild the residual network
953 954
        buildResidualNetwork();
954 955
      }
955 956
    }
956 957

	
957 958
    // Execute the "Cancel And Tighten" method
958 959
    void startCancelAndTighten() {
959 960
      // Constants for the min mean cycle computations
960 961
      const double LIMIT_FACTOR = 1.0;
961 962
      const int MIN_LIMIT = 5;
962 963

	
963 964
      // Contruct auxiliary data vectors
964 965
      DoubleVector pi(_res_node_num, 0.0);
965 966
      IntVector level(_res_node_num);
966 967
      BoolVector reached(_res_node_num);
967 968
      BoolVector processed(_res_node_num);
968 969
      IntVector pred_node(_res_node_num);
969 970
      IntVector pred_arc(_res_node_num);
970 971
      std::vector<int> stack(_res_node_num);
971 972
      std::vector<int> proc_vector(_res_node_num);
972 973

	
973 974
      // Initialize epsilon
974 975
      double epsilon = 0;
975 976
      for (int a = 0; a != _res_arc_num; ++a) {
976 977
        if (_res_cap[a] > 0 && -_cost[a] > epsilon)
977 978
          epsilon = -_cost[a];
978 979
      }
979 980

	
980 981
      // Start phases
981 982
      Tolerance<double> tol;
982 983
      tol.epsilon(1e-6);
983 984
      int limit = int(LIMIT_FACTOR * std::sqrt(double(_res_node_num)));
984 985
      if (limit < MIN_LIMIT) limit = MIN_LIMIT;
985 986
      int iter = limit;
986 987
      while (epsilon * _res_node_num >= 1) {
987 988
        // Find and cancel cycles in the admissible network using DFS
988 989
        for (int u = 0; u != _res_node_num; ++u) {
989 990
          reached[u] = false;
990 991
          processed[u] = false;
991 992
        }
992 993
        int stack_head = -1;
993 994
        int proc_head = -1;
994 995
        for (int start = 0; start != _res_node_num; ++start) {
995 996
          if (reached[start]) continue;
996 997

	
997 998
          // New start node
998 999
          reached[start] = true;
999 1000
          pred_arc[start] = -1;
1000 1001
          pred_node[start] = -1;
1001 1002

	
1002 1003
          // Find the first admissible outgoing arc
1003 1004
          double p = pi[start];
1004 1005
          int a = _first_out[start];
1005 1006
          int last_out = _first_out[start+1];
1006 1007
          for (; a != last_out && (_res_cap[a] == 0 ||
1007 1008
               !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1008 1009
          if (a == last_out) {
1009 1010
            processed[start] = true;
1010 1011
            proc_vector[++proc_head] = start;
1011 1012
            continue;
1012 1013
          }
1013 1014
          stack[++stack_head] = a;
1014 1015

	
1015 1016
          while (stack_head >= 0) {
1016 1017
            int sa = stack[stack_head];
1017 1018
            int u = _source[sa];
1018 1019
            int v = _target[sa];
1019 1020

	
1020 1021
            if (!reached[v]) {
1021 1022
              // A new node is reached
1022 1023
              reached[v] = true;
1023 1024
              pred_node[v] = u;
1024 1025
              pred_arc[v] = sa;
1025 1026
              p = pi[v];
1026 1027
              a = _first_out[v];
1027 1028
              last_out = _first_out[v+1];
1028 1029
              for (; a != last_out && (_res_cap[a] == 0 ||
1029 1030
                   !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1030 1031
              stack[++stack_head] = a == last_out ? -1 : a;
1031 1032
            } else {
1032 1033
              if (!processed[v]) {
1033 1034
                // A cycle is found
1034 1035
                int n, w = u;
1035 1036
                Value d, delta = _res_cap[sa];
1036 1037
                for (n = u; n != v; n = pred_node[n]) {
1037 1038
                  d = _res_cap[pred_arc[n]];
1038 1039
                  if (d <= delta) {
1039 1040
                    delta = d;
1040 1041
                    w = pred_node[n];
1041 1042
                  }
1042 1043
                }
1043 1044

	
1044 1045
                // Augment along the cycle
1045 1046
                _res_cap[sa] -= delta;
1046 1047
                _res_cap[_reverse[sa]] += delta;
1047 1048
                for (n = u; n != v; n = pred_node[n]) {
1048 1049
                  int pa = pred_arc[n];
1049 1050
                  _res_cap[pa] -= delta;
1050 1051
                  _res_cap[_reverse[pa]] += delta;
1051 1052
                }
1052 1053
                for (n = u; stack_head > 0 && n != w; n = pred_node[n]) {
1053 1054
                  --stack_head;
1054 1055
                  reached[n] = false;
1055 1056
                }
1056 1057
                u = w;
1057 1058
              }
1058 1059
              v = u;
1059 1060

	
1060 1061
              // Find the next admissible outgoing arc
1061 1062
              p = pi[v];
1062 1063
              a = stack[stack_head] + 1;
1063 1064
              last_out = _first_out[v+1];
1064 1065
              for (; a != last_out && (_res_cap[a] == 0 ||
1065 1066
                   !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1066 1067
              stack[stack_head] = a == last_out ? -1 : a;
1067 1068
            }
1068 1069

	
1069 1070
            while (stack_head >= 0 && stack[stack_head] == -1) {
1070 1071
              processed[v] = true;
1071 1072
              proc_vector[++proc_head] = v;
1072 1073
              if (--stack_head >= 0) {
1073 1074
                // Find the next admissible outgoing arc
1074 1075
                v = _source[stack[stack_head]];
1075 1076
                p = pi[v];
1076 1077
                a = stack[stack_head] + 1;
1077 1078
                last_out = _first_out[v+1];
1078 1079
                for (; a != last_out && (_res_cap[a] == 0 ||
1079 1080
                     !tol.negative(_cost[a] + p - pi[_target[a]])); ++a) ;
1080 1081
                stack[stack_head] = a == last_out ? -1 : a;
1081 1082
              }
1082 1083
            }
1083 1084
          }
1084 1085
        }
1085 1086

	
1086 1087
        // Tighten potentials and epsilon
1087 1088
        if (--iter > 0) {
1088 1089
          for (int u = 0; u != _res_node_num; ++u) {
1089 1090
            level[u] = 0;
1090 1091
          }
1091 1092
          for (int i = proc_head; i > 0; --i) {
1092 1093
            int u = proc_vector[i];
1093 1094
            double p = pi[u];
1094 1095
            int l = level[u] + 1;
1095 1096
            int last_out = _first_out[u+1];
1096 1097
            for (int a = _first_out[u]; a != last_out; ++a) {
1097 1098
              int v = _target[a];
1098 1099
              if (_res_cap[a] > 0 && tol.negative(_cost[a] + p - pi[v]) &&
1099 1100
                  l > level[v]) level[v] = l;
1100 1101
            }
1101 1102
          }
1102 1103

	
1103 1104
          // Modify potentials
1104 1105
          double q = std::numeric_limits<double>::max();
1105 1106
          for (int u = 0; u != _res_node_num; ++u) {
1106 1107
            int lu = level[u];
1107 1108
            double p, pu = pi[u];
1108 1109
            int last_out = _first_out[u+1];
1109 1110
            for (int a = _first_out[u]; a != last_out; ++a) {
1110 1111
              if (_res_cap[a] == 0) continue;
1111 1112
              int v = _target[a];
1112 1113
              int ld = lu - level[v];
1113 1114
              if (ld > 0) {
1114 1115
                p = (_cost[a] + pu - pi[v] + epsilon) / (ld + 1);
1115 1116
                if (p < q) q = p;
1116 1117
              }
1117 1118
            }
1118 1119
          }
1119 1120
          for (int u = 0; u != _res_node_num; ++u) {
1120 1121
            pi[u] -= q * level[u];
1121 1122
          }
1122 1123

	
1123 1124
          // Modify epsilon
1124 1125
          epsilon = 0;
1125 1126
          for (int u = 0; u != _res_node_num; ++u) {
1126 1127
            double curr, pu = pi[u];
1127 1128
            int last_out = _first_out[u+1];
1128 1129
            for (int a = _first_out[u]; a != last_out; ++a) {
1129 1130
              if (_res_cap[a] == 0) continue;
1130 1131
              curr = _cost[a] + pu - pi[_target[a]];
1131 1132
              if (-curr > epsilon) epsilon = -curr;
1132 1133
            }
1133 1134
          }
1134 1135
        } else {
1135 1136
          typedef HowardMmc<StaticDigraph, CostArcMap> MMC;
1136 1137
          typedef typename BellmanFord<StaticDigraph, CostArcMap>
1137 1138
            ::template SetDistMap<CostNodeMap>::Create BF;
1138 1139

	
1139 1140
          // Set epsilon to the minimum cycle mean
1140 1141
          buildResidualNetwork();
1141 1142
          MMC mmc(_sgr, _cost_map);
1142 1143
          mmc.findCycleMean();
1143 1144
          epsilon = -mmc.cycleMean();
1144 1145
          Cost cycle_cost = mmc.cycleCost();
1145 1146
          int cycle_size = mmc.cycleSize();
1146 1147

	
1147 1148
          // Compute feasible potentials for the current epsilon
1148 1149
          for (int i = 0; i != int(_cost_vec.size()); ++i) {
1149 1150
            _cost_vec[i] = cycle_size * _cost_vec[i] - cycle_cost;
1150 1151
          }
1151 1152
          BF bf(_sgr, _cost_map);
1152 1153
          bf.distMap(_pi_map);
1153 1154
          bf.init(0);
1154 1155
          bf.start();
1155 1156
          for (int u = 0; u != _res_node_num; ++u) {
1156 1157
            pi[u] = static_cast<double>(_pi[u]) / cycle_size;
1157 1158
          }
1158 1159

	
1159 1160
          iter = limit;
1160 1161
        }
1161 1162
      }
1162 1163
    }
1163 1164

	
1164 1165
  }; //class CycleCanceling
1165 1166

	
1166 1167
  ///@}
1167 1168

	
1168 1169
} //namespace lemon
1169 1170

	
1170 1171
#endif //LEMON_CYCLE_CANCELING_H
Ignore white space 12288 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_KRUSKAL_H
20 20
#define LEMON_KRUSKAL_H
21 21

	
22 22
#include <algorithm>
23 23
#include <vector>
24 24
#include <lemon/unionfind.h>
25 25
#include <lemon/maps.h>
26 26

	
27 27
#include <lemon/core.h>
28 28
#include <lemon/bits/traits.h>
29 29

	
30 30
///\ingroup spantree
31 31
///\file
32 32
///\brief Kruskal's algorithm to compute a minimum cost spanning tree
33
///
34
///Kruskal's algorithm to compute a minimum cost spanning tree.
35
///
36 33

	
37 34
namespace lemon {
38 35

	
39 36
  namespace _kruskal_bits {
40 37

	
41 38
    // Kruskal for directed graphs.
42 39

	
43 40
    template <typename Digraph, typename In, typename Out>
44 41
    typename disable_if<lemon::UndirectedTagIndicator<Digraph>,
45 42
                       typename In::value_type::second_type >::type
46 43
    kruskal(const Digraph& digraph, const In& in, Out& out,dummy<0> = 0) {
47 44
      typedef typename In::value_type::second_type Value;
48 45
      typedef typename Digraph::template NodeMap<int> IndexMap;
49 46
      typedef typename Digraph::Node Node;
50 47

	
51 48
      IndexMap index(digraph);
52 49
      UnionFind<IndexMap> uf(index);
53 50
      for (typename Digraph::NodeIt it(digraph); it != INVALID; ++it) {
54 51
        uf.insert(it);
55 52
      }
56 53

	
57 54
      Value tree_value = 0;
58 55
      for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) {
59 56
        if (uf.join(digraph.target(it->first),digraph.source(it->first))) {
60 57
          out.set(it->first, true);
61 58
          tree_value += it->second;
62 59
        }
63 60
        else {
64 61
          out.set(it->first, false);
65 62
        }
66 63
      }
67 64
      return tree_value;
68 65
    }
69 66

	
70 67
    // Kruskal for undirected graphs.
71 68

	
72 69
    template <typename Graph, typename In, typename Out>
73 70
    typename enable_if<lemon::UndirectedTagIndicator<Graph>,
74 71
                       typename In::value_type::second_type >::type
75 72
    kruskal(const Graph& graph, const In& in, Out& out,dummy<1> = 1) {
76 73
      typedef typename In::value_type::second_type Value;
77 74
      typedef typename Graph::template NodeMap<int> IndexMap;
78 75
      typedef typename Graph::Node Node;
79 76

	
80 77
      IndexMap index(graph);
81 78
      UnionFind<IndexMap> uf(index);
82 79
      for (typename Graph::NodeIt it(graph); it != INVALID; ++it) {
83 80
        uf.insert(it);
84 81
      }
85 82

	
86 83
      Value tree_value = 0;
87 84
      for (typename In::const_iterator it = in.begin(); it != in.end(); ++it) {
88 85
        if (uf.join(graph.u(it->first),graph.v(it->first))) {
89 86
          out.set(it->first, true);
90 87
          tree_value += it->second;
91 88
        }
92 89
        else {
93 90
          out.set(it->first, false);
94 91
        }
95 92
      }
96 93
      return tree_value;
97 94
    }
98 95

	
99 96

	
100 97
    template <typename Sequence>
101 98
    struct PairComp {
102 99
      typedef typename Sequence::value_type Value;
103 100
      bool operator()(const Value& left, const Value& right) {
104 101
        return left.second < right.second;
105 102
      }
106 103
    };
107 104

	
108 105
    template <typename In, typename Enable = void>
109 106
    struct SequenceInputIndicator {
110 107
      static const bool value = false;
111 108
    };
112 109

	
113 110
    template <typename In>
114 111
    struct SequenceInputIndicator<In,
115 112
      typename exists<typename In::value_type::first_type>::type> {
116 113
      static const bool value = true;
117 114
    };
118 115

	
119 116
    template <typename In, typename Enable = void>
120 117
    struct MapInputIndicator {
121 118
      static const bool value = false;
122 119
    };
123 120

	
124 121
    template <typename In>
125 122
    struct MapInputIndicator<In,
126 123
      typename exists<typename In::Value>::type> {
127 124
      static const bool value = true;
128 125
    };
129 126

	
130 127
    template <typename In, typename Enable = void>
131 128
    struct SequenceOutputIndicator {
132 129
      static const bool value = false;
133 130
    };
134 131

	
135 132
    template <typename Out>
136 133
    struct SequenceOutputIndicator<Out,
137 134
      typename exists<typename Out::value_type>::type> {
138 135
      static const bool value = true;
139 136
    };
140 137

	
141 138
    template <typename Out, typename Enable = void>
142 139
    struct MapOutputIndicator {
143 140
      static const bool value = false;
144 141
    };
145 142

	
146 143
    template <typename Out>
147 144
    struct MapOutputIndicator<Out,
148 145
      typename exists<typename Out::Value>::type> {
149 146
      static const bool value = true;
150 147
    };
151 148

	
152 149
    template <typename In, typename InEnable = void>
153 150
    struct KruskalValueSelector {};
154 151

	
155 152
    template <typename In>
156 153
    struct KruskalValueSelector<In,
157 154
      typename enable_if<SequenceInputIndicator<In>, void>::type>
158 155
    {
159 156
      typedef typename In::value_type::second_type Value;
160 157
    };
161 158

	
162 159
    template <typename In>
163 160
    struct KruskalValueSelector<In,
164 161
      typename enable_if<MapInputIndicator<In>, void>::type>
165 162
    {
166 163
      typedef typename In::Value Value;
167 164
    };
168 165

	
169 166
    template <typename Graph, typename In, typename Out,
170 167
              typename InEnable = void>
171 168
    struct KruskalInputSelector {};
172 169

	
173 170
    template <typename Graph, typename In, typename Out,
174 171
              typename InEnable = void>
175 172
    struct KruskalOutputSelector {};
176 173

	
177 174
    template <typename Graph, typename In, typename Out>
178 175
    struct KruskalInputSelector<Graph, In, Out,
179 176
      typename enable_if<SequenceInputIndicator<In>, void>::type >
180 177
    {
181 178
      typedef typename In::value_type::second_type Value;
182 179

	
183 180
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
184 181
        return KruskalOutputSelector<Graph, In, Out>::
185 182
          kruskal(graph, in, out);
186 183
      }
187 184

	
188 185
    };
189 186

	
190 187
    template <typename Graph, typename In, typename Out>
191 188
    struct KruskalInputSelector<Graph, In, Out,
192 189
      typename enable_if<MapInputIndicator<In>, void>::type >
193 190
    {
194 191
      typedef typename In::Value Value;
195 192
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
196 193
        typedef typename In::Key MapArc;
197 194
        typedef typename In::Value Value;
198 195
        typedef typename ItemSetTraits<Graph, MapArc>::ItemIt MapArcIt;
199 196
        typedef std::vector<std::pair<MapArc, Value> > Sequence;
200 197
        Sequence seq;
201 198

	
202 199
        for (MapArcIt it(graph); it != INVALID; ++it) {
203 200
          seq.push_back(std::make_pair(it, in[it]));
204 201
        }
205 202

	
206 203
        std::sort(seq.begin(), seq.end(), PairComp<Sequence>());
207 204
        return KruskalOutputSelector<Graph, Sequence, Out>::
208 205
          kruskal(graph, seq, out);
209 206
      }
210 207
    };
211 208

	
212 209
    template <typename T>
213 210
    struct RemoveConst {
214 211
      typedef T type;
215 212
    };
216 213

	
217 214
    template <typename T>
218 215
    struct RemoveConst<const T> {
219 216
      typedef T type;
220 217
    };
221 218

	
222 219
    template <typename Graph, typename In, typename Out>
223 220
    struct KruskalOutputSelector<Graph, In, Out,
224 221
      typename enable_if<SequenceOutputIndicator<Out>, void>::type >
225 222
    {
226 223
      typedef typename In::value_type::second_type Value;
227 224

	
228 225
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
229 226
        typedef LoggerBoolMap<typename RemoveConst<Out>::type> Map;
230 227
        Map map(out);
231 228
        return _kruskal_bits::kruskal(graph, in, map);
232 229
      }
233 230

	
234 231
    };
235 232

	
236 233
    template <typename Graph, typename In, typename Out>
237 234
    struct KruskalOutputSelector<Graph, In, Out,
238 235
      typename enable_if<MapOutputIndicator<Out>, void>::type >
239 236
    {
240 237
      typedef typename In::value_type::second_type Value;
241 238

	
242 239
      static Value kruskal(const Graph& graph, const In& in, Out& out) {
243 240
        return _kruskal_bits::kruskal(graph, in, out);
244 241
      }
245 242
    };
246 243

	
247 244
  }
248 245

	
249 246
  /// \ingroup spantree
250 247
  ///
251 248
  /// \brief Kruskal's algorithm for finding a minimum cost spanning tree of
252 249
  /// a graph.
253 250
  ///
254 251
  /// This function runs Kruskal's algorithm to find a minimum cost
255 252
  /// spanning tree of a graph.
256 253
  /// Due to some C++ hacking, it accepts various input and output types.
257 254
  ///
258 255
  /// \param g The graph the algorithm runs on.
259 256
  /// It can be either \ref concepts::Digraph "directed" or
260 257
  /// \ref concepts::Graph "undirected".
261 258
  /// If the graph is directed, the algorithm consider it to be
262 259
  /// undirected by disregarding the direction of the arcs.
263 260
  ///
264 261
  /// \param in This object is used to describe the arc/edge costs.
265 262
  /// It can be one of the following choices.
266 263
  /// - An STL compatible 'Forward Container' with
267 264
  /// <tt>std::pair<GR::Arc,C></tt> or
268 265
  /// <tt>std::pair<GR::Edge,C></tt> as its <tt>value_type</tt>, where
269 266
  /// \c C is the type of the costs. The pairs indicates the arcs/edges
270 267
  /// along with the assigned cost. <em>They must be in a
271 268
  /// cost-ascending order.</em>
272 269
  /// - Any readable arc/edge map. The values of the map indicate the
273 270
  /// arc/edge costs.
274 271
  ///
275 272
  /// \retval out Here we also have a choice.
276 273
  /// - It can be a writable arc/edge map with \c bool value type. After
277 274
  /// running the algorithm it will contain the found minimum cost spanning
278 275
  /// tree: the value of an arc/edge will be set to \c true if it belongs
279 276
  /// to the tree, otherwise it will be set to \c false. The value of
280 277
  /// each arc/edge will be set exactly once.
281 278
  /// - It can also be an iteraror of an STL Container with
282 279
  /// <tt>GR::Arc</tt> or <tt>GR::Edge</tt> as its
283 280
  /// <tt>value_type</tt>.  The algorithm copies the elements of the
284 281
  /// found tree into this sequence.  For example, if we know that the
285 282
  /// spanning tree of the graph \c g has say 53 arcs, then we can
286 283
  /// put its arcs into an STL vector \c tree with a code like this.
287 284
  ///\code
288 285
  /// std::vector<Arc> tree(53);
289 286
  /// kruskal(g,cost,tree.begin());
290 287
  ///\endcode
291 288
  /// Or if we don't know in advance the size of the tree, we can
292 289
  /// write this.
293 290
  ///\code
294 291
  /// std::vector<Arc> tree;
295 292
  /// kruskal(g,cost,std::back_inserter(tree));
296 293
  ///\endcode
297 294
  ///
298 295
  /// \return The total cost of the found spanning tree.
299 296
  ///
300 297
  /// \note If the input graph is not (weakly) connected, a spanning
301 298
  /// forest is calculated instead of a spanning tree.
302 299

	
303 300
#ifdef DOXYGEN
304 301
  template <typename Graph, typename In, typename Out>
305 302
  Value kruskal(const Graph& g, const In& in, Out& out)
306 303
#else
307 304
  template <class Graph, class In, class Out>
308 305
  inline typename _kruskal_bits::KruskalValueSelector<In>::Value
309 306
  kruskal(const Graph& graph, const In& in, Out& out)
310 307
#endif
311 308
  {
312 309
    return _kruskal_bits::KruskalInputSelector<Graph, In, Out>::
313 310
      kruskal(graph, in, out);
314 311
  }
315 312

	
316 313

	
317 314
  template <class Graph, class In, class Out>
318 315
  inline typename _kruskal_bits::KruskalValueSelector<In>::Value
319 316
  kruskal(const Graph& graph, const In& in, const Out& out)
320 317
  {
321 318
    return _kruskal_bits::KruskalInputSelector<Graph, In, const Out>::
322 319
      kruskal(graph, in, out);
323 320
  }
324 321

	
325 322
} //namespace lemon
326 323

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

	
19 19
#ifndef LEMON_NETWORK_SIMPLEX_H
20 20
#define LEMON_NETWORK_SIMPLEX_H
21 21

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

	
27 27
#include <vector>
28 28
#include <limits>
29 29
#include <algorithm>
30 30

	
31 31
#include <lemon/core.h>
32 32
#include <lemon/math.h>
33 33

	
34 34
namespace lemon {
35 35

	
36 36
  /// \addtogroup min_cost_flow_algs
37 37
  /// @{
38 38

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

	
77 78
    /// The type of the flow amounts, capacity bounds and supply values
78 79
    typedef V Value;
79 80
    /// The type of the arc costs
80 81
    typedef C Cost;
81 82

	
82 83
  public:
83 84

	
84 85
    /// \brief Problem type constants for the \c run() function.
85 86
    ///
86 87
    /// Enum type containing the problem type constants that can be
87 88
    /// returned by the \ref run() function of the algorithm.
88 89
    enum ProblemType {
89 90
      /// The problem has no feasible solution (flow).
90 91
      INFEASIBLE,
91 92
      /// The problem has optimal solution (i.e. it is feasible and
92 93
      /// bounded), and the algorithm has found optimal flow and node
93 94
      /// potentials (primal and dual solutions).
94 95
      OPTIMAL,
95 96
      /// The objective function of the problem is unbounded, i.e.
96 97
      /// there is a directed cycle having negative total cost and
97 98
      /// infinite upper bound.
98 99
      UNBOUNDED
99 100
    };
100 101

	
101 102
    /// \brief Constants for selecting the type of the supply constraints.
102 103
    ///
103 104
    /// Enum type containing constants for selecting the supply type,
104 105
    /// i.e. the direction of the inequalities in the supply/demand
105 106
    /// constraints of the \ref min_cost_flow "minimum cost flow problem".
106 107
    ///
107 108
    /// The default supply type is \c GEQ, the \c LEQ type can be
108 109
    /// selected using \ref supplyType().
109 110
    /// The equality form is a special case of both supply types.
110 111
    enum SupplyType {
111 112
      /// This option means that there are <em>"greater or equal"</em>
112 113
      /// supply/demand constraints in the definition of the problem.
113 114
      GEQ,
114 115
      /// This option means that there are <em>"less or equal"</em>
115 116
      /// supply/demand constraints in the definition of the problem.
116 117
      LEQ
117 118
    };
118 119

	
119 120
    /// \brief Constants for selecting the pivot rule.
120 121
    ///
121 122
    /// Enum type containing constants for selecting the pivot rule for
122 123
    /// the \ref run() function.
123 124
    ///
124 125
    /// \ref NetworkSimplex provides five different pivot rule
125 126
    /// implementations that significantly affect the running time
126 127
    /// of the algorithm.
127 128
    /// By default, \ref BLOCK_SEARCH "Block Search" is used, which
128 129
    /// proved to be the most efficient and the most robust on various
129 130
    /// test inputs.
130 131
    /// However, another pivot rule can be selected using the \ref run()
131 132
    /// function with the proper parameter.
132 133
    enum PivotRule {
133 134

	
134 135
      /// The \e First \e Eligible pivot rule.
135 136
      /// The next eligible arc is selected in a wraparound fashion
136 137
      /// in every iteration.
137 138
      FIRST_ELIGIBLE,
138 139

	
139 140
      /// The \e Best \e Eligible pivot rule.
140 141
      /// The best eligible arc is selected in every iteration.
141 142
      BEST_ELIGIBLE,
142 143

	
143 144
      /// The \e Block \e Search pivot rule.
144 145
      /// A specified number of arcs are examined in every iteration
145 146
      /// in a wraparound fashion and the best eligible arc is selected
146 147
      /// from this block.
147 148
      BLOCK_SEARCH,
148 149

	
149 150
      /// The \e Candidate \e List pivot rule.
150 151
      /// In a major iteration a candidate list is built from eligible arcs
151 152
      /// in a wraparound fashion and in the following minor iterations
152 153
      /// the best eligible arc is selected from this list.
153 154
      CANDIDATE_LIST,
154 155

	
155 156
      /// The \e Altering \e Candidate \e List pivot rule.
156 157
      /// It is a modified version of the Candidate List method.
157 158
      /// It keeps only the several best eligible arcs from the former
158 159
      /// candidate list and extends this list in every iteration.
159 160
      ALTERING_LIST
160 161
    };
161 162

	
162 163
  private:
163 164

	
164 165
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
165 166

	
166 167
    typedef std::vector<int> IntVector;
167 168
    typedef std::vector<Value> ValueVector;
168 169
    typedef std::vector<Cost> CostVector;
169 170
    typedef std::vector<signed char> CharVector;
170 171
    // Note: vector<signed char> is used instead of vector<ArcState> and 
171 172
    // vector<ArcDirection> for efficiency reasons
172 173

	
173 174
    // State constants for arcs
174 175
    enum ArcState {
175 176
      STATE_UPPER = -1,
176 177
      STATE_TREE  =  0,
177 178
      STATE_LOWER =  1
178 179
    };
179 180

	
180 181
    // Direction constants for tree arcs
181 182
    enum ArcDirection {
182 183
      DIR_DOWN = -1,
183 184
      DIR_UP   =  1
184 185
    };
185 186

	
186 187
  private:
187 188

	
188 189
    // Data related to the underlying digraph
189 190
    const GR &_graph;
190 191
    int _node_num;
191 192
    int _arc_num;
192 193
    int _all_arc_num;
193 194
    int _search_arc_num;
194 195

	
195 196
    // Parameters of the problem
196 197
    bool _have_lower;
197 198
    SupplyType _stype;
198 199
    Value _sum_supply;
199 200

	
200 201
    // Data structures for storing the digraph
201 202
    IntNodeMap _node_id;
202 203
    IntArcMap _arc_id;
203 204
    IntVector _source;
204 205
    IntVector _target;
205 206
    bool _arc_mixing;
206 207

	
207 208
    // Node and arc data
208 209
    ValueVector _lower;
209 210
    ValueVector _upper;
210 211
    ValueVector _cap;
211 212
    CostVector _cost;
212 213
    ValueVector _supply;
213 214
    ValueVector _flow;
214 215
    CostVector _pi;
215 216

	
216 217
    // Data for storing the spanning tree structure
217 218
    IntVector _parent;
218 219
    IntVector _pred;
219 220
    IntVector _thread;
220 221
    IntVector _rev_thread;
221 222
    IntVector _succ_num;
222 223
    IntVector _last_succ;
223 224
    CharVector _pred_dir;
224 225
    CharVector _state;
225 226
    IntVector _dirty_revs;
226 227
    int _root;
227 228

	
228 229
    // Temporary data used in the current pivot iteration
229 230
    int in_arc, join, u_in, v_in, u_out, v_out;
230 231
    Value delta;
231 232

	
232 233
    const Value MAX;
233 234

	
234 235
  public:
235 236

	
236 237
    /// \brief Constant for infinite upper bounds (capacities).
237 238
    ///
238 239
    /// Constant for infinite upper bounds (capacities).
239 240
    /// It is \c std::numeric_limits<Value>::infinity() if available,
240 241
    /// \c std::numeric_limits<Value>::max() otherwise.
241 242
    const Value INF;
242 243

	
243 244
  private:
244 245

	
245 246
    // Implementation of the First Eligible pivot rule
246 247
    class FirstEligiblePivotRule
247 248
    {
248 249
    private:
249 250

	
250 251
      // References to the NetworkSimplex class
251 252
      const IntVector  &_source;
252 253
      const IntVector  &_target;
253 254
      const CostVector &_cost;
254 255
      const CharVector &_state;
255 256
      const CostVector &_pi;
256 257
      int &_in_arc;
257 258
      int _search_arc_num;
258 259

	
259 260
      // Pivot rule data
260 261
      int _next_arc;
261 262

	
262 263
    public:
263 264

	
264 265
      // Constructor
265 266
      FirstEligiblePivotRule(NetworkSimplex &ns) :
266 267
        _source(ns._source), _target(ns._target),
267 268
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
268 269
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
269 270
        _next_arc(0)
270 271
      {}
271 272

	
272 273
      // Find next entering arc
273 274
      bool findEnteringArc() {
274 275
        Cost c;
275 276
        for (int e = _next_arc; e != _search_arc_num; ++e) {
276 277
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
277 278
          if (c < 0) {
278 279
            _in_arc = e;
279 280
            _next_arc = e + 1;
280 281
            return true;
281 282
          }
282 283
        }
283 284
        for (int e = 0; e != _next_arc; ++e) {
284 285
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
285 286
          if (c < 0) {
286 287
            _in_arc = e;
287 288
            _next_arc = e + 1;
288 289
            return true;
289 290
          }
290 291
        }
291 292
        return false;
292 293
      }
293 294

	
294 295
    }; //class FirstEligiblePivotRule
295 296

	
296 297

	
297 298
    // Implementation of the Best Eligible pivot rule
298 299
    class BestEligiblePivotRule
299 300
    {
300 301
    private:
301 302

	
302 303
      // References to the NetworkSimplex class
303 304
      const IntVector  &_source;
304 305
      const IntVector  &_target;
305 306
      const CostVector &_cost;
306 307
      const CharVector &_state;
307 308
      const CostVector &_pi;
308 309
      int &_in_arc;
309 310
      int _search_arc_num;
310 311

	
311 312
    public:
312 313

	
313 314
      // Constructor
314 315
      BestEligiblePivotRule(NetworkSimplex &ns) :
315 316
        _source(ns._source), _target(ns._target),
316 317
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
317 318
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
318 319
      {}
319 320

	
320 321
      // Find next entering arc
321 322
      bool findEnteringArc() {
322 323
        Cost c, min = 0;
323 324
        for (int e = 0; e != _search_arc_num; ++e) {
324 325
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
325 326
          if (c < min) {
326 327
            min = c;
327 328
            _in_arc = e;
328 329
          }
329 330
        }
330 331
        return min < 0;
331 332
      }
332 333

	
333 334
    }; //class BestEligiblePivotRule
334 335

	
335 336

	
336 337
    // Implementation of the Block Search pivot rule
337 338
    class BlockSearchPivotRule
338 339
    {
339 340
    private:
340 341

	
341 342
      // References to the NetworkSimplex class
342 343
      const IntVector  &_source;
343 344
      const IntVector  &_target;
344 345
      const CostVector &_cost;
345 346
      const CharVector &_state;
346 347
      const CostVector &_pi;
347 348
      int &_in_arc;
348 349
      int _search_arc_num;
349 350

	
350 351
      // Pivot rule data
351 352
      int _block_size;
352 353
      int _next_arc;
353 354

	
354 355
    public:
355 356

	
356 357
      // Constructor
357 358
      BlockSearchPivotRule(NetworkSimplex &ns) :
358 359
        _source(ns._source), _target(ns._target),
359 360
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
360 361
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
361 362
        _next_arc(0)
362 363
      {
363 364
        // The main parameters of the pivot rule
364 365
        const double BLOCK_SIZE_FACTOR = 1.0;
365 366
        const int MIN_BLOCK_SIZE = 10;
366 367

	
367 368
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
368 369
                                    std::sqrt(double(_search_arc_num))),
369 370
                                MIN_BLOCK_SIZE );
370 371
      }
371 372

	
372 373
      // Find next entering arc
373 374
      bool findEnteringArc() {
374 375
        Cost c, min = 0;
375 376
        int cnt = _block_size;
376 377
        int e;
377 378
        for (e = _next_arc; e != _search_arc_num; ++e) {
378 379
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
379 380
          if (c < min) {
380 381
            min = c;
381 382
            _in_arc = e;
382 383
          }
383 384
          if (--cnt == 0) {
384 385
            if (min < 0) goto search_end;
385 386
            cnt = _block_size;
386 387
          }
387 388
        }
388 389
        for (e = 0; e != _next_arc; ++e) {
389 390
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
390 391
          if (c < min) {
391 392
            min = c;
392 393
            _in_arc = e;
393 394
          }
394 395
          if (--cnt == 0) {
395 396
            if (min < 0) goto search_end;
396 397
            cnt = _block_size;
397 398
          }
398 399
        }
399 400
        if (min >= 0) return false;
400 401

	
401 402
      search_end:
402 403
        _next_arc = e;
403 404
        return true;
404 405
      }
405 406

	
406 407
    }; //class BlockSearchPivotRule
407 408

	
408 409

	
409 410
    // Implementation of the Candidate List pivot rule
410 411
    class CandidateListPivotRule
411 412
    {
412 413
    private:
413 414

	
414 415
      // References to the NetworkSimplex class
415 416
      const IntVector  &_source;
416 417
      const IntVector  &_target;
417 418
      const CostVector &_cost;
418 419
      const CharVector &_state;
419 420
      const CostVector &_pi;
420 421
      int &_in_arc;
421 422
      int _search_arc_num;
422 423

	
423 424
      // Pivot rule data
424 425
      IntVector _candidates;
425 426
      int _list_length, _minor_limit;
426 427
      int _curr_length, _minor_count;
427 428
      int _next_arc;
428 429

	
429 430
    public:
430 431

	
431 432
      /// Constructor
432 433
      CandidateListPivotRule(NetworkSimplex &ns) :
433 434
        _source(ns._source), _target(ns._target),
434 435
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
435 436
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
436 437
        _next_arc(0)
437 438
      {
438 439
        // The main parameters of the pivot rule
439 440
        const double LIST_LENGTH_FACTOR = 0.25;
440 441
        const int MIN_LIST_LENGTH = 10;
441 442
        const double MINOR_LIMIT_FACTOR = 0.1;
442 443
        const int MIN_MINOR_LIMIT = 3;
443 444

	
444 445
        _list_length = std::max( int(LIST_LENGTH_FACTOR *
445 446
                                     std::sqrt(double(_search_arc_num))),
446 447
                                 MIN_LIST_LENGTH );
447 448
        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
448 449
                                 MIN_MINOR_LIMIT );
449 450
        _curr_length = _minor_count = 0;
450 451
        _candidates.resize(_list_length);
451 452
      }
452 453

	
453 454
      /// Find next entering arc
454 455
      bool findEnteringArc() {
455 456
        Cost min, c;
456 457
        int e;
457 458
        if (_curr_length > 0 && _minor_count < _minor_limit) {
458 459
          // Minor iteration: select the best eligible arc from the
459 460
          // current candidate list
460 461
          ++_minor_count;
461 462
          min = 0;
462 463
          for (int i = 0; i < _curr_length; ++i) {
463 464
            e = _candidates[i];
464 465
            c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
465 466
            if (c < min) {
466 467
              min = c;
467 468
              _in_arc = e;
468 469
            }
469 470
            else if (c >= 0) {
470 471
              _candidates[i--] = _candidates[--_curr_length];
471 472
            }
472 473
          }
473 474
          if (min < 0) return true;
474 475
        }
475 476

	
476 477
        // Major iteration: build a new candidate list
477 478
        min = 0;
478 479
        _curr_length = 0;
479 480
        for (e = _next_arc; e != _search_arc_num; ++e) {
480 481
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
481 482
          if (c < 0) {
482 483
            _candidates[_curr_length++] = e;
483 484
            if (c < min) {
484 485
              min = c;
485 486
              _in_arc = e;
486 487
            }
487 488
            if (_curr_length == _list_length) goto search_end;
488 489
          }
489 490
        }
490 491
        for (e = 0; e != _next_arc; ++e) {
491 492
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
492 493
          if (c < 0) {
493 494
            _candidates[_curr_length++] = e;
494 495
            if (c < min) {
495 496
              min = c;
496 497
              _in_arc = e;
497 498
            }
498 499
            if (_curr_length == _list_length) goto search_end;
499 500
          }
500 501
        }
501 502
        if (_curr_length == 0) return false;
502 503

	
503 504
      search_end:
504 505
        _minor_count = 1;
505 506
        _next_arc = e;
506 507
        return true;
507 508
      }
508 509

	
509 510
    }; //class CandidateListPivotRule
510 511

	
511 512

	
512 513
    // Implementation of the Altering Candidate List pivot rule
513 514
    class AlteringListPivotRule
514 515
    {
515 516
    private:
516 517

	
517 518
      // References to the NetworkSimplex class
518 519
      const IntVector  &_source;
519 520
      const IntVector  &_target;
520 521
      const CostVector &_cost;
521 522
      const CharVector &_state;
522 523
      const CostVector &_pi;
523 524
      int &_in_arc;
524 525
      int _search_arc_num;
525 526

	
526 527
      // Pivot rule data
527 528
      int _block_size, _head_length, _curr_length;
528 529
      int _next_arc;
529 530
      IntVector _candidates;
530 531
      CostVector _cand_cost;
531 532

	
532 533
      // Functor class to compare arcs during sort of the candidate list
533 534
      class SortFunc
534 535
      {
535 536
      private:
536 537
        const CostVector &_map;
537 538
      public:
538 539
        SortFunc(const CostVector &map) : _map(map) {}
539 540
        bool operator()(int left, int right) {
540 541
          return _map[left] > _map[right];
541 542
        }
542 543
      };
543 544

	
544 545
      SortFunc _sort_func;
545 546

	
546 547
    public:
547 548

	
548 549
      // Constructor
549 550
      AlteringListPivotRule(NetworkSimplex &ns) :
550 551
        _source(ns._source), _target(ns._target),
551 552
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
552 553
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
553 554
        _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
554 555
      {
555 556
        // The main parameters of the pivot rule
556 557
        const double BLOCK_SIZE_FACTOR = 1.0;
557 558
        const int MIN_BLOCK_SIZE = 10;
558 559
        const double HEAD_LENGTH_FACTOR = 0.1;
559 560
        const int MIN_HEAD_LENGTH = 3;
560 561

	
561 562
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
562 563
                                    std::sqrt(double(_search_arc_num))),
563 564
                                MIN_BLOCK_SIZE );
564 565
        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
565 566
                                 MIN_HEAD_LENGTH );
566 567
        _candidates.resize(_head_length + _block_size);
567 568
        _curr_length = 0;
568 569
      }
569 570

	
570 571
      // Find next entering arc
571 572
      bool findEnteringArc() {
572 573
        // Check the current candidate list
573 574
        int e;
574 575
        Cost c;
575 576
        for (int i = 0; i != _curr_length; ++i) {
576 577
          e = _candidates[i];
577 578
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
578 579
          if (c < 0) {
579 580
            _cand_cost[e] = c;
580 581
          } else {
581 582
            _candidates[i--] = _candidates[--_curr_length];
582 583
          }
583 584
        }
584 585

	
585 586
        // Extend the list
586 587
        int cnt = _block_size;
587 588
        int limit = _head_length;
588 589

	
589 590
        for (e = _next_arc; e != _search_arc_num; ++e) {
590 591
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
591 592
          if (c < 0) {
592 593
            _cand_cost[e] = c;
593 594
            _candidates[_curr_length++] = e;
594 595
          }
595 596
          if (--cnt == 0) {
596 597
            if (_curr_length > limit) goto search_end;
597 598
            limit = 0;
598 599
            cnt = _block_size;
599 600
          }
600 601
        }
601 602
        for (e = 0; e != _next_arc; ++e) {
602 603
          _cand_cost[e] = _state[e] *
603 604
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
604 605
          if (_cand_cost[e] < 0) {
605 606
            _candidates[_curr_length++] = e;
606 607
          }
607 608
          if (--cnt == 0) {
608 609
            if (_curr_length > limit) goto search_end;
609 610
            limit = 0;
610 611
            cnt = _block_size;
611 612
          }
612 613
        }
613 614
        if (_curr_length == 0) return false;
614 615

	
615 616
      search_end:
616 617

	
617 618
        // Make heap of the candidate list (approximating a partial sort)
618 619
        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
619 620
                   _sort_func );
620 621

	
621 622
        // Pop the first element of the heap
622 623
        _in_arc = _candidates[0];
623 624
        _next_arc = e;
624 625
        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
625 626
                  _sort_func );
626 627
        _curr_length = std::min(_head_length, _curr_length - 1);
627 628
        return true;
628 629
      }
629 630

	
630 631
    }; //class AlteringListPivotRule
631 632

	
632 633
  public:
633 634

	
634 635
    /// \brief Constructor.
635 636
    ///
636 637
    /// The constructor of the class.
637 638
    ///
638 639
    /// \param graph The digraph the algorithm runs on.
639 640
    /// \param arc_mixing Indicate if the arcs will be stored in a
640 641
    /// mixed order in the internal data structure.
641 642
    /// In general, it leads to similar performance as using the original
642 643
    /// arc order, but it makes the algorithm more robust and in special
643 644
    /// cases, even significantly faster. Therefore, it is enabled by default.
644 645
    NetworkSimplex(const GR& graph, bool arc_mixing = true) :
645 646
      _graph(graph), _node_id(graph), _arc_id(graph),
646 647
      _arc_mixing(arc_mixing),
647 648
      MAX(std::numeric_limits<Value>::max()),
648 649
      INF(std::numeric_limits<Value>::has_infinity ?
649 650
          std::numeric_limits<Value>::infinity() : MAX)
650 651
    {
651 652
      // Check the number types
652 653
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
653 654
        "The flow type of NetworkSimplex must be signed");
654 655
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
655 656
        "The cost type of NetworkSimplex must be signed");
656 657

	
657 658
      // Reset data structures
658 659
      reset();
659 660
    }
660 661

	
661 662
    /// \name Parameters
662 663
    /// The parameters of the algorithm can be specified using these
663 664
    /// functions.
664 665

	
665 666
    /// @{
666 667

	
667 668
    /// \brief Set the lower bounds on the arcs.
668 669
    ///
669 670
    /// This function sets the lower bounds on the arcs.
670 671
    /// If it is not used before calling \ref run(), the lower bounds
671 672
    /// will be set to zero on all arcs.
672 673
    ///
673 674
    /// \param map An arc map storing the lower bounds.
674 675
    /// Its \c Value type must be convertible to the \c Value type
675 676
    /// of the algorithm.
676 677
    ///
677 678
    /// \return <tt>(*this)</tt>
678 679
    template <typename LowerMap>
679 680
    NetworkSimplex& lowerMap(const LowerMap& map) {
680 681
      _have_lower = true;
681 682
      for (ArcIt a(_graph); a != INVALID; ++a) {
682 683
        _lower[_arc_id[a]] = map[a];
683 684
      }
684 685
      return *this;
685 686
    }
686 687

	
687 688
    /// \brief Set the upper bounds (capacities) on the arcs.
688 689
    ///
689 690
    /// This function sets the upper bounds (capacities) on the arcs.
690 691
    /// If it is not used before calling \ref run(), the upper bounds
691 692
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
692 693
    /// unbounded from above).
693 694
    ///
694 695
    /// \param map An arc map storing the upper bounds.
695 696
    /// Its \c Value type must be convertible to the \c Value type
696 697
    /// of the algorithm.
697 698
    ///
698 699
    /// \return <tt>(*this)</tt>
699 700
    template<typename UpperMap>
700 701
    NetworkSimplex& upperMap(const UpperMap& map) {
701 702
      for (ArcIt a(_graph); a != INVALID; ++a) {
702 703
        _upper[_arc_id[a]] = map[a];
703 704
      }
704 705
      return *this;
705 706
    }
706 707

	
707 708
    /// \brief Set the costs of the arcs.
708 709
    ///
709 710
    /// This function sets the costs of the arcs.
710 711
    /// If it is not used before calling \ref run(), the costs
711 712
    /// will be set to \c 1 on all arcs.
712 713
    ///
713 714
    /// \param map An arc map storing the costs.
714 715
    /// Its \c Value type must be convertible to the \c Cost type
715 716
    /// of the algorithm.
716 717
    ///
717 718
    /// \return <tt>(*this)</tt>
718 719
    template<typename CostMap>
719 720
    NetworkSimplex& costMap(const CostMap& map) {
720 721
      for (ArcIt a(_graph); a != INVALID; ++a) {
721 722
        _cost[_arc_id[a]] = map[a];
722 723
      }
723 724
      return *this;
724 725
    }
725 726

	
726 727
    /// \brief Set the supply values of the nodes.
727 728
    ///
728 729
    /// This function sets the supply values of the nodes.
729 730
    /// If neither this function nor \ref stSupply() is used before
730 731
    /// calling \ref run(), the supply of each node will be set to zero.
731 732
    ///
732 733
    /// \param map A node map storing the supply values.
733 734
    /// Its \c Value type must be convertible to the \c Value type
734 735
    /// of the algorithm.
735 736
    ///
736 737
    /// \return <tt>(*this)</tt>
737 738
    template<typename SupplyMap>
738 739
    NetworkSimplex& supplyMap(const SupplyMap& map) {
739 740
      for (NodeIt n(_graph); n != INVALID; ++n) {
740 741
        _supply[_node_id[n]] = map[n];
741 742
      }
742 743
      return *this;
743 744
    }
744 745

	
745 746
    /// \brief Set single source and target nodes and a supply value.
746 747
    ///
747 748
    /// This function sets a single source node and a single target node
748 749
    /// and the required flow value.
749 750
    /// If neither this function nor \ref supplyMap() is used before
750 751
    /// calling \ref run(), the supply of each node will be set to zero.
751 752
    ///
752 753
    /// Using this function has the same effect as using \ref supplyMap()
753 754
    /// with such a map in which \c k is assigned to \c s, \c -k is
754 755
    /// assigned to \c t and all other nodes have zero supply value.
755 756
    ///
756 757
    /// \param s The source node.
757 758
    /// \param t The target node.
758 759
    /// \param k The required amount of flow from node \c s to node \c t
759 760
    /// (i.e. the supply of \c s and the demand of \c t).
760 761
    ///
761 762
    /// \return <tt>(*this)</tt>
762 763
    NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
763 764
      for (int i = 0; i != _node_num; ++i) {
764 765
        _supply[i] = 0;
765 766
      }
766 767
      _supply[_node_id[s]] =  k;
767 768
      _supply[_node_id[t]] = -k;
768 769
      return *this;
769 770
    }
770 771

	
771 772
    /// \brief Set the type of the supply constraints.
772 773
    ///
773 774
    /// This function sets the type of the supply/demand constraints.
774 775
    /// If it is not used before calling \ref run(), the \ref GEQ supply
775 776
    /// type will be used.
776 777
    ///
777 778
    /// For more information, see \ref SupplyType.
778 779
    ///
779 780
    /// \return <tt>(*this)</tt>
780 781
    NetworkSimplex& supplyType(SupplyType supply_type) {
781 782
      _stype = supply_type;
782 783
      return *this;
783 784
    }
784 785

	
785 786
    /// @}
786 787

	
787 788
    /// \name Execution Control
788 789
    /// The algorithm can be executed using \ref run().
789 790

	
790 791
    /// @{
791 792

	
792 793
    /// \brief Run the algorithm.
793 794
    ///
794 795
    /// This function runs the algorithm.
795 796
    /// The paramters can be specified using functions \ref lowerMap(),
796 797
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
797 798
    /// \ref supplyType().
798 799
    /// For example,
799 800
    /// \code
800 801
    ///   NetworkSimplex<ListDigraph> ns(graph);
801 802
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
802 803
    ///     .supplyMap(sup).run();
803 804
    /// \endcode
804 805
    ///
805 806
    /// This function can be called more than once. All the given parameters
806 807
    /// are kept for the next call, unless \ref resetParams() or \ref reset()
807 808
    /// is used, thus only the modified parameters have to be set again.
808 809
    /// If the underlying digraph was also modified after the construction
809 810
    /// of the class (or the last \ref reset() call), then the \ref reset()
810 811
    /// function must be called.
811 812
    ///
812 813
    /// \param pivot_rule The pivot rule that will be used during the
813 814
    /// algorithm. For more information, see \ref PivotRule.
814 815
    ///
815 816
    /// \return \c INFEASIBLE if no feasible flow exists,
816 817
    /// \n \c OPTIMAL if the problem has optimal solution
817 818
    /// (i.e. it is feasible and bounded), and the algorithm has found
818 819
    /// optimal flow and node potentials (primal and dual solutions),
819 820
    /// \n \c UNBOUNDED if the objective function of the problem is
820 821
    /// unbounded, i.e. there is a directed cycle having negative total
821 822
    /// cost and infinite upper bound.
822 823
    ///
823 824
    /// \see ProblemType, PivotRule
824 825
    /// \see resetParams(), reset()
825 826
    ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
826 827
      if (!init()) return INFEASIBLE;
827 828
      return start(pivot_rule);
828 829
    }
829 830

	
830 831
    /// \brief Reset all the parameters that have been given before.
831 832
    ///
832 833
    /// This function resets all the paramaters that have been given
833 834
    /// before using functions \ref lowerMap(), \ref upperMap(),
834 835
    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
835 836
    ///
836 837
    /// It is useful for multiple \ref run() calls. Basically, all the given
837 838
    /// parameters are kept for the next \ref run() call, unless
838 839
    /// \ref resetParams() or \ref reset() is used.
839 840
    /// If the underlying digraph was also modified after the construction
840 841
    /// of the class or the last \ref reset() call, then the \ref reset()
841 842
    /// function must be used, otherwise \ref resetParams() is sufficient.
842 843
    ///
843 844
    /// For example,
844 845
    /// \code
845 846
    ///   NetworkSimplex<ListDigraph> ns(graph);
846 847
    ///
847 848
    ///   // First run
848 849
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
849 850
    ///     .supplyMap(sup).run();
850 851
    ///
851 852
    ///   // Run again with modified cost map (resetParams() is not called,
852 853
    ///   // so only the cost map have to be set again)
853 854
    ///   cost[e] += 100;
854 855
    ///   ns.costMap(cost).run();
855 856
    ///
856 857
    ///   // Run again from scratch using resetParams()
857 858
    ///   // (the lower bounds will be set to zero on all arcs)
858 859
    ///   ns.resetParams();
859 860
    ///   ns.upperMap(capacity).costMap(cost)
860 861
    ///     .supplyMap(sup).run();
861 862
    /// \endcode
862 863
    ///
863 864
    /// \return <tt>(*this)</tt>
864 865
    ///
865 866
    /// \see reset(), run()
866 867
    NetworkSimplex& resetParams() {
867 868
      for (int i = 0; i != _node_num; ++i) {
868 869
        _supply[i] = 0;
869 870
      }
870 871
      for (int i = 0; i != _arc_num; ++i) {
871 872
        _lower[i] = 0;
872 873
        _upper[i] = INF;
873 874
        _cost[i] = 1;
874 875
      }
875 876
      _have_lower = false;
876 877
      _stype = GEQ;
877 878
      return *this;
878 879
    }
879 880

	
880 881
    /// \brief Reset the internal data structures and all the parameters
881 882
    /// that have been given before.
882 883
    ///
883 884
    /// This function resets the internal data structures and all the
884 885
    /// paramaters that have been given before using functions \ref lowerMap(),
885 886
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(),
886 887
    /// \ref supplyType().
887 888
    ///
888 889
    /// It is useful for multiple \ref run() calls. Basically, all the given
889 890
    /// parameters are kept for the next \ref run() call, unless
890 891
    /// \ref resetParams() or \ref reset() is used.
891 892
    /// If the underlying digraph was also modified after the construction
892 893
    /// of the class or the last \ref reset() call, then the \ref reset()
893 894
    /// function must be used, otherwise \ref resetParams() is sufficient.
894 895
    ///
895 896
    /// See \ref resetParams() for examples.
896 897
    ///
897 898
    /// \return <tt>(*this)</tt>
898 899
    ///
899 900
    /// \see resetParams(), run()
900 901
    NetworkSimplex& reset() {
901 902
      // Resize vectors
902 903
      _node_num = countNodes(_graph);
903 904
      _arc_num = countArcs(_graph);
904 905
      int all_node_num = _node_num + 1;
905 906
      int max_arc_num = _arc_num + 2 * _node_num;
906 907

	
907 908
      _source.resize(max_arc_num);
908 909
      _target.resize(max_arc_num);
909 910

	
910 911
      _lower.resize(_arc_num);
911 912
      _upper.resize(_arc_num);
912 913
      _cap.resize(max_arc_num);
913 914
      _cost.resize(max_arc_num);
914 915
      _supply.resize(all_node_num);
915 916
      _flow.resize(max_arc_num);
916 917
      _pi.resize(all_node_num);
917 918

	
918 919
      _parent.resize(all_node_num);
919 920
      _pred.resize(all_node_num);
920 921
      _pred_dir.resize(all_node_num);
921 922
      _thread.resize(all_node_num);
922 923
      _rev_thread.resize(all_node_num);
923 924
      _succ_num.resize(all_node_num);
924 925
      _last_succ.resize(all_node_num);
925 926
      _state.resize(max_arc_num);
926 927

	
927 928
      // Copy the graph
928 929
      int i = 0;
929 930
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
930 931
        _node_id[n] = i;
931 932
      }
932 933
      if (_arc_mixing) {
933 934
        // Store the arcs in a mixed order
934 935
        const int skip = std::max(_arc_num / _node_num, 3);
935 936
        int i = 0, j = 0;
936 937
        for (ArcIt a(_graph); a != INVALID; ++a) {
937 938
          _arc_id[a] = i;
938 939
          _source[i] = _node_id[_graph.source(a)];
939 940
          _target[i] = _node_id[_graph.target(a)];
940 941
          if ((i += skip) >= _arc_num) i = ++j;
941 942
        }
942 943
      } else {
943 944
        // Store the arcs in the original order
944 945
        int i = 0;
945 946
        for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
946 947
          _arc_id[a] = i;
947 948
          _source[i] = _node_id[_graph.source(a)];
948 949
          _target[i] = _node_id[_graph.target(a)];
949 950
        }
950 951
      }
951 952

	
952 953
      // Reset parameters
953 954
      resetParams();
954 955
      return *this;
955 956
    }
956 957

	
957 958
    /// @}
958 959

	
959 960
    /// \name Query Functions
960 961
    /// The results of the algorithm can be obtained using these
961 962
    /// functions.\n
962 963
    /// The \ref run() function must be called before using them.
963 964

	
964 965
    /// @{
965 966

	
966 967
    /// \brief Return the total cost of the found flow.
967 968
    ///
968 969
    /// This function returns the total cost of the found flow.
969 970
    /// Its complexity is O(e).
970 971
    ///
971 972
    /// \note The return type of the function can be specified as a
972 973
    /// template parameter. For example,
973 974
    /// \code
974 975
    ///   ns.totalCost<double>();
975 976
    /// \endcode
976 977
    /// It is useful if the total cost cannot be stored in the \c Cost
977 978
    /// type of the algorithm, which is the default return type of the
978 979
    /// function.
979 980
    ///
980 981
    /// \pre \ref run() must be called before using this function.
981 982
    template <typename Number>
982 983
    Number totalCost() const {
983 984
      Number c = 0;
984 985
      for (ArcIt a(_graph); a != INVALID; ++a) {
985 986
        int i = _arc_id[a];
986 987
        c += Number(_flow[i]) * Number(_cost[i]);
987 988
      }
988 989
      return c;
989 990
    }
990 991

	
991 992
#ifndef DOXYGEN
992 993
    Cost totalCost() const {
993 994
      return totalCost<Cost>();
994 995
    }
995 996
#endif
996 997

	
997 998
    /// \brief Return the flow on the given arc.
998 999
    ///
999 1000
    /// This function returns the flow on the given arc.
1000 1001
    ///
1001 1002
    /// \pre \ref run() must be called before using this function.
1002 1003
    Value flow(const Arc& a) const {
1003 1004
      return _flow[_arc_id[a]];
1004 1005
    }
1005 1006

	
1006 1007
    /// \brief Return the flow map (the primal solution).
1007 1008
    ///
1008 1009
    /// This function copies the flow value on each arc into the given
1009 1010
    /// map. The \c Value type of the algorithm must be convertible to
1010 1011
    /// the \c Value type of the map.
1011 1012
    ///
1012 1013
    /// \pre \ref run() must be called before using this function.
1013 1014
    template <typename FlowMap>
1014 1015
    void flowMap(FlowMap &map) const {
1015 1016
      for (ArcIt a(_graph); a != INVALID; ++a) {
1016 1017
        map.set(a, _flow[_arc_id[a]]);
1017 1018
      }
1018 1019
    }
1019 1020

	
1020 1021
    /// \brief Return the potential (dual value) of the given node.
1021 1022
    ///
1022 1023
    /// This function returns the potential (dual value) of the
1023 1024
    /// given node.
1024 1025
    ///
1025 1026
    /// \pre \ref run() must be called before using this function.
1026 1027
    Cost potential(const Node& n) const {
1027 1028
      return _pi[_node_id[n]];
1028 1029
    }
1029 1030

	
1030 1031
    /// \brief Return the potential map (the dual solution).
1031 1032
    ///
1032 1033
    /// This function copies the potential (dual value) of each node
1033 1034
    /// into the given map.
1034 1035
    /// The \c Cost type of the algorithm must be convertible to the
1035 1036
    /// \c Value type of the map.
1036 1037
    ///
1037 1038
    /// \pre \ref run() must be called before using this function.
1038 1039
    template <typename PotentialMap>
1039 1040
    void potentialMap(PotentialMap &map) const {
1040 1041
      for (NodeIt n(_graph); n != INVALID; ++n) {
1041 1042
        map.set(n, _pi[_node_id[n]]);
1042 1043
      }
1043 1044
    }
1044 1045

	
1045 1046
    /// @}
1046 1047

	
1047 1048
  private:
1048 1049

	
1049 1050
    // Initialize internal data structures
1050 1051
    bool init() {
1051 1052
      if (_node_num == 0) return false;
1052 1053

	
1053 1054
      // Check the sum of supply values
1054 1055
      _sum_supply = 0;
1055 1056
      for (int i = 0; i != _node_num; ++i) {
1056 1057
        _sum_supply += _supply[i];
1057 1058
      }
1058 1059
      if ( !((_stype == GEQ && _sum_supply <= 0) ||
1059 1060
             (_stype == LEQ && _sum_supply >= 0)) ) return false;
1060 1061

	
1061 1062
      // Remove non-zero lower bounds
1062 1063
      if (_have_lower) {
1063 1064
        for (int i = 0; i != _arc_num; ++i) {
1064 1065
          Value c = _lower[i];
1065 1066
          if (c >= 0) {
1066 1067
            _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF;
1067 1068
          } else {
1068 1069
            _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF;
1069 1070
          }
1070 1071
          _supply[_source[i]] -= c;
1071 1072
          _supply[_target[i]] += c;
1072 1073
        }
1073 1074
      } else {
1074 1075
        for (int i = 0; i != _arc_num; ++i) {
1075 1076
          _cap[i] = _upper[i];
1076 1077
        }
1077 1078
      }
1078 1079

	
1079 1080
      // Initialize artifical cost
1080 1081
      Cost ART_COST;
1081 1082
      if (std::numeric_limits<Cost>::is_exact) {
1082 1083
        ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1083 1084
      } else {
1084 1085
        ART_COST = 0;
1085 1086
        for (int i = 0; i != _arc_num; ++i) {
1086 1087
          if (_cost[i] > ART_COST) ART_COST = _cost[i];
1087 1088
        }
1088 1089
        ART_COST = (ART_COST + 1) * _node_num;
1089 1090
      }
1090 1091

	
1091 1092
      // Initialize arc maps
1092 1093
      for (int i = 0; i != _arc_num; ++i) {
1093 1094
        _flow[i] = 0;
1094 1095
        _state[i] = STATE_LOWER;
1095 1096
      }
1096 1097

	
1097 1098
      // Set data for the artificial root node
1098 1099
      _root = _node_num;
1099 1100
      _parent[_root] = -1;
1100 1101
      _pred[_root] = -1;
1101 1102
      _thread[_root] = 0;
1102 1103
      _rev_thread[0] = _root;
1103 1104
      _succ_num[_root] = _node_num + 1;
1104 1105
      _last_succ[_root] = _root - 1;
1105 1106
      _supply[_root] = -_sum_supply;
1106 1107
      _pi[_root] = 0;
1107 1108

	
1108 1109
      // Add artificial arcs and initialize the spanning tree data structure
1109 1110
      if (_sum_supply == 0) {
1110 1111
        // EQ supply constraints
1111 1112
        _search_arc_num = _arc_num;
1112 1113
        _all_arc_num = _arc_num + _node_num;
1113 1114
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1114 1115
          _parent[u] = _root;
1115 1116
          _pred[u] = e;
1116 1117
          _thread[u] = u + 1;
1117 1118
          _rev_thread[u + 1] = u;
1118 1119
          _succ_num[u] = 1;
1119 1120
          _last_succ[u] = u;
1120 1121
          _cap[e] = INF;
1121 1122
          _state[e] = STATE_TREE;
1122 1123
          if (_supply[u] >= 0) {
1123 1124
            _pred_dir[u] = DIR_UP;
1124 1125
            _pi[u] = 0;
1125 1126
            _source[e] = u;
1126 1127
            _target[e] = _root;
1127 1128
            _flow[e] = _supply[u];
1128 1129
            _cost[e] = 0;
1129 1130
          } else {
1130 1131
            _pred_dir[u] = DIR_DOWN;
1131 1132
            _pi[u] = ART_COST;
1132 1133
            _source[e] = _root;
1133 1134
            _target[e] = u;
1134 1135
            _flow[e] = -_supply[u];
1135 1136
            _cost[e] = ART_COST;
1136 1137
          }
1137 1138
        }
1138 1139
      }
1139 1140
      else if (_sum_supply > 0) {
1140 1141
        // LEQ supply constraints
1141 1142
        _search_arc_num = _arc_num + _node_num;
1142 1143
        int f = _arc_num + _node_num;
1143 1144
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1144 1145
          _parent[u] = _root;
1145 1146
          _thread[u] = u + 1;
1146 1147
          _rev_thread[u + 1] = u;
1147 1148
          _succ_num[u] = 1;
1148 1149
          _last_succ[u] = u;
1149 1150
          if (_supply[u] >= 0) {
1150 1151
            _pred_dir[u] = DIR_UP;
1151 1152
            _pi[u] = 0;
1152 1153
            _pred[u] = e;
1153 1154
            _source[e] = u;
1154 1155
            _target[e] = _root;
1155 1156
            _cap[e] = INF;
1156 1157
            _flow[e] = _supply[u];
1157 1158
            _cost[e] = 0;
1158 1159
            _state[e] = STATE_TREE;
1159 1160
          } else {
1160 1161
            _pred_dir[u] = DIR_DOWN;
1161 1162
            _pi[u] = ART_COST;
1162 1163
            _pred[u] = f;
1163 1164
            _source[f] = _root;
1164 1165
            _target[f] = u;
1165 1166
            _cap[f] = INF;
1166 1167
            _flow[f] = -_supply[u];
1167 1168
            _cost[f] = ART_COST;
1168 1169
            _state[f] = STATE_TREE;
1169 1170
            _source[e] = u;
1170 1171
            _target[e] = _root;
1171 1172
            _cap[e] = INF;
1172 1173
            _flow[e] = 0;
1173 1174
            _cost[e] = 0;
1174 1175
            _state[e] = STATE_LOWER;
1175 1176
            ++f;
1176 1177
          }
1177 1178
        }
1178 1179
        _all_arc_num = f;
1179 1180
      }
1180 1181
      else {
1181 1182
        // GEQ supply constraints
1182 1183
        _search_arc_num = _arc_num + _node_num;
1183 1184
        int f = _arc_num + _node_num;
1184 1185
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1185 1186
          _parent[u] = _root;
1186 1187
          _thread[u] = u + 1;
1187 1188
          _rev_thread[u + 1] = u;
1188 1189
          _succ_num[u] = 1;
1189 1190
          _last_succ[u] = u;
1190 1191
          if (_supply[u] <= 0) {
1191 1192
            _pred_dir[u] = DIR_DOWN;
1192 1193
            _pi[u] = 0;
1193 1194
            _pred[u] = e;
1194 1195
            _source[e] = _root;
1195 1196
            _target[e] = u;
1196 1197
            _cap[e] = INF;
1197 1198
            _flow[e] = -_supply[u];
1198 1199
            _cost[e] = 0;
1199 1200
            _state[e] = STATE_TREE;
1200 1201
          } else {
1201 1202
            _pred_dir[u] = DIR_UP;
1202 1203
            _pi[u] = -ART_COST;
1203 1204
            _pred[u] = f;
1204 1205
            _source[f] = u;
1205 1206
            _target[f] = _root;
1206 1207
            _cap[f] = INF;
1207 1208
            _flow[f] = _supply[u];
1208 1209
            _state[f] = STATE_TREE;
1209 1210
            _cost[f] = ART_COST;
1210 1211
            _source[e] = _root;
1211 1212
            _target[e] = u;
1212 1213
            _cap[e] = INF;
1213 1214
            _flow[e] = 0;
1214 1215
            _cost[e] = 0;
1215 1216
            _state[e] = STATE_LOWER;
1216 1217
            ++f;
1217 1218
          }
1218 1219
        }
1219 1220
        _all_arc_num = f;
1220 1221
      }
1221 1222

	
1222 1223
      return true;
1223 1224
    }
1224 1225

	
1225 1226
    // Find the join node
1226 1227
    void findJoinNode() {
1227 1228
      int u = _source[in_arc];
1228 1229
      int v = _target[in_arc];
1229 1230
      while (u != v) {
1230 1231
        if (_succ_num[u] < _succ_num[v]) {
1231 1232
          u = _parent[u];
1232 1233
        } else {
1233 1234
          v = _parent[v];
1234 1235
        }
1235 1236
      }
1236 1237
      join = u;
1237 1238
    }
1238 1239

	
1239 1240
    // Find the leaving arc of the cycle and returns true if the
1240 1241
    // leaving arc is not the same as the entering arc
1241 1242
    bool findLeavingArc() {
1242 1243
      // Initialize first and second nodes according to the direction
1243 1244
      // of the cycle
1244 1245
      int first, second;
1245 1246
      if (_state[in_arc] == STATE_LOWER) {
1246 1247
        first  = _source[in_arc];
1247 1248
        second = _target[in_arc];
1248 1249
      } else {
1249 1250
        first  = _target[in_arc];
1250 1251
        second = _source[in_arc];
1251 1252
      }
1252 1253
      delta = _cap[in_arc];
1253 1254
      int result = 0;
1254 1255
      Value c, d;
1255 1256
      int e;
1256 1257

	
1257 1258
      // Search the cycle form the first node to the join node
1258 1259
      for (int u = first; u != join; u = _parent[u]) {
1259 1260
        e = _pred[u];
1260 1261
        d = _flow[e];
1261 1262
        if (_pred_dir[u] == DIR_DOWN) {
1262 1263
          c = _cap[e];
1263 1264
          d = c >= MAX ? INF : c - d;
1264 1265
        }
1265 1266
        if (d < delta) {
1266 1267
          delta = d;
1267 1268
          u_out = u;
1268 1269
          result = 1;
1269 1270
        }
1270 1271
      }
1271 1272

	
1272 1273
      // Search the cycle form the second node to the join node
1273 1274
      for (int u = second; u != join; u = _parent[u]) {
1274 1275
        e = _pred[u];
1275 1276
        d = _flow[e];
1276 1277
        if (_pred_dir[u] == DIR_UP) {
1277 1278
          c = _cap[e];
1278 1279
          d = c >= MAX ? INF : c - d;
1279 1280
        }
1280 1281
        if (d <= delta) {
1281 1282
          delta = d;
1282 1283
          u_out = u;
1283 1284
          result = 2;
1284 1285
        }
1285 1286
      }
1286 1287

	
1287 1288
      if (result == 1) {
1288 1289
        u_in = first;
1289 1290
        v_in = second;
1290 1291
      } else {
1291 1292
        u_in = second;
1292 1293
        v_in = first;
1293 1294
      }
1294 1295
      return result != 0;
1295 1296
    }
1296 1297

	
1297 1298
    // Change _flow and _state vectors
1298 1299
    void changeFlow(bool change) {
1299 1300
      // Augment along the cycle
1300 1301
      if (delta > 0) {
1301 1302
        Value val = _state[in_arc] * delta;
1302 1303
        _flow[in_arc] += val;
1303 1304
        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1304 1305
          _flow[_pred[u]] -= _pred_dir[u] * val;
1305 1306
        }
1306 1307
        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1307 1308
          _flow[_pred[u]] += _pred_dir[u] * val;
1308 1309
        }
1309 1310
      }
1310 1311
      // Update the state of the entering and leaving arcs
1311 1312
      if (change) {
1312 1313
        _state[in_arc] = STATE_TREE;
1313 1314
        _state[_pred[u_out]] =
1314 1315
          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1315 1316
      } else {
1316 1317
        _state[in_arc] = -_state[in_arc];
1317 1318
      }
1318 1319
    }
1319 1320

	
1320 1321
    // Update the tree structure
1321 1322
    void updateTreeStructure() {
1322 1323
      int old_rev_thread = _rev_thread[u_out];
1323 1324
      int old_succ_num = _succ_num[u_out];
1324 1325
      int old_last_succ = _last_succ[u_out];
1325 1326
      v_out = _parent[u_out];
1326 1327

	
1327 1328
      // Check if u_in and u_out coincide
1328 1329
      if (u_in == u_out) {
1329 1330
        // Update _parent, _pred, _pred_dir
1330 1331
        _parent[u_in] = v_in;
1331 1332
        _pred[u_in] = in_arc;
1332 1333
        _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN;
1333 1334

	
1334 1335
        // Update _thread and _rev_thread
1335 1336
        if (_thread[v_in] != u_out) {
1336 1337
          int after = _thread[old_last_succ];
1337 1338
          _thread[old_rev_thread] = after;
1338 1339
          _rev_thread[after] = old_rev_thread;
1339 1340
          after = _thread[v_in];
1340 1341
          _thread[v_in] = u_out;
1341 1342
          _rev_thread[u_out] = v_in;
1342 1343
          _thread[old_last_succ] = after;
1343 1344
          _rev_thread[after] = old_last_succ;
1344 1345
        }
1345 1346
      } else {
1346 1347
        // Handle the case when old_rev_thread equals to v_in
1347 1348
        // (it also means that join and v_out coincide)
1348 1349
        int thread_continue = old_rev_thread == v_in ?
1349 1350
          _thread[old_last_succ] : _thread[v_in];
1350 1351

	
1351 1352
        // Update _thread and _parent along the stem nodes (i.e. the nodes
1352 1353
        // between u_in and u_out, whose parent have to be changed)
1353 1354
        int stem = u_in;              // the current stem node
1354 1355
        int par_stem = v_in;          // the new parent of stem
1355 1356
        int next_stem;                // the next stem node
1356 1357
        int last = _last_succ[u_in];  // the last successor of stem
1357 1358
        int before, after = _thread[last];
1358 1359
        _thread[v_in] = u_in;
1359 1360
        _dirty_revs.clear();
1360 1361
        _dirty_revs.push_back(v_in);
1361 1362
        while (stem != u_out) {
1362 1363
          // Insert the next stem node into the thread list
1363 1364
          next_stem = _parent[stem];
1364 1365
          _thread[last] = next_stem;
1365 1366
          _dirty_revs.push_back(last);
1366 1367

	
1367 1368
          // Remove the subtree of stem from the thread list
1368 1369
          before = _rev_thread[stem];
1369 1370
          _thread[before] = after;
1370 1371
          _rev_thread[after] = before;
1371 1372

	
1372 1373
          // Change the parent node and shift stem nodes
1373 1374
          _parent[stem] = par_stem;
1374 1375
          par_stem = stem;
1375 1376
          stem = next_stem;
1376 1377

	
1377 1378
          // Update last and after
1378 1379
          last = _last_succ[stem] == _last_succ[par_stem] ?
1379 1380
            _rev_thread[par_stem] : _last_succ[stem];
1380 1381
          after = _thread[last];
1381 1382
        }
1382 1383
        _parent[u_out] = par_stem;
1383 1384
        _thread[last] = thread_continue;
1384 1385
        _rev_thread[thread_continue] = last;
1385 1386
        _last_succ[u_out] = last;
1386 1387

	
1387 1388
        // Remove the subtree of u_out from the thread list except for
1388 1389
        // the case when old_rev_thread equals to v_in
1389 1390
        if (old_rev_thread != v_in) {
1390 1391
          _thread[old_rev_thread] = after;
1391 1392
          _rev_thread[after] = old_rev_thread;
1392 1393
        }
1393 1394

	
1394 1395
        // Update _rev_thread using the new _thread values
1395 1396
        for (int i = 0; i != int(_dirty_revs.size()); ++i) {
1396 1397
          int u = _dirty_revs[i];
1397 1398
          _rev_thread[_thread[u]] = u;
1398 1399
        }
1399 1400

	
1400 1401
        // Update _pred, _pred_dir, _last_succ and _succ_num for the
1401 1402
        // stem nodes from u_out to u_in
1402 1403
        int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1403 1404
        for (int u = u_out, p = _parent[u]; u != u_in; u = p, p = _parent[u]) {
1404 1405
          _pred[u] = _pred[p];
1405 1406
          _pred_dir[u] = -_pred_dir[p];
1406 1407
          tmp_sc += _succ_num[u] - _succ_num[p];
1407 1408
          _succ_num[u] = tmp_sc;
1408 1409
          _last_succ[p] = tmp_ls;
1409 1410
        }
1410 1411
        _pred[u_in] = in_arc;
1411 1412
        _pred_dir[u_in] = u_in == _source[in_arc] ? DIR_UP : DIR_DOWN;
1412 1413
        _succ_num[u_in] = old_succ_num;
1413 1414
      }
1414 1415

	
1415 1416
      // Update _last_succ from v_in towards the root
1416 1417
      int up_limit_out = _last_succ[join] == v_in ? join : -1;
1417 1418
      int last_succ_out = _last_succ[u_out];
1418 1419
      for (int u = v_in; u != -1 && _last_succ[u] == v_in; u = _parent[u]) {
1419 1420
        _last_succ[u] = last_succ_out;
1420 1421
      }
1421 1422

	
1422 1423
      // Update _last_succ from v_out towards the root
1423 1424
      if (join != old_rev_thread && v_in != old_rev_thread) {
1424 1425
        for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1425 1426
             u = _parent[u]) {
1426 1427
          _last_succ[u] = old_rev_thread;
1427 1428
        }
1428 1429
      }
1429 1430
      else if (last_succ_out != old_last_succ) {
1430 1431
        for (int u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1431 1432
             u = _parent[u]) {
1432 1433
          _last_succ[u] = last_succ_out;
1433 1434
        }
1434 1435
      }
1435 1436

	
1436 1437
      // Update _succ_num from v_in to join
1437 1438
      for (int u = v_in; u != join; u = _parent[u]) {
1438 1439
        _succ_num[u] += old_succ_num;
1439 1440
      }
1440 1441
      // Update _succ_num from v_out to join
1441 1442
      for (int u = v_out; u != join; u = _parent[u]) {
1442 1443
        _succ_num[u] -= old_succ_num;
1443 1444
      }
1444 1445
    }
1445 1446

	
1446 1447
    // Update potentials in the subtree that has been moved
1447 1448
    void updatePotential() {
1448 1449
      Cost sigma = _pi[v_in] - _pi[u_in] -
1449 1450
                   _pred_dir[u_in] * _cost[in_arc];
1450 1451
      int end = _thread[_last_succ[u_in]];
1451 1452
      for (int u = u_in; u != end; u = _thread[u]) {
1452 1453
        _pi[u] += sigma;
1453 1454
      }
1454 1455
    }
1455 1456

	
1456 1457
    // Heuristic initial pivots
1457 1458
    bool initialPivots() {
1458 1459
      Value curr, total = 0;
1459 1460
      std::vector<Node> supply_nodes, demand_nodes;
1460 1461
      for (NodeIt u(_graph); u != INVALID; ++u) {
1461 1462
        curr = _supply[_node_id[u]];
1462 1463
        if (curr > 0) {
1463 1464
          total += curr;
1464 1465
          supply_nodes.push_back(u);
1465 1466
        }
1466 1467
        else if (curr < 0) {
1467 1468
          demand_nodes.push_back(u);
1468 1469
        }
1469 1470
      }
1470 1471
      if (_sum_supply > 0) total -= _sum_supply;
1471 1472
      if (total <= 0) return true;
1472 1473

	
1473 1474
      IntVector arc_vector;
1474 1475
      if (_sum_supply >= 0) {
1475 1476
        if (supply_nodes.size() == 1 && demand_nodes.size() == 1) {
1476 1477
          // Perform a reverse graph search from the sink to the source
1477 1478
          typename GR::template NodeMap<bool> reached(_graph, false);
1478 1479
          Node s = supply_nodes[0], t = demand_nodes[0];
1479 1480
          std::vector<Node> stack;
1480 1481
          reached[t] = true;
1481 1482
          stack.push_back(t);
1482 1483
          while (!stack.empty()) {
1483 1484
            Node u, v = stack.back();
1484 1485
            stack.pop_back();
1485 1486
            if (v == s) break;
1486 1487
            for (InArcIt a(_graph, v); a != INVALID; ++a) {
1487 1488
              if (reached[u = _graph.source(a)]) continue;
1488 1489
              int j = _arc_id[a];
1489 1490
              if (_cap[j] >= total) {
1490 1491
                arc_vector.push_back(j);
1491 1492
                reached[u] = true;
1492 1493
                stack.push_back(u);
1493 1494
              }
1494 1495
            }
1495 1496
          }
1496 1497
        } else {
1497 1498
          // Find the min. cost incomming arc for each demand node
1498 1499
          for (int i = 0; i != int(demand_nodes.size()); ++i) {
1499 1500
            Node v = demand_nodes[i];
1500 1501
            Cost c, min_cost = std::numeric_limits<Cost>::max();
1501 1502
            Arc min_arc = INVALID;
1502 1503
            for (InArcIt a(_graph, v); a != INVALID; ++a) {
1503 1504
              c = _cost[_arc_id[a]];
1504 1505
              if (c < min_cost) {
1505 1506
                min_cost = c;
1506 1507
                min_arc = a;
1507 1508
              }
1508 1509
            }
1509 1510
            if (min_arc != INVALID) {
1510 1511
              arc_vector.push_back(_arc_id[min_arc]);
1511 1512
            }
1512 1513
          }
1513 1514
        }
1514 1515
      } else {
1515 1516
        // Find the min. cost outgoing arc for each supply node
1516 1517
        for (int i = 0; i != int(supply_nodes.size()); ++i) {
1517 1518
          Node u = supply_nodes[i];
1518 1519
          Cost c, min_cost = std::numeric_limits<Cost>::max();
1519 1520
          Arc min_arc = INVALID;
1520 1521
          for (OutArcIt a(_graph, u); a != INVALID; ++a) {
1521 1522
            c = _cost[_arc_id[a]];
1522 1523
            if (c < min_cost) {
1523 1524
              min_cost = c;
1524 1525
              min_arc = a;
1525 1526
            }
1526 1527
          }
1527 1528
          if (min_arc != INVALID) {
1528 1529
            arc_vector.push_back(_arc_id[min_arc]);
1529 1530
          }
1530 1531
        }
1531 1532
      }
1532 1533

	
1533 1534
      // Perform heuristic initial pivots
1534 1535
      for (int i = 0; i != int(arc_vector.size()); ++i) {
1535 1536
        in_arc = arc_vector[i];
1536 1537
        if (_state[in_arc] * (_cost[in_arc] + _pi[_source[in_arc]] -
1537 1538
            _pi[_target[in_arc]]) >= 0) continue;
1538 1539
        findJoinNode();
1539 1540
        bool change = findLeavingArc();
1540 1541
        if (delta >= MAX) return false;
1541 1542
        changeFlow(change);
1542 1543
        if (change) {
1543 1544
          updateTreeStructure();
1544 1545
          updatePotential();
1545 1546
        }
1546 1547
      }
1547 1548
      return true;
1548 1549
    }
1549 1550

	
1550 1551
    // Execute the algorithm
1551 1552
    ProblemType start(PivotRule pivot_rule) {
1552 1553
      // Select the pivot rule implementation
1553 1554
      switch (pivot_rule) {
1554 1555
        case FIRST_ELIGIBLE:
1555 1556
          return start<FirstEligiblePivotRule>();
1556 1557
        case BEST_ELIGIBLE:
1557 1558
          return start<BestEligiblePivotRule>();
1558 1559
        case BLOCK_SEARCH:
1559 1560
          return start<BlockSearchPivotRule>();
1560 1561
        case CANDIDATE_LIST:
1561 1562
          return start<CandidateListPivotRule>();
1562 1563
        case ALTERING_LIST:
1563 1564
          return start<AlteringListPivotRule>();
1564 1565
      }
1565 1566
      return INFEASIBLE; // avoid warning
1566 1567
    }
1567 1568

	
1568 1569
    template <typename PivotRuleImpl>
1569 1570
    ProblemType start() {
1570 1571
      PivotRuleImpl pivot(*this);
1571 1572

	
1572 1573
      // Perform heuristic initial pivots
1573 1574
      if (!initialPivots()) return UNBOUNDED;
1574 1575

	
1575 1576
      // Execute the Network Simplex algorithm
1576 1577
      while (pivot.findEnteringArc()) {
1577 1578
        findJoinNode();
1578 1579
        bool change = findLeavingArc();
1579 1580
        if (delta >= MAX) return UNBOUNDED;
1580 1581
        changeFlow(change);
1581 1582
        if (change) {
1582 1583
          updateTreeStructure();
1583 1584
          updatePotential();
1584 1585
        }
1585 1586
      }
1586 1587

	
1587 1588
      // Check feasibility
1588 1589
      for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1589 1590
        if (_flow[e] != 0) return INFEASIBLE;
1590 1591
      }
1591 1592

	
1592 1593
      // Transform the solution and the supply map to the original form
1593 1594
      if (_have_lower) {
1594 1595
        for (int i = 0; i != _arc_num; ++i) {
1595 1596
          Value c = _lower[i];
1596 1597
          if (c != 0) {
1597 1598
            _flow[i] += c;
1598 1599
            _supply[_source[i]] += c;
1599 1600
            _supply[_target[i]] -= c;
1600 1601
          }
1601 1602
        }
1602 1603
      }
1603 1604

	
1604 1605
      // Shift potentials to meet the requirements of the GEQ/LEQ type
1605 1606
      // optimality conditions
1606 1607
      if (_sum_supply == 0) {
1607 1608
        if (_stype == GEQ) {
1608 1609
          Cost max_pot = -std::numeric_limits<Cost>::max();
1609 1610
          for (int i = 0; i != _node_num; ++i) {
1610 1611
            if (_pi[i] > max_pot) max_pot = _pi[i];
1611 1612
          }
1612 1613
          if (max_pot > 0) {
1613 1614
            for (int i = 0; i != _node_num; ++i)
1614 1615
              _pi[i] -= max_pot;
1615 1616
          }
1616 1617
        } else {
1617 1618
          Cost min_pot = std::numeric_limits<Cost>::max();
1618 1619
          for (int i = 0; i != _node_num; ++i) {
1619 1620
            if (_pi[i] < min_pot) min_pot = _pi[i];
1620 1621
          }
1621 1622
          if (min_pot < 0) {
1622 1623
            for (int i = 0; i != _node_num; ++i)
1623 1624
              _pi[i] -= min_pot;
1624 1625
          }
1625 1626
        }
1626 1627
      }
1627 1628

	
1628 1629
      return OPTIMAL;
1629 1630
    }
1630 1631

	
1631 1632
  }; //class NetworkSimplex
1632 1633

	
1633 1634
  ///@}
1634 1635

	
1635 1636
} //namespace lemon
1636 1637

	
1637 1638
#endif //LEMON_NETWORK_SIMPLEX_H
0 comments (0 inline)