gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Small implementation improvements in MCF algorithms (#180) - Handle max() as infinite value (not only infinity()). - Better GEQ handling in CapacityScaling. - Skip the unnecessary saturating operations in the first phase in CapacityScaling. - Use vector<char> instead of vector<bool> and vector<int> if it is possible and it proved to be usually faster.
0 2 0
default
2 files changed with 61 insertions and 50 deletions:
↑ Collapse diff ↑
Ignore white space 384 line context
1 1
/* -*- C++ -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_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 value type used for flow amounts, capacity bounds
39 39
  /// and supply values. By default it is \c int.
40 40
  /// \tparam C The value 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". It is an efficient dual
70 70
  /// solution method.
71 71
  ///
72 72
  /// Most of the parameters of the problem (except for the digraph)
73 73
  /// can be given using separate functions, and the algorithm can be
74 74
  /// executed using the \ref run() function. If some parameters are not
75 75
  /// specified, then default values will be used.
76 76
  ///
77 77
  /// \tparam GR The digraph type the algorithm runs on.
78 78
  /// \tparam V The value type used for flow amounts, capacity bounds
79 79
  /// and supply values in the algorithm. By default it is \c int.
80 80
  /// \tparam C The value type used for costs and potentials in the
81 81
  /// algorithm. By default it is the same as \c V.
82 82
  ///
83 83
  /// \warning Both value types must be signed and all input data must
84 84
  /// be integer.
85 85
  /// \warning This algorithm does not support negative costs for such
86 86
  /// arcs that have infinite upper bound.
87 87
#ifdef DOXYGEN
88 88
  template <typename GR, typename V, typename C, typename TR>
89 89
#else
90 90
  template < typename GR, typename V = int, typename C = V,
91 91
             typename TR = CapacityScalingDefaultTraits<GR, V, C> >
92 92
#endif
93 93
  class CapacityScaling
94 94
  {
95 95
  public:
96 96

	
97 97
    /// The type of the digraph
98 98
    typedef typename TR::Digraph Digraph;
99 99
    /// The type of the flow amounts, capacity bounds and supply values
100 100
    typedef typename TR::Value Value;
101 101
    /// The type of the arc costs
102 102
    typedef typename TR::Cost Cost;
103 103

	
104 104
    /// The type of the heap used for internal Dijkstra computations
105 105
    typedef typename TR::Heap Heap;
106 106

	
107 107
    /// The \ref CapacityScalingDefaultTraits "traits class" of the algorithm
108 108
    typedef TR Traits;
109 109

	
110 110
  public:
111 111

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

	
133 133
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
134 134

	
135 135
    typedef std::vector<int> IntVector;
136
    typedef std::vector<bool> BoolVector;
136
    typedef std::vector<char> BoolVector;
137 137
    typedef std::vector<Value> ValueVector;
138 138
    typedef std::vector<Cost> CostVector;
139 139

	
140 140
  private:
141 141

	
142 142
    // Data related to the underlying digraph
143 143
    const GR &_graph;
144 144
    int _node_num;
145 145
    int _arc_num;
146 146
    int _res_arc_num;
147 147
    int _root;
148 148

	
149 149
    // Parameters of the problem
150 150
    bool _have_lower;
151 151
    Value _sum_supply;
152 152

	
153 153
    // Data structures for storing the digraph
154 154
    IntNodeMap _node_id;
155 155
    IntArcMap _arc_idf;
156 156
    IntArcMap _arc_idb;
157 157
    IntVector _first_out;
158 158
    BoolVector _forward;
159 159
    IntVector _source;
160 160
    IntVector _target;
161 161
    IntVector _reverse;
162 162

	
163 163
    // Node and arc data
164 164
    ValueVector _lower;
165 165
    ValueVector _upper;
166 166
    CostVector _cost;
167 167
    ValueVector _supply;
168 168

	
169 169
    ValueVector _res_cap;
170 170
    CostVector _pi;
171 171
    ValueVector _excess;
172 172
    IntVector _excess_nodes;
173 173
    IntVector _deficit_nodes;
174 174

	
175 175
    Value _delta;
176 176
    int _factor;
177 177
    IntVector _pred;
178 178

	
179 179
  public:
180 180
  
181 181
    /// \brief Constant for infinite upper bounds (capacities).
182 182
    ///
183 183
    /// Constant for infinite upper bounds (capacities).
184 184
    /// It is \c std::numeric_limits<Value>::infinity() if available,
185 185
    /// \c std::numeric_limits<Value>::max() otherwise.
186 186
    const Value INF;
187 187

	
188 188
  private:
189 189

	
190 190
    // Special implementation of the Dijkstra algorithm for finding
191 191
    // shortest paths in the residual network of the digraph with
192 192
    // respect to the reduced arc costs and modifying the node
193 193
    // potentials according to the found distance labels.
194 194
    class ResidualDijkstra
195 195
    {
196 196
    private:
197 197

	
198 198
      int _node_num;
199
      bool _geq;
199 200
      const IntVector &_first_out;
200 201
      const IntVector &_target;
201 202
      const CostVector &_cost;
202 203
      const ValueVector &_res_cap;
203 204
      const ValueVector &_excess;
204 205
      CostVector &_pi;
205 206
      IntVector &_pred;
206 207
      
207 208
      IntVector _proc_nodes;
208 209
      CostVector _dist;
209 210
      
210 211
    public:
211 212

	
212 213
      ResidualDijkstra(CapacityScaling& cs) :
213
        _node_num(cs._node_num), _first_out(cs._first_out), 
214
        _target(cs._target), _cost(cs._cost), _res_cap(cs._res_cap),
215
        _excess(cs._excess), _pi(cs._pi), _pred(cs._pred),
216
        _dist(cs._node_num)
214
        _node_num(cs._node_num), _geq(cs._sum_supply < 0),
215
        _first_out(cs._first_out), _target(cs._target), _cost(cs._cost),
216
        _res_cap(cs._res_cap), _excess(cs._excess), _pi(cs._pi),
217
        _pred(cs._pred), _dist(cs._node_num)
217 218
      {}
218 219

	
219 220
      int run(int s, Value delta = 1) {
220 221
        RangeMap<int> heap_cross_ref(_node_num, Heap::PRE_HEAP);
221 222
        Heap heap(heap_cross_ref);
222 223
        heap.push(s, 0);
223 224
        _pred[s] = -1;
224 225
        _proc_nodes.clear();
225 226

	
226 227
        // Process nodes
227 228
        while (!heap.empty() && _excess[heap.top()] > -delta) {
228 229
          int u = heap.top(), v;
229 230
          Cost d = heap.prio() + _pi[u], dn;
230 231
          _dist[u] = heap.prio();
231 232
          _proc_nodes.push_back(u);
232 233
          heap.pop();
233 234

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

	
257 259
        // Update potentials of processed nodes
258 260
        int t = heap.top();
259 261
        Cost dt = heap.prio();
260 262
        for (int i = 0; i < int(_proc_nodes.size()); ++i) {
261 263
          _pi[_proc_nodes[i]] += _dist[_proc_nodes[i]] - dt;
262 264
        }
263 265

	
264 266
        return t;
265 267
      }
266 268

	
267 269
    }; //class ResidualDijkstra
268 270

	
269 271
  public:
270 272

	
271 273
    /// \name Named Template Parameters
272 274
    /// @{
273 275

	
274 276
    template <typename T>
275 277
    struct SetHeapTraits : public Traits {
276 278
      typedef T Heap;
277 279
    };
278 280

	
279 281
    /// \brief \ref named-templ-param "Named parameter" for setting
280 282
    /// \c Heap type.
281 283
    ///
282 284
    /// \ref named-templ-param "Named parameter" for setting \c Heap
283 285
    /// type, which is used for internal Dijkstra computations.
284 286
    /// It must conform to the \ref lemon::concepts::Heap "Heap" concept,
285 287
    /// its priority type must be \c Cost and its cross reference type
286 288
    /// must be \ref RangeMap "RangeMap<int>".
287 289
    template <typename T>
288 290
    struct SetHeap
289 291
      : public CapacityScaling<GR, V, C, SetHeapTraits<T> > {
290 292
      typedef  CapacityScaling<GR, V, C, SetHeapTraits<T> > Create;
291 293
    };
292 294

	
293 295
    /// @}
294 296

	
295 297
  public:
296 298

	
297 299
    /// \brief Constructor.
298 300
    ///
299 301
    /// The constructor of the class.
300 302
    ///
301 303
    /// \param graph The digraph the algorithm runs on.
302 304
    CapacityScaling(const GR& graph) :
303 305
      _graph(graph), _node_id(graph), _arc_idf(graph), _arc_idb(graph),
304 306
      INF(std::numeric_limits<Value>::has_infinity ?
305 307
          std::numeric_limits<Value>::infinity() :
306 308
          std::numeric_limits<Value>::max())
307 309
    {
308 310
      // Check the value types
309 311
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
310 312
        "The flow type of CapacityScaling must be signed");
311 313
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
312 314
        "The cost type of CapacityScaling must be signed");
313 315

	
314 316
      // Resize vectors
315 317
      _node_num = countNodes(_graph);
316 318
      _arc_num = countArcs(_graph);
317 319
      _res_arc_num = 2 * (_arc_num + _node_num);
318 320
      _root = _node_num;
319 321
      ++_node_num;
320 322

	
321 323
      _first_out.resize(_node_num + 1);
322 324
      _forward.resize(_res_arc_num);
323 325
      _source.resize(_res_arc_num);
324 326
      _target.resize(_res_arc_num);
325 327
      _reverse.resize(_res_arc_num);
326 328

	
327 329
      _lower.resize(_res_arc_num);
328 330
      _upper.resize(_res_arc_num);
329 331
      _cost.resize(_res_arc_num);
330 332
      _supply.resize(_node_num);
331 333
      
332 334
      _res_cap.resize(_res_arc_num);
333 335
      _pi.resize(_node_num);
334 336
      _excess.resize(_node_num);
335 337
      _pred.resize(_node_num);
336 338

	
337 339
      // Copy the graph
338 340
      int i = 0, j = 0, k = 2 * _arc_num + _node_num - 1;
339 341
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
340 342
        _node_id[n] = i;
341 343
      }
342 344
      i = 0;
343 345
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
344 346
        _first_out[i] = j;
345 347
        for (OutArcIt a(_graph, n); a != INVALID; ++a, ++j) {
346 348
          _arc_idf[a] = j;
347 349
          _forward[j] = true;
348 350
          _source[j] = i;
349 351
          _target[j] = _node_id[_graph.runningNode(a)];
350 352
        }
351 353
        for (InArcIt a(_graph, n); a != INVALID; ++a, ++j) {
352 354
          _arc_idb[a] = j;
353 355
          _forward[j] = false;
354 356
          _source[j] = i;
355 357
          _target[j] = _node_id[_graph.runningNode(a)];
356 358
        }
357 359
        _forward[j] = false;
358 360
        _source[j] = i;
359 361
        _target[j] = _root;
360 362
        _reverse[j] = k;
361 363
        _forward[k] = true;
362 364
        _source[k] = _root;
363 365
        _target[k] = i;
364 366
        _reverse[k] = j;
365 367
        ++j; ++k;
366 368
      }
367 369
      _first_out[i] = j;
368 370
      _first_out[_node_num] = k;
369 371
      for (ArcIt a(_graph); a != INVALID; ++a) {
370 372
        int fi = _arc_idf[a];
371 373
        int bi = _arc_idb[a];
372 374
        _reverse[fi] = bi;
373 375
        _reverse[bi] = fi;
374 376
      }
375 377
      
376 378
      // Reset parameters
377 379
      reset();
378 380
    }
379 381

	
380 382
    /// \name Parameters
381 383
    /// The parameters of the algorithm can be specified using these
382 384
    /// functions.
383 385

	
384 386
    /// @{
385 387

	
386 388
    /// \brief Set the lower bounds on the arcs.
387 389
    ///
388 390
    /// This function sets the lower bounds on the arcs.
389 391
    /// If it is not used before calling \ref run(), the lower bounds
390 392
    /// will be set to zero on all arcs.
391 393
    ///
392 394
    /// \param map An arc map storing the lower bounds.
393 395
    /// Its \c Value type must be convertible to the \c Value type
394 396
    /// of the algorithm.
395 397
    ///
396 398
    /// \return <tt>(*this)</tt>
397 399
    template <typename LowerMap>
398 400
    CapacityScaling& lowerMap(const LowerMap& map) {
399 401
      _have_lower = true;
400 402
      for (ArcIt a(_graph); a != INVALID; ++a) {
401 403
        _lower[_arc_idf[a]] = map[a];
402 404
        _lower[_arc_idb[a]] = map[a];
403 405
      }
404 406
      return *this;
405 407
    }
406 408

	
407 409
    /// \brief Set the upper bounds (capacities) on the arcs.
408 410
    ///
409 411
    /// This function sets the upper bounds (capacities) on the arcs.
410 412
    /// If it is not used before calling \ref run(), the upper bounds
411 413
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
412 414
    /// unbounded from above on each arc).
413 415
    ///
414 416
    /// \param map An arc map storing the upper bounds.
415 417
    /// Its \c Value type must be convertible to the \c Value type
416 418
    /// of the algorithm.
417 419
    ///
418 420
    /// \return <tt>(*this)</tt>
419 421
    template<typename UpperMap>
420 422
    CapacityScaling& upperMap(const UpperMap& map) {
421 423
      for (ArcIt a(_graph); a != INVALID; ++a) {
422 424
        _upper[_arc_idf[a]] = map[a];
423 425
      }
424 426
      return *this;
425 427
    }
426 428

	
427 429
    /// \brief Set the costs of the arcs.
... ...
@@ -498,444 +500,451 @@
498 500

	
499 501
    /// \brief Run the algorithm.
500 502
    ///
501 503
    /// This function runs the algorithm.
502 504
    /// The paramters can be specified using functions \ref lowerMap(),
503 505
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply().
504 506
    /// For example,
505 507
    /// \code
506 508
    ///   CapacityScaling<ListDigraph> cs(graph);
507 509
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
508 510
    ///     .supplyMap(sup).run();
509 511
    /// \endcode
510 512
    ///
511 513
    /// This function can be called more than once. All the parameters
512 514
    /// that have been given are kept for the next call, unless
513 515
    /// \ref reset() is called, thus only the modified parameters
514 516
    /// have to be set again. See \ref reset() for examples.
515 517
    /// However the underlying digraph must not be modified after this
516 518
    /// class have been constructed, since it copies and extends the graph.
517 519
    ///
518 520
    /// \param factor The capacity scaling factor. It must be larger than
519 521
    /// one to use scaling. If it is less or equal to one, then scaling
520 522
    /// will be disabled.
521 523
    ///
522 524
    /// \return \c INFEASIBLE if no feasible flow exists,
523 525
    /// \n \c OPTIMAL if the problem has optimal solution
524 526
    /// (i.e. it is feasible and bounded), and the algorithm has found
525 527
    /// optimal flow and node potentials (primal and dual solutions),
526 528
    /// \n \c UNBOUNDED if the digraph contains an arc of negative cost
527 529
    /// and infinite upper bound. It means that the objective function
528 530
    /// is unbounded on that arc, however note that it could actually be
529 531
    /// bounded over the feasible flows, but this algroithm cannot handle
530 532
    /// these cases.
531 533
    ///
532 534
    /// \see ProblemType
533 535
    ProblemType run(int factor = 4) {
534 536
      _factor = factor;
535 537
      ProblemType pt = init();
536 538
      if (pt != OPTIMAL) return pt;
537 539
      return start();
538 540
    }
539 541

	
540 542
    /// \brief Reset all the parameters that have been given before.
541 543
    ///
542 544
    /// This function resets all the paramaters that have been given
543 545
    /// before using functions \ref lowerMap(), \ref upperMap(),
544 546
    /// \ref costMap(), \ref supplyMap(), \ref stSupply().
545 547
    ///
546 548
    /// It is useful for multiple run() calls. If this function is not
547 549
    /// used, all the parameters given before are kept for the next
548 550
    /// \ref run() call.
549 551
    /// However, the underlying digraph must not be modified after this
550 552
    /// class have been constructed, since it copies and extends the graph.
551 553
    ///
552 554
    /// For example,
553 555
    /// \code
554 556
    ///   CapacityScaling<ListDigraph> cs(graph);
555 557
    ///
556 558
    ///   // First run
557 559
    ///   cs.lowerMap(lower).upperMap(upper).costMap(cost)
558 560
    ///     .supplyMap(sup).run();
559 561
    ///
560 562
    ///   // Run again with modified cost map (reset() is not called,
561 563
    ///   // so only the cost map have to be set again)
562 564
    ///   cost[e] += 100;
563 565
    ///   cs.costMap(cost).run();
564 566
    ///
565 567
    ///   // Run again from scratch using reset()
566 568
    ///   // (the lower bounds will be set to zero on all arcs)
567 569
    ///   cs.reset();
568 570
    ///   cs.upperMap(capacity).costMap(cost)
569 571
    ///     .supplyMap(sup).run();
570 572
    /// \endcode
571 573
    ///
572 574
    /// \return <tt>(*this)</tt>
573 575
    CapacityScaling& reset() {
574 576
      for (int i = 0; i != _node_num; ++i) {
575 577
        _supply[i] = 0;
576 578
      }
577 579
      for (int j = 0; j != _res_arc_num; ++j) {
578 580
        _lower[j] = 0;
579 581
        _upper[j] = INF;
580 582
        _cost[j] = _forward[j] ? 1 : -1;
581 583
      }
582 584
      _have_lower = false;
583 585
      return *this;
584 586
    }
585 587

	
586 588
    /// @}
587 589

	
588 590
    /// \name Query Functions
589 591
    /// The results of the algorithm can be obtained using these
590 592
    /// functions.\n
591 593
    /// The \ref run() function must be called before using them.
592 594

	
593 595
    /// @{
594 596

	
595 597
    /// \brief Return the total cost of the found flow.
596 598
    ///
597 599
    /// This function returns the total cost of the found flow.
598 600
    /// Its complexity is O(e).
599 601
    ///
600 602
    /// \note The return type of the function can be specified as a
601 603
    /// template parameter. For example,
602 604
    /// \code
603 605
    ///   cs.totalCost<double>();
604 606
    /// \endcode
605 607
    /// It is useful if the total cost cannot be stored in the \c Cost
606 608
    /// type of the algorithm, which is the default return type of the
607 609
    /// function.
608 610
    ///
609 611
    /// \pre \ref run() must be called before using this function.
610 612
    template <typename Number>
611 613
    Number totalCost() const {
612 614
      Number c = 0;
613 615
      for (ArcIt a(_graph); a != INVALID; ++a) {
614 616
        int i = _arc_idb[a];
615 617
        c += static_cast<Number>(_res_cap[i]) *
616 618
             (-static_cast<Number>(_cost[i]));
617 619
      }
618 620
      return c;
619 621
    }
620 622

	
621 623
#ifndef DOXYGEN
622 624
    Cost totalCost() const {
623 625
      return totalCost<Cost>();
624 626
    }
625 627
#endif
626 628

	
627 629
    /// \brief Return the flow on the given arc.
628 630
    ///
629 631
    /// This function returns the flow on the given arc.
630 632
    ///
631 633
    /// \pre \ref run() must be called before using this function.
632 634
    Value flow(const Arc& a) const {
633 635
      return _res_cap[_arc_idb[a]];
634 636
    }
635 637

	
636 638
    /// \brief Return the flow map (the primal solution).
637 639
    ///
638 640
    /// This function copies the flow value on each arc into the given
639 641
    /// map. The \c Value type of the algorithm must be convertible to
640 642
    /// the \c Value type of the map.
641 643
    ///
642 644
    /// \pre \ref run() must be called before using this function.
643 645
    template <typename FlowMap>
644 646
    void flowMap(FlowMap &map) const {
645 647
      for (ArcIt a(_graph); a != INVALID; ++a) {
646 648
        map.set(a, _res_cap[_arc_idb[a]]);
647 649
      }
648 650
    }
649 651

	
650 652
    /// \brief Return the potential (dual value) of the given node.
651 653
    ///
652 654
    /// This function returns the potential (dual value) of the
653 655
    /// given node.
654 656
    ///
655 657
    /// \pre \ref run() must be called before using this function.
656 658
    Cost potential(const Node& n) const {
657 659
      return _pi[_node_id[n]];
658 660
    }
659 661

	
660 662
    /// \brief Return the potential map (the dual solution).
661 663
    ///
662 664
    /// This function copies the potential (dual value) of each node
663 665
    /// into the given map.
664 666
    /// The \c Cost type of the algorithm must be convertible to the
665 667
    /// \c Value type of the map.
666 668
    ///
667 669
    /// \pre \ref run() must be called before using this function.
668 670
    template <typename PotentialMap>
669 671
    void potentialMap(PotentialMap &map) const {
670 672
      for (NodeIt n(_graph); n != INVALID; ++n) {
671 673
        map.set(n, _pi[_node_id[n]]);
672 674
      }
673 675
    }
674 676

	
675 677
    /// @}
676 678

	
677 679
  private:
678 680

	
679 681
    // Initialize the algorithm
680 682
    ProblemType init() {
681 683
      if (_node_num == 0) return INFEASIBLE;
682 684

	
683 685
      // Check the sum of supply values
684 686
      _sum_supply = 0;
685 687
      for (int i = 0; i != _root; ++i) {
686 688
        _sum_supply += _supply[i];
687 689
      }
688 690
      if (_sum_supply > 0) return INFEASIBLE;
689 691
      
690
      // Initialize maps
692
      // Initialize vectors
691 693
      for (int i = 0; i != _root; ++i) {
692 694
        _pi[i] = 0;
693 695
        _excess[i] = _supply[i];
694 696
      }
695 697

	
696 698
      // Remove non-zero lower bounds
699
      const Value MAX = std::numeric_limits<Value>::max();
700
      int last_out;
697 701
      if (_have_lower) {
698 702
        for (int i = 0; i != _root; ++i) {
699
          for (int j = _first_out[i]; j != _first_out[i+1]; ++j) {
703
          last_out = _first_out[i+1];
704
          for (int j = _first_out[i]; j != last_out; ++j) {
700 705
            if (_forward[j]) {
701 706
              Value c = _lower[j];
702 707
              if (c >= 0) {
703
                _res_cap[j] = _upper[j] < INF ? _upper[j] - c : INF;
708
                _res_cap[j] = _upper[j] < MAX ? _upper[j] - c : INF;
704 709
              } else {
705
                _res_cap[j] = _upper[j] < INF + c ? _upper[j] - c : INF;
710
                _res_cap[j] = _upper[j] < MAX + c ? _upper[j] - c : INF;
706 711
              }
707 712
              _excess[i] -= c;
708 713
              _excess[_target[j]] += c;
709 714
            } else {
710 715
              _res_cap[j] = 0;
711 716
            }
712 717
          }
713 718
        }
714 719
      } else {
715 720
        for (int j = 0; j != _res_arc_num; ++j) {
716 721
          _res_cap[j] = _forward[j] ? _upper[j] : 0;
717 722
        }
718 723
      }
719 724

	
720 725
      // Handle negative costs
721
      for (int u = 0; u != _root; ++u) {
722
        for (int a = _first_out[u]; a != _first_out[u+1]; ++a) {
723
          Value rc = _res_cap[a];
724
          if (_cost[a] < 0 && rc > 0) {
725
            if (rc == INF) return UNBOUNDED;
726
            _excess[u] -= rc;
727
            _excess[_target[a]] += rc;
728
            _res_cap[a] = 0;
729
            _res_cap[_reverse[a]] += rc;
726
      for (int i = 0; i != _root; ++i) {
727
        last_out = _first_out[i+1] - 1;
728
        for (int j = _first_out[i]; j != last_out; ++j) {
729
          Value rc = _res_cap[j];
730
          if (_cost[j] < 0 && rc > 0) {
731
            if (rc >= MAX) return UNBOUNDED;
732
            _excess[i] -= rc;
733
            _excess[_target[j]] += rc;
734
            _res_cap[j] = 0;
735
            _res_cap[_reverse[j]] += rc;
730 736
          }
731 737
        }
732 738
      }
733 739
      
734 740
      // Handle GEQ supply type
735 741
      if (_sum_supply < 0) {
736 742
        _pi[_root] = 0;
737 743
        _excess[_root] = -_sum_supply;
738 744
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
739
          int u = _target[a];
740
          if (_excess[u] < 0) {
741
            _res_cap[a] = -_excess[u] + 1;
742
          } else {
743
            _res_cap[a] = 1;
744
          }
745
          _res_cap[_reverse[a]] = 0;
745
          int ra = _reverse[a];
746
          _res_cap[a] = -_sum_supply + 1;
747
          _res_cap[ra] = 0;
746 748
          _cost[a] = 0;
747
          _cost[_reverse[a]] = 0;
749
          _cost[ra] = 0;
748 750
        }
749 751
      } else {
750 752
        _pi[_root] = 0;
751 753
        _excess[_root] = 0;
752 754
        for (int a = _first_out[_root]; a != _res_arc_num; ++a) {
755
          int ra = _reverse[a];
753 756
          _res_cap[a] = 1;
754
          _res_cap[_reverse[a]] = 0;
757
          _res_cap[ra] = 0;
755 758
          _cost[a] = 0;
756
          _cost[_reverse[a]] = 0;
759
          _cost[ra] = 0;
757 760
        }
758 761
      }
759 762

	
760 763
      // Initialize delta value
761 764
      if (_factor > 1) {
762 765
        // With scaling
763 766
        Value max_sup = 0, max_dem = 0;
764 767
        for (int i = 0; i != _node_num; ++i) {
765
          if ( _excess[i] > max_sup) max_sup =  _excess[i];
766
          if (-_excess[i] > max_dem) max_dem = -_excess[i];
768
          Value ex = _excess[i];
769
          if ( ex > max_sup) max_sup =  ex;
770
          if (-ex > max_dem) max_dem = -ex;
767 771
        }
768 772
        Value max_cap = 0;
769 773
        for (int j = 0; j != _res_arc_num; ++j) {
770 774
          if (_res_cap[j] > max_cap) max_cap = _res_cap[j];
771 775
        }
772 776
        max_sup = std::min(std::min(max_sup, max_dem), max_cap);
773 777
        for (_delta = 1; 2 * _delta <= max_sup; _delta *= 2) ;
774 778
      } else {
775 779
        // Without scaling
776 780
        _delta = 1;
777 781
      }
778 782

	
779 783
      return OPTIMAL;
780 784
    }
781 785

	
782 786
    ProblemType start() {
783 787
      // Execute the algorithm
784 788
      ProblemType pt;
785 789
      if (_delta > 1)
786 790
        pt = startWithScaling();
787 791
      else
788 792
        pt = startWithoutScaling();
789 793

	
790 794
      // Handle non-zero lower bounds
791 795
      if (_have_lower) {
792
        for (int j = 0; j != _res_arc_num - _node_num + 1; ++j) {
796
        int limit = _first_out[_root];
797
        for (int j = 0; j != limit; ++j) {
793 798
          if (!_forward[j]) _res_cap[j] += _lower[j];
794 799
        }
795 800
      }
796 801

	
797 802
      // Shift potentials if necessary
798 803
      Cost pr = _pi[_root];
799 804
      if (_sum_supply < 0 || pr > 0) {
800 805
        for (int i = 0; i != _node_num; ++i) {
801 806
          _pi[i] -= pr;
802 807
        }        
803 808
      }
804 809
      
805 810
      return pt;
806 811
    }
807 812

	
808 813
    // Execute the capacity scaling algorithm
809 814
    ProblemType startWithScaling() {
810 815
      // Perform capacity scaling phases
811 816
      int s, t;
812 817
      ResidualDijkstra _dijkstra(*this);
813 818
      while (true) {
814 819
        // Saturate all arcs not satisfying the optimality condition
820
        int last_out;
815 821
        for (int u = 0; u != _node_num; ++u) {
816
          for (int a = _first_out[u]; a != _first_out[u+1]; ++a) {
822
          last_out = _sum_supply < 0 ?
823
            _first_out[u+1] : _first_out[u+1] - 1;
824
          for (int a = _first_out[u]; a != last_out; ++a) {
817 825
            int v = _target[a];
818 826
            Cost c = _cost[a] + _pi[u] - _pi[v];
819 827
            Value rc = _res_cap[a];
820 828
            if (c < 0 && rc >= _delta) {
821 829
              _excess[u] -= rc;
822 830
              _excess[v] += rc;
823 831
              _res_cap[a] = 0;
824 832
              _res_cap[_reverse[a]] += rc;
825 833
            }
826 834
          }
827 835
        }
828 836

	
829 837
        // Find excess nodes and deficit nodes
830 838
        _excess_nodes.clear();
831 839
        _deficit_nodes.clear();
832 840
        for (int u = 0; u != _node_num; ++u) {
833
          if (_excess[u] >=  _delta) _excess_nodes.push_back(u);
834
          if (_excess[u] <= -_delta) _deficit_nodes.push_back(u);
841
          Value ex = _excess[u];
842
          if (ex >=  _delta) _excess_nodes.push_back(u);
843
          if (ex <= -_delta) _deficit_nodes.push_back(u);
835 844
        }
836 845
        int next_node = 0, next_def_node = 0;
837 846

	
838 847
        // Find augmenting shortest paths
839 848
        while (next_node < int(_excess_nodes.size())) {
840 849
          // Check deficit nodes
841 850
          if (_delta > 1) {
842 851
            bool delta_deficit = false;
843 852
            for ( ; next_def_node < int(_deficit_nodes.size());
844 853
                    ++next_def_node ) {
845 854
              if (_excess[_deficit_nodes[next_def_node]] <= -_delta) {
846 855
                delta_deficit = true;
847 856
                break;
848 857
              }
849 858
            }
850 859
            if (!delta_deficit) break;
851 860
          }
852 861

	
853 862
          // Run Dijkstra in the residual network
854 863
          s = _excess_nodes[next_node];
855 864
          if ((t = _dijkstra.run(s, _delta)) == -1) {
856 865
            if (_delta > 1) {
857 866
              ++next_node;
858 867
              continue;
859 868
            }
860 869
            return INFEASIBLE;
861 870
          }
862 871

	
863 872
          // Augment along a shortest path from s to t
864 873
          Value d = std::min(_excess[s], -_excess[t]);
865 874
          int u = t;
866 875
          int a;
867 876
          if (d > _delta) {
868 877
            while ((a = _pred[u]) != -1) {
869 878
              if (_res_cap[a] < d) d = _res_cap[a];
870 879
              u = _source[a];
871 880
            }
872 881
          }
873 882
          u = t;
874 883
          while ((a = _pred[u]) != -1) {
875 884
            _res_cap[a] -= d;
876 885
            _res_cap[_reverse[a]] += d;
877 886
            u = _source[a];
878 887
          }
879 888
          _excess[s] -= d;
880 889
          _excess[t] += d;
881 890

	
882 891
          if (_excess[s] < _delta) ++next_node;
883 892
        }
884 893

	
885 894
        if (_delta == 1) break;
886 895
        _delta = _delta <= _factor ? 1 : _delta / _factor;
887 896
      }
888 897

	
889 898
      return OPTIMAL;
890 899
    }
891 900

	
892 901
    // Execute the successive shortest path algorithm
893 902
    ProblemType startWithoutScaling() {
894 903
      // Find excess nodes
895 904
      _excess_nodes.clear();
896 905
      for (int i = 0; i != _node_num; ++i) {
897 906
        if (_excess[i] > 0) _excess_nodes.push_back(i);
898 907
      }
899 908
      if (_excess_nodes.size() == 0) return OPTIMAL;
900 909
      int next_node = 0;
901 910

	
902 911
      // Find shortest paths
903 912
      int s, t;
904 913
      ResidualDijkstra _dijkstra(*this);
905 914
      while ( _excess[_excess_nodes[next_node]] > 0 ||
906 915
              ++next_node < int(_excess_nodes.size()) )
907 916
      {
908 917
        // Run Dijkstra in the residual network
909 918
        s = _excess_nodes[next_node];
910 919
        if ((t = _dijkstra.run(s)) == -1) return INFEASIBLE;
911 920

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

	
932 941
      return OPTIMAL;
933 942
    }
934 943

	
935 944
  }; //class CapacityScaling
936 945

	
937 946
  ///@}
938 947

	
939 948
} //namespace lemon
940 949

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

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

	
22 22
/// \ingroup min_cost_flow_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 specialized version of the linear programming
47 47
  /// simplex method directly for the minimum cost flow problem.
48 48
  /// It is one of the most efficient solution methods.
49 49
  ///
50 50
  /// In general this class is the fastest implementation available
51 51
  /// in LEMON for the minimum cost flow 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 value 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 value type used for costs and potentials in the
64 64
  /// algorithm. By default, it is the same as \c V.
65 65
  ///
66 66
  /// \warning Both value types must be signed and all input data must
67 67
  /// be integer.
68 68
  ///
69 69
  /// \note %NetworkSimplex provides five different pivot rule
70 70
  /// implementations, from which the most efficient one is used
71 71
  /// by default. For more information, see \ref PivotRule.
72 72
  template <typename GR, typename V = int, typename C = V>
73 73
  class NetworkSimplex
74 74
  {
75 75
  public:
76 76

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

	
82 82
  public:
83 83

	
84 84
    /// \brief Problem type constants for the \c run() function.
85 85
    ///
86 86
    /// Enum type containing the problem type constants that can be
87 87
    /// returned by the \ref run() function of the algorithm.
88 88
    enum ProblemType {
89 89
      /// The problem has no feasible solution (flow).
90 90
      INFEASIBLE,
91 91
      /// The problem has optimal solution (i.e. it is feasible and
92 92
      /// bounded), and the algorithm has found optimal flow and node
93 93
      /// potentials (primal and dual solutions).
94 94
      OPTIMAL,
95 95
      /// The objective function of the problem is unbounded, i.e.
96 96
      /// there is a directed cycle having negative total cost and
97 97
      /// infinite upper bound.
98 98
      UNBOUNDED
99 99
    };
100 100
    
101 101
    /// \brief Constants for selecting the type of the supply constraints.
102 102
    ///
103 103
    /// Enum type containing constants for selecting the supply type,
104 104
    /// i.e. the direction of the inequalities in the supply/demand
105 105
    /// constraints of the \ref min_cost_flow "minimum cost flow problem".
106 106
    ///
107 107
    /// The default supply type is \c GEQ, the \c LEQ type can be
108 108
    /// selected using \ref supplyType().
109 109
    /// The equality form is a special case of both supply types.
110 110
    enum SupplyType {
111 111
      /// This option means that there are <em>"greater or equal"</em>
112 112
      /// supply/demand constraints in the definition of the problem.
113 113
      GEQ,
114 114
      /// This option means that there are <em>"less or equal"</em>
115 115
      /// supply/demand constraints in the definition of the problem.
116 116
      LEQ
117 117
    };
118 118
    
119 119
    /// \brief Constants for selecting the pivot rule.
120 120
    ///
121 121
    /// Enum type containing constants for selecting the pivot rule for
122 122
    /// the \ref run() function.
123 123
    ///
124 124
    /// \ref NetworkSimplex provides five different pivot rule
125 125
    /// implementations that significantly affect the running time
126 126
    /// of the algorithm.
127 127
    /// By default, \ref BLOCK_SEARCH "Block Search" is used, which
128 128
    /// proved to be the most efficient and the most robust on various
129 129
    /// test inputs according to our benchmark tests.
130 130
    /// However, another pivot rule can be selected using the \ref run()
131 131
    /// function with the proper parameter.
132 132
    enum PivotRule {
133 133

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

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

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

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

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

	
164 164
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
165 165

	
166 166
    typedef std::vector<int> IntVector;
167
    typedef std::vector<bool> BoolVector;
167
    typedef std::vector<char> CharVector;
168 168
    typedef std::vector<Value> ValueVector;
169 169
    typedef std::vector<Cost> CostVector;
170 170

	
171 171
    // State constants for arcs
172 172
    enum ArcStateEnum {
173 173
      STATE_UPPER = -1,
174 174
      STATE_TREE  =  0,
175 175
      STATE_LOWER =  1
176 176
    };
177 177

	
178 178
  private:
179 179

	
180 180
    // Data related to the underlying digraph
181 181
    const GR &_graph;
182 182
    int _node_num;
183 183
    int _arc_num;
184 184
    int _all_arc_num;
185 185
    int _search_arc_num;
186 186

	
187 187
    // Parameters of the problem
188 188
    bool _have_lower;
189 189
    SupplyType _stype;
190 190
    Value _sum_supply;
191 191

	
192 192
    // Data structures for storing the digraph
193 193
    IntNodeMap _node_id;
194 194
    IntArcMap _arc_id;
195 195
    IntVector _source;
196 196
    IntVector _target;
197 197

	
198 198
    // Node and arc data
199 199
    ValueVector _lower;
200 200
    ValueVector _upper;
201 201
    ValueVector _cap;
202 202
    CostVector _cost;
203 203
    ValueVector _supply;
204 204
    ValueVector _flow;
205 205
    CostVector _pi;
206 206

	
207 207
    // Data for storing the spanning tree structure
208 208
    IntVector _parent;
209 209
    IntVector _pred;
210 210
    IntVector _thread;
211 211
    IntVector _rev_thread;
212 212
    IntVector _succ_num;
213 213
    IntVector _last_succ;
214 214
    IntVector _dirty_revs;
215
    BoolVector _forward;
216
    IntVector _state;
215
    CharVector _forward;
216
    CharVector _state;
217 217
    int _root;
218 218

	
219 219
    // Temporary data used in the current pivot iteration
220 220
    int in_arc, join, u_in, v_in, u_out, v_out;
221 221
    int first, second, right, last;
222 222
    int stem, par_stem, new_stem;
223 223
    Value delta;
224
    
225
    const Value MAX;
224 226

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

	
234 236
  private:
235 237

	
236 238
    // Implementation of the First Eligible pivot rule
237 239
    class FirstEligiblePivotRule
238 240
    {
239 241
    private:
240 242

	
241 243
      // References to the NetworkSimplex class
242 244
      const IntVector  &_source;
243 245
      const IntVector  &_target;
244 246
      const CostVector &_cost;
245
      const IntVector  &_state;
247
      const CharVector &_state;
246 248
      const CostVector &_pi;
247 249
      int &_in_arc;
248 250
      int _search_arc_num;
249 251

	
250 252
      // Pivot rule data
251 253
      int _next_arc;
252 254

	
253 255
    public:
254 256

	
255 257
      // Constructor
256 258
      FirstEligiblePivotRule(NetworkSimplex &ns) :
257 259
        _source(ns._source), _target(ns._target),
258 260
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
259 261
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
260 262
        _next_arc(0)
261 263
      {}
262 264

	
263 265
      // Find next entering arc
264 266
      bool findEnteringArc() {
265 267
        Cost c;
266 268
        for (int e = _next_arc; e < _search_arc_num; ++e) {
267 269
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
268 270
          if (c < 0) {
269 271
            _in_arc = e;
270 272
            _next_arc = e + 1;
271 273
            return true;
272 274
          }
273 275
        }
274 276
        for (int e = 0; e < _next_arc; ++e) {
275 277
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
276 278
          if (c < 0) {
277 279
            _in_arc = e;
278 280
            _next_arc = e + 1;
279 281
            return true;
280 282
          }
281 283
        }
282 284
        return false;
283 285
      }
284 286

	
285 287
    }; //class FirstEligiblePivotRule
286 288

	
287 289

	
288 290
    // Implementation of the Best Eligible pivot rule
289 291
    class BestEligiblePivotRule
290 292
    {
291 293
    private:
292 294

	
293 295
      // References to the NetworkSimplex class
294 296
      const IntVector  &_source;
295 297
      const IntVector  &_target;
296 298
      const CostVector &_cost;
297
      const IntVector  &_state;
299
      const CharVector &_state;
298 300
      const CostVector &_pi;
299 301
      int &_in_arc;
300 302
      int _search_arc_num;
301 303

	
302 304
    public:
303 305

	
304 306
      // Constructor
305 307
      BestEligiblePivotRule(NetworkSimplex &ns) :
306 308
        _source(ns._source), _target(ns._target),
307 309
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
308 310
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num)
309 311
      {}
310 312

	
311 313
      // Find next entering arc
312 314
      bool findEnteringArc() {
313 315
        Cost c, min = 0;
314 316
        for (int e = 0; e < _search_arc_num; ++e) {
315 317
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
316 318
          if (c < min) {
317 319
            min = c;
318 320
            _in_arc = e;
319 321
          }
320 322
        }
321 323
        return min < 0;
322 324
      }
323 325

	
324 326
    }; //class BestEligiblePivotRule
325 327

	
326 328

	
327 329
    // Implementation of the Block Search pivot rule
328 330
    class BlockSearchPivotRule
329 331
    {
330 332
    private:
331 333

	
332 334
      // References to the NetworkSimplex class
333 335
      const IntVector  &_source;
334 336
      const IntVector  &_target;
335 337
      const CostVector &_cost;
336
      const IntVector  &_state;
338
      const CharVector &_state;
337 339
      const CostVector &_pi;
338 340
      int &_in_arc;
339 341
      int _search_arc_num;
340 342

	
341 343
      // Pivot rule data
342 344
      int _block_size;
343 345
      int _next_arc;
344 346

	
345 347
    public:
346 348

	
347 349
      // Constructor
348 350
      BlockSearchPivotRule(NetworkSimplex &ns) :
349 351
        _source(ns._source), _target(ns._target),
350 352
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
351 353
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
352 354
        _next_arc(0)
353 355
      {
354 356
        // The main parameters of the pivot rule
355 357
        const double BLOCK_SIZE_FACTOR = 0.5;
356 358
        const int MIN_BLOCK_SIZE = 10;
357 359

	
358 360
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
359 361
                                    std::sqrt(double(_search_arc_num))),
360 362
                                MIN_BLOCK_SIZE );
361 363
      }
362 364

	
363 365
      // Find next entering arc
364 366
      bool findEnteringArc() {
365 367
        Cost c, min = 0;
366 368
        int cnt = _block_size;
367 369
        int e;
368 370
        for (e = _next_arc; e < _search_arc_num; ++e) {
369 371
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
370 372
          if (c < min) {
371 373
            min = c;
372 374
            _in_arc = e;
373 375
          }
374 376
          if (--cnt == 0) {
375 377
            if (min < 0) goto search_end;
376 378
            cnt = _block_size;
377 379
          }
378 380
        }
379 381
        for (e = 0; e < _next_arc; ++e) {
380 382
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
381 383
          if (c < min) {
382 384
            min = c;
383 385
            _in_arc = e;
384 386
          }
385 387
          if (--cnt == 0) {
386 388
            if (min < 0) goto search_end;
387 389
            cnt = _block_size;
388 390
          }
389 391
        }
390 392
        if (min >= 0) return false;
391 393

	
392 394
      search_end:
393 395
        _next_arc = e;
394 396
        return true;
395 397
      }
396 398

	
397 399
    }; //class BlockSearchPivotRule
398 400

	
399 401

	
400 402
    // Implementation of the Candidate List pivot rule
401 403
    class CandidateListPivotRule
402 404
    {
403 405
    private:
404 406

	
405 407
      // References to the NetworkSimplex class
406 408
      const IntVector  &_source;
407 409
      const IntVector  &_target;
408 410
      const CostVector &_cost;
409
      const IntVector  &_state;
411
      const CharVector &_state;
410 412
      const CostVector &_pi;
411 413
      int &_in_arc;
412 414
      int _search_arc_num;
413 415

	
414 416
      // Pivot rule data
415 417
      IntVector _candidates;
416 418
      int _list_length, _minor_limit;
417 419
      int _curr_length, _minor_count;
418 420
      int _next_arc;
419 421

	
420 422
    public:
421 423

	
422 424
      /// Constructor
423 425
      CandidateListPivotRule(NetworkSimplex &ns) :
424 426
        _source(ns._source), _target(ns._target),
425 427
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
426 428
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
427 429
        _next_arc(0)
428 430
      {
429 431
        // The main parameters of the pivot rule
430 432
        const double LIST_LENGTH_FACTOR = 0.25;
431 433
        const int MIN_LIST_LENGTH = 10;
432 434
        const double MINOR_LIMIT_FACTOR = 0.1;
433 435
        const int MIN_MINOR_LIMIT = 3;
434 436

	
435 437
        _list_length = std::max( int(LIST_LENGTH_FACTOR *
436 438
                                     std::sqrt(double(_search_arc_num))),
437 439
                                 MIN_LIST_LENGTH );
438 440
        _minor_limit = std::max( int(MINOR_LIMIT_FACTOR * _list_length),
439 441
                                 MIN_MINOR_LIMIT );
440 442
        _curr_length = _minor_count = 0;
441 443
        _candidates.resize(_list_length);
442 444
      }
443 445

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

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

	
500 502
    }; //class CandidateListPivotRule
501 503

	
502 504

	
503 505
    // Implementation of the Altering Candidate List pivot rule
504 506
    class AlteringListPivotRule
505 507
    {
506 508
    private:
507 509

	
508 510
      // References to the NetworkSimplex class
509 511
      const IntVector  &_source;
510 512
      const IntVector  &_target;
511 513
      const CostVector &_cost;
512
      const IntVector  &_state;
514
      const CharVector &_state;
513 515
      const CostVector &_pi;
514 516
      int &_in_arc;
515 517
      int _search_arc_num;
516 518

	
517 519
      // Pivot rule data
518 520
      int _block_size, _head_length, _curr_length;
519 521
      int _next_arc;
520 522
      IntVector _candidates;
521 523
      CostVector _cand_cost;
522 524

	
523 525
      // Functor class to compare arcs during sort of the candidate list
524 526
      class SortFunc
525 527
      {
526 528
      private:
527 529
        const CostVector &_map;
528 530
      public:
529 531
        SortFunc(const CostVector &map) : _map(map) {}
530 532
        bool operator()(int left, int right) {
531 533
          return _map[left] > _map[right];
532 534
        }
533 535
      };
534 536

	
535 537
      SortFunc _sort_func;
536 538

	
537 539
    public:
538 540

	
539 541
      // Constructor
540 542
      AlteringListPivotRule(NetworkSimplex &ns) :
541 543
        _source(ns._source), _target(ns._target),
542 544
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
543 545
        _in_arc(ns.in_arc), _search_arc_num(ns._search_arc_num),
544 546
        _next_arc(0), _cand_cost(ns._search_arc_num), _sort_func(_cand_cost)
545 547
      {
546 548
        // The main parameters of the pivot rule
547 549
        const double BLOCK_SIZE_FACTOR = 1.0;
548 550
        const int MIN_BLOCK_SIZE = 10;
549 551
        const double HEAD_LENGTH_FACTOR = 0.1;
550 552
        const int MIN_HEAD_LENGTH = 3;
551 553

	
552 554
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
553 555
                                    std::sqrt(double(_search_arc_num))),
554 556
                                MIN_BLOCK_SIZE );
555 557
        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
556 558
                                 MIN_HEAD_LENGTH );
557 559
        _candidates.resize(_head_length + _block_size);
558 560
        _curr_length = 0;
559 561
      }
560 562

	
561 563
      // Find next entering arc
562 564
      bool findEnteringArc() {
563 565
        // Check the current candidate list
564 566
        int e;
565 567
        for (int i = 0; i < _curr_length; ++i) {
566 568
          e = _candidates[i];
567 569
          _cand_cost[e] = _state[e] *
568 570
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
569 571
          if (_cand_cost[e] >= 0) {
570 572
            _candidates[i--] = _candidates[--_curr_length];
571 573
          }
572 574
        }
573 575

	
574 576
        // Extend the list
575 577
        int cnt = _block_size;
576 578
        int limit = _head_length;
577 579

	
578 580
        for (e = _next_arc; e < _search_arc_num; ++e) {
579 581
          _cand_cost[e] = _state[e] *
580 582
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
581 583
          if (_cand_cost[e] < 0) {
582 584
            _candidates[_curr_length++] = e;
583 585
          }
584 586
          if (--cnt == 0) {
585 587
            if (_curr_length > limit) goto search_end;
586 588
            limit = 0;
587 589
            cnt = _block_size;
588 590
          }
589 591
        }
590 592
        for (e = 0; e < _next_arc; ++e) {
591 593
          _cand_cost[e] = _state[e] *
592 594
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
593 595
          if (_cand_cost[e] < 0) {
594 596
            _candidates[_curr_length++] = e;
595 597
          }
596 598
          if (--cnt == 0) {
597 599
            if (_curr_length > limit) goto search_end;
598 600
            limit = 0;
599 601
            cnt = _block_size;
600 602
          }
601 603
        }
602 604
        if (_curr_length == 0) return false;
603 605
        
604 606
      search_end:
605 607

	
606 608
        // Make heap of the candidate list (approximating a partial sort)
607 609
        make_heap( _candidates.begin(), _candidates.begin() + _curr_length,
608 610
                   _sort_func );
609 611

	
610 612
        // Pop the first element of the heap
611 613
        _in_arc = _candidates[0];
612 614
        _next_arc = e;
613 615
        pop_heap( _candidates.begin(), _candidates.begin() + _curr_length,
614 616
                  _sort_func );
615 617
        _curr_length = std::min(_head_length, _curr_length - 1);
616 618
        return true;
617 619
      }
618 620

	
619 621
    }; //class AlteringListPivotRule
620 622

	
621 623
  public:
622 624

	
623 625
    /// \brief Constructor.
624 626
    ///
625 627
    /// The constructor of the class.
626 628
    ///
627 629
    /// \param graph The digraph the algorithm runs on.
628 630
    /// \param arc_mixing Indicate if the arcs have to be stored in a
629 631
    /// mixed order in the internal data structure. 
630 632
    /// In special cases, it could lead to better overall performance,
631 633
    /// but it is usually slower. Therefore it is disabled by default.
632 634
    NetworkSimplex(const GR& graph, bool arc_mixing = false) :
633 635
      _graph(graph), _node_id(graph), _arc_id(graph),
636
      MAX(std::numeric_limits<Value>::max()),
634 637
      INF(std::numeric_limits<Value>::has_infinity ?
635
          std::numeric_limits<Value>::infinity() :
636
          std::numeric_limits<Value>::max())
638
          std::numeric_limits<Value>::infinity() : MAX)
637 639
    {
638 640
      // Check the value types
639 641
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
640 642
        "The flow type of NetworkSimplex must be signed");
641 643
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
642 644
        "The cost type of NetworkSimplex must be signed");
643 645
        
644 646
      // Resize vectors
645 647
      _node_num = countNodes(_graph);
646 648
      _arc_num = countArcs(_graph);
647 649
      int all_node_num = _node_num + 1;
648 650
      int max_arc_num = _arc_num + 2 * _node_num;
649 651

	
650 652
      _source.resize(max_arc_num);
651 653
      _target.resize(max_arc_num);
652 654

	
653 655
      _lower.resize(_arc_num);
654 656
      _upper.resize(_arc_num);
655 657
      _cap.resize(max_arc_num);
656 658
      _cost.resize(max_arc_num);
657 659
      _supply.resize(all_node_num);
658 660
      _flow.resize(max_arc_num);
659 661
      _pi.resize(all_node_num);
660 662

	
661 663
      _parent.resize(all_node_num);
662 664
      _pred.resize(all_node_num);
663 665
      _forward.resize(all_node_num);
664 666
      _thread.resize(all_node_num);
665 667
      _rev_thread.resize(all_node_num);
666 668
      _succ_num.resize(all_node_num);
667 669
      _last_succ.resize(all_node_num);
668 670
      _state.resize(max_arc_num);
669 671

	
670 672
      // Copy the graph
671 673
      int i = 0;
672 674
      for (NodeIt n(_graph); n != INVALID; ++n, ++i) {
673 675
        _node_id[n] = i;
674 676
      }
675 677
      if (arc_mixing) {
676 678
        // Store the arcs in a mixed order
677 679
        int k = std::max(int(std::sqrt(double(_arc_num))), 10);
678 680
        int i = 0, j = 0;
679 681
        for (ArcIt a(_graph); a != INVALID; ++a) {
680 682
          _arc_id[a] = i;
681 683
          _source[i] = _node_id[_graph.source(a)];
682 684
          _target[i] = _node_id[_graph.target(a)];
683 685
          if ((i += k) >= _arc_num) i = ++j;
684 686
        }
685 687
      } else {
686 688
        // Store the arcs in the original order
687 689
        int i = 0;
688 690
        for (ArcIt a(_graph); a != INVALID; ++a, ++i) {
689 691
          _arc_id[a] = i;
690 692
          _source[i] = _node_id[_graph.source(a)];
691 693
          _target[i] = _node_id[_graph.target(a)];
692 694
        }
693 695
      }
694 696
      
695 697
      // Reset parameters
696 698
      reset();
697 699
    }
698 700

	
699 701
    /// \name Parameters
700 702
    /// The parameters of the algorithm can be specified using these
701 703
    /// functions.
702 704

	
703 705
    /// @{
704 706

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

	
725 727
    /// \brief Set the upper bounds (capacities) on the arcs.
726 728
    ///
727 729
    /// This function sets the upper bounds (capacities) on the arcs.
728 730
    /// If it is not used before calling \ref run(), the upper bounds
729 731
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
730 732
    /// unbounded from above on each arc).
731 733
    ///
732 734
    /// \param map An arc map storing the upper bounds.
733 735
    /// Its \c Value type must be convertible to the \c Value type
734 736
    /// of the algorithm.
735 737
    ///
736 738
    /// \return <tt>(*this)</tt>
737 739
    template<typename UpperMap>
738 740
    NetworkSimplex& upperMap(const UpperMap& map) {
739 741
      for (ArcIt a(_graph); a != INVALID; ++a) {
740 742
        _upper[_arc_id[a]] = map[a];
741 743
      }
742 744
      return *this;
743 745
    }
744 746

	
745 747
    /// \brief Set the costs of the arcs.
746 748
    ///
747 749
    /// This function sets the costs of the arcs.
748 750
    /// If it is not used before calling \ref run(), the costs
749 751
    /// will be set to \c 1 on all arcs.
750 752
    ///
751 753
    /// \param map An arc map storing the costs.
752 754
    /// Its \c Value type must be convertible to the \c Cost type
753 755
    /// of the algorithm.
754 756
    ///
755 757
    /// \return <tt>(*this)</tt>
756 758
    template<typename CostMap>
757 759
    NetworkSimplex& costMap(const CostMap& map) {
758 760
      for (ArcIt a(_graph); a != INVALID; ++a) {
759 761
        _cost[_arc_id[a]] = map[a];
760 762
      }
761 763
      return *this;
762 764
    }
763 765

	
764 766
    /// \brief Set the supply values of the nodes.
765 767
    ///
766 768
    /// This function sets the supply values of the nodes.
767 769
    /// If neither this function nor \ref stSupply() is used before
768 770
    /// calling \ref run(), the supply of each node will be set to zero.
769 771
    ///
770 772
    /// \param map A node map storing the supply values.
771 773
    /// Its \c Value type must be convertible to the \c Value type
772 774
    /// of the algorithm.
773 775
    ///
774 776
    /// \return <tt>(*this)</tt>
775 777
    template<typename SupplyMap>
776 778
    NetworkSimplex& supplyMap(const SupplyMap& map) {
777 779
      for (NodeIt n(_graph); n != INVALID; ++n) {
778 780
        _supply[_node_id[n]] = map[n];
779 781
      }
780 782
      return *this;
781 783
    }
782 784

	
783 785
    /// \brief Set single source and target nodes and a supply value.
784 786
    ///
785 787
    /// This function sets a single source node and a single target node
786 788
    /// and the required flow value.
787 789
    /// If neither this function nor \ref supplyMap() is used before
788 790
    /// calling \ref run(), the supply of each node will be set to zero.
789 791
    ///
790 792
    /// Using this function has the same effect as using \ref supplyMap()
791 793
    /// with such a map in which \c k is assigned to \c s, \c -k is
792 794
    /// assigned to \c t and all other nodes have zero supply value.
793 795
    ///
794 796
    /// \param s The source node.
795 797
    /// \param t The target node.
796 798
    /// \param k The required amount of flow from node \c s to node \c t
797 799
    /// (i.e. the supply of \c s and the demand of \c t).
798 800
    ///
799 801
    /// \return <tt>(*this)</tt>
800 802
    NetworkSimplex& stSupply(const Node& s, const Node& t, Value k) {
801 803
      for (int i = 0; i != _node_num; ++i) {
802 804
        _supply[i] = 0;
803 805
      }
804 806
      _supply[_node_id[s]] =  k;
805 807
      _supply[_node_id[t]] = -k;
806 808
      return *this;
807 809
    }
808 810
    
809 811
    /// \brief Set the type of the supply constraints.
810 812
    ///
811 813
    /// This function sets the type of the supply/demand constraints.
812 814
    /// If it is not used before calling \ref run(), the \ref GEQ supply
813 815
    /// type will be used.
814 816
    ///
815 817
    /// For more information, see \ref SupplyType.
816 818
    ///
817 819
    /// \return <tt>(*this)</tt>
818 820
    NetworkSimplex& supplyType(SupplyType supply_type) {
819 821
      _stype = supply_type;
820 822
      return *this;
821 823
    }
822 824

	
823 825
    /// @}
824 826

	
825 827
    /// \name Execution Control
826 828
    /// The algorithm can be executed using \ref run().
827 829

	
828 830
    /// @{
... ...
@@ -831,655 +833,655 @@
831 833
    ///
832 834
    /// This function runs the algorithm.
833 835
    /// The paramters can be specified using functions \ref lowerMap(),
834 836
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(), 
835 837
    /// \ref supplyType().
836 838
    /// For example,
837 839
    /// \code
838 840
    ///   NetworkSimplex<ListDigraph> ns(graph);
839 841
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
840 842
    ///     .supplyMap(sup).run();
841 843
    /// \endcode
842 844
    ///
843 845
    /// This function can be called more than once. All the parameters
844 846
    /// that have been given are kept for the next call, unless
845 847
    /// \ref reset() is called, thus only the modified parameters
846 848
    /// have to be set again. See \ref reset() for examples.
847 849
    /// However, the underlying digraph must not be modified after this
848 850
    /// class have been constructed, since it copies and extends the graph.
849 851
    ///
850 852
    /// \param pivot_rule The pivot rule that will be used during the
851 853
    /// algorithm. For more information, see \ref PivotRule.
852 854
    ///
853 855
    /// \return \c INFEASIBLE if no feasible flow exists,
854 856
    /// \n \c OPTIMAL if the problem has optimal solution
855 857
    /// (i.e. it is feasible and bounded), and the algorithm has found
856 858
    /// optimal flow and node potentials (primal and dual solutions),
857 859
    /// \n \c UNBOUNDED if the objective function of the problem is
858 860
    /// unbounded, i.e. there is a directed cycle having negative total
859 861
    /// cost and infinite upper bound.
860 862
    ///
861 863
    /// \see ProblemType, PivotRule
862 864
    ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
863 865
      if (!init()) return INFEASIBLE;
864 866
      return start(pivot_rule);
865 867
    }
866 868

	
867 869
    /// \brief Reset all the parameters that have been given before.
868 870
    ///
869 871
    /// This function resets all the paramaters that have been given
870 872
    /// before using functions \ref lowerMap(), \ref upperMap(),
871 873
    /// \ref costMap(), \ref supplyMap(), \ref stSupply(), \ref supplyType().
872 874
    ///
873 875
    /// It is useful for multiple run() calls. If this function is not
874 876
    /// used, all the parameters given before are kept for the next
875 877
    /// \ref run() call.
876 878
    /// However, the underlying digraph must not be modified after this
877 879
    /// class have been constructed, since it copies and extends the graph.
878 880
    ///
879 881
    /// For example,
880 882
    /// \code
881 883
    ///   NetworkSimplex<ListDigraph> ns(graph);
882 884
    ///
883 885
    ///   // First run
884 886
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
885 887
    ///     .supplyMap(sup).run();
886 888
    ///
887 889
    ///   // Run again with modified cost map (reset() is not called,
888 890
    ///   // so only the cost map have to be set again)
889 891
    ///   cost[e] += 100;
890 892
    ///   ns.costMap(cost).run();
891 893
    ///
892 894
    ///   // Run again from scratch using reset()
893 895
    ///   // (the lower bounds will be set to zero on all arcs)
894 896
    ///   ns.reset();
895 897
    ///   ns.upperMap(capacity).costMap(cost)
896 898
    ///     .supplyMap(sup).run();
897 899
    /// \endcode
898 900
    ///
899 901
    /// \return <tt>(*this)</tt>
900 902
    NetworkSimplex& reset() {
901 903
      for (int i = 0; i != _node_num; ++i) {
902 904
        _supply[i] = 0;
903 905
      }
904 906
      for (int i = 0; i != _arc_num; ++i) {
905 907
        _lower[i] = 0;
906 908
        _upper[i] = INF;
907 909
        _cost[i] = 1;
908 910
      }
909 911
      _have_lower = false;
910 912
      _stype = GEQ;
911 913
      return *this;
912 914
    }
913 915

	
914 916
    /// @}
915 917

	
916 918
    /// \name Query Functions
917 919
    /// The results of the algorithm can be obtained using these
918 920
    /// functions.\n
919 921
    /// The \ref run() function must be called before using them.
920 922

	
921 923
    /// @{
922 924

	
923 925
    /// \brief Return the total cost of the found flow.
924 926
    ///
925 927
    /// This function returns the total cost of the found flow.
926 928
    /// Its complexity is O(e).
927 929
    ///
928 930
    /// \note The return type of the function can be specified as a
929 931
    /// template parameter. For example,
930 932
    /// \code
931 933
    ///   ns.totalCost<double>();
932 934
    /// \endcode
933 935
    /// It is useful if the total cost cannot be stored in the \c Cost
934 936
    /// type of the algorithm, which is the default return type of the
935 937
    /// function.
936 938
    ///
937 939
    /// \pre \ref run() must be called before using this function.
938 940
    template <typename Number>
939 941
    Number totalCost() const {
940 942
      Number c = 0;
941 943
      for (ArcIt a(_graph); a != INVALID; ++a) {
942 944
        int i = _arc_id[a];
943 945
        c += Number(_flow[i]) * Number(_cost[i]);
944 946
      }
945 947
      return c;
946 948
    }
947 949

	
948 950
#ifndef DOXYGEN
949 951
    Cost totalCost() const {
950 952
      return totalCost<Cost>();
951 953
    }
952 954
#endif
953 955

	
954 956
    /// \brief Return the flow on the given arc.
955 957
    ///
956 958
    /// This function returns the flow on the given arc.
957 959
    ///
958 960
    /// \pre \ref run() must be called before using this function.
959 961
    Value flow(const Arc& a) const {
960 962
      return _flow[_arc_id[a]];
961 963
    }
962 964

	
963 965
    /// \brief Return the flow map (the primal solution).
964 966
    ///
965 967
    /// This function copies the flow value on each arc into the given
966 968
    /// map. The \c Value type of the algorithm must be convertible to
967 969
    /// the \c Value type of the map.
968 970
    ///
969 971
    /// \pre \ref run() must be called before using this function.
970 972
    template <typename FlowMap>
971 973
    void flowMap(FlowMap &map) const {
972 974
      for (ArcIt a(_graph); a != INVALID; ++a) {
973 975
        map.set(a, _flow[_arc_id[a]]);
974 976
      }
975 977
    }
976 978

	
977 979
    /// \brief Return the potential (dual value) of the given node.
978 980
    ///
979 981
    /// This function returns the potential (dual value) of the
980 982
    /// given node.
981 983
    ///
982 984
    /// \pre \ref run() must be called before using this function.
983 985
    Cost potential(const Node& n) const {
984 986
      return _pi[_node_id[n]];
985 987
    }
986 988

	
987 989
    /// \brief Return the potential map (the dual solution).
988 990
    ///
989 991
    /// This function copies the potential (dual value) of each node
990 992
    /// into the given map.
991 993
    /// The \c Cost type of the algorithm must be convertible to the
992 994
    /// \c Value type of the map.
993 995
    ///
994 996
    /// \pre \ref run() must be called before using this function.
995 997
    template <typename PotentialMap>
996 998
    void potentialMap(PotentialMap &map) const {
997 999
      for (NodeIt n(_graph); n != INVALID; ++n) {
998 1000
        map.set(n, _pi[_node_id[n]]);
999 1001
      }
1000 1002
    }
1001 1003

	
1002 1004
    /// @}
1003 1005

	
1004 1006
  private:
1005 1007

	
1006 1008
    // Initialize internal data structures
1007 1009
    bool init() {
1008 1010
      if (_node_num == 0) return false;
1009 1011

	
1010 1012
      // Check the sum of supply values
1011 1013
      _sum_supply = 0;
1012 1014
      for (int i = 0; i != _node_num; ++i) {
1013 1015
        _sum_supply += _supply[i];
1014 1016
      }
1015 1017
      if ( !((_stype == GEQ && _sum_supply <= 0) ||
1016 1018
             (_stype == LEQ && _sum_supply >= 0)) ) return false;
1017 1019

	
1018 1020
      // Remove non-zero lower bounds
1019 1021
      if (_have_lower) {
1020 1022
        for (int i = 0; i != _arc_num; ++i) {
1021 1023
          Value c = _lower[i];
1022 1024
          if (c >= 0) {
1023
            _cap[i] = _upper[i] < INF ? _upper[i] - c : INF;
1025
            _cap[i] = _upper[i] < MAX ? _upper[i] - c : INF;
1024 1026
          } else {
1025
            _cap[i] = _upper[i] < INF + c ? _upper[i] - c : INF;
1027
            _cap[i] = _upper[i] < MAX + c ? _upper[i] - c : INF;
1026 1028
          }
1027 1029
          _supply[_source[i]] -= c;
1028 1030
          _supply[_target[i]] += c;
1029 1031
        }
1030 1032
      } else {
1031 1033
        for (int i = 0; i != _arc_num; ++i) {
1032 1034
          _cap[i] = _upper[i];
1033 1035
        }
1034 1036
      }
1035 1037

	
1036 1038
      // Initialize artifical cost
1037 1039
      Cost ART_COST;
1038 1040
      if (std::numeric_limits<Cost>::is_exact) {
1039 1041
        ART_COST = std::numeric_limits<Cost>::max() / 2 + 1;
1040 1042
      } else {
1041 1043
        ART_COST = std::numeric_limits<Cost>::min();
1042 1044
        for (int i = 0; i != _arc_num; ++i) {
1043 1045
          if (_cost[i] > ART_COST) ART_COST = _cost[i];
1044 1046
        }
1045 1047
        ART_COST = (ART_COST + 1) * _node_num;
1046 1048
      }
1047 1049

	
1048 1050
      // Initialize arc maps
1049 1051
      for (int i = 0; i != _arc_num; ++i) {
1050 1052
        _flow[i] = 0;
1051 1053
        _state[i] = STATE_LOWER;
1052 1054
      }
1053 1055
      
1054 1056
      // Set data for the artificial root node
1055 1057
      _root = _node_num;
1056 1058
      _parent[_root] = -1;
1057 1059
      _pred[_root] = -1;
1058 1060
      _thread[_root] = 0;
1059 1061
      _rev_thread[0] = _root;
1060 1062
      _succ_num[_root] = _node_num + 1;
1061 1063
      _last_succ[_root] = _root - 1;
1062 1064
      _supply[_root] = -_sum_supply;
1063 1065
      _pi[_root] = 0;
1064 1066

	
1065 1067
      // Add artificial arcs and initialize the spanning tree data structure
1066 1068
      if (_sum_supply == 0) {
1067 1069
        // EQ supply constraints
1068 1070
        _search_arc_num = _arc_num;
1069 1071
        _all_arc_num = _arc_num + _node_num;
1070 1072
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1071 1073
          _parent[u] = _root;
1072 1074
          _pred[u] = e;
1073 1075
          _thread[u] = u + 1;
1074 1076
          _rev_thread[u + 1] = u;
1075 1077
          _succ_num[u] = 1;
1076 1078
          _last_succ[u] = u;
1077 1079
          _cap[e] = INF;
1078 1080
          _state[e] = STATE_TREE;
1079 1081
          if (_supply[u] >= 0) {
1080 1082
            _forward[u] = true;
1081 1083
            _pi[u] = 0;
1082 1084
            _source[e] = u;
1083 1085
            _target[e] = _root;
1084 1086
            _flow[e] = _supply[u];
1085 1087
            _cost[e] = 0;
1086 1088
          } else {
1087 1089
            _forward[u] = false;
1088 1090
            _pi[u] = ART_COST;
1089 1091
            _source[e] = _root;
1090 1092
            _target[e] = u;
1091 1093
            _flow[e] = -_supply[u];
1092 1094
            _cost[e] = ART_COST;
1093 1095
          }
1094 1096
        }
1095 1097
      }
1096 1098
      else if (_sum_supply > 0) {
1097 1099
        // LEQ supply constraints
1098 1100
        _search_arc_num = _arc_num + _node_num;
1099 1101
        int f = _arc_num + _node_num;
1100 1102
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1101 1103
          _parent[u] = _root;
1102 1104
          _thread[u] = u + 1;
1103 1105
          _rev_thread[u + 1] = u;
1104 1106
          _succ_num[u] = 1;
1105 1107
          _last_succ[u] = u;
1106 1108
          if (_supply[u] >= 0) {
1107 1109
            _forward[u] = true;
1108 1110
            _pi[u] = 0;
1109 1111
            _pred[u] = e;
1110 1112
            _source[e] = u;
1111 1113
            _target[e] = _root;
1112 1114
            _cap[e] = INF;
1113 1115
            _flow[e] = _supply[u];
1114 1116
            _cost[e] = 0;
1115 1117
            _state[e] = STATE_TREE;
1116 1118
          } else {
1117 1119
            _forward[u] = false;
1118 1120
            _pi[u] = ART_COST;
1119 1121
            _pred[u] = f;
1120 1122
            _source[f] = _root;
1121 1123
            _target[f] = u;
1122 1124
            _cap[f] = INF;
1123 1125
            _flow[f] = -_supply[u];
1124 1126
            _cost[f] = ART_COST;
1125 1127
            _state[f] = STATE_TREE;
1126 1128
            _source[e] = u;
1127 1129
            _target[e] = _root;
1128 1130
            _cap[e] = INF;
1129 1131
            _flow[e] = 0;
1130 1132
            _cost[e] = 0;
1131 1133
            _state[e] = STATE_LOWER;
1132 1134
            ++f;
1133 1135
          }
1134 1136
        }
1135 1137
        _all_arc_num = f;
1136 1138
      }
1137 1139
      else {
1138 1140
        // GEQ supply constraints
1139 1141
        _search_arc_num = _arc_num + _node_num;
1140 1142
        int f = _arc_num + _node_num;
1141 1143
        for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1142 1144
          _parent[u] = _root;
1143 1145
          _thread[u] = u + 1;
1144 1146
          _rev_thread[u + 1] = u;
1145 1147
          _succ_num[u] = 1;
1146 1148
          _last_succ[u] = u;
1147 1149
          if (_supply[u] <= 0) {
1148 1150
            _forward[u] = false;
1149 1151
            _pi[u] = 0;
1150 1152
            _pred[u] = e;
1151 1153
            _source[e] = _root;
1152 1154
            _target[e] = u;
1153 1155
            _cap[e] = INF;
1154 1156
            _flow[e] = -_supply[u];
1155 1157
            _cost[e] = 0;
1156 1158
            _state[e] = STATE_TREE;
1157 1159
          } else {
1158 1160
            _forward[u] = true;
1159 1161
            _pi[u] = -ART_COST;
1160 1162
            _pred[u] = f;
1161 1163
            _source[f] = u;
1162 1164
            _target[f] = _root;
1163 1165
            _cap[f] = INF;
1164 1166
            _flow[f] = _supply[u];
1165 1167
            _state[f] = STATE_TREE;
1166 1168
            _cost[f] = ART_COST;
1167 1169
            _source[e] = _root;
1168 1170
            _target[e] = u;
1169 1171
            _cap[e] = INF;
1170 1172
            _flow[e] = 0;
1171 1173
            _cost[e] = 0;
1172 1174
            _state[e] = STATE_LOWER;
1173 1175
            ++f;
1174 1176
          }
1175 1177
        }
1176 1178
        _all_arc_num = f;
1177 1179
      }
1178 1180

	
1179 1181
      return true;
1180 1182
    }
1181 1183

	
1182 1184
    // Find the join node
1183 1185
    void findJoinNode() {
1184 1186
      int u = _source[in_arc];
1185 1187
      int v = _target[in_arc];
1186 1188
      while (u != v) {
1187 1189
        if (_succ_num[u] < _succ_num[v]) {
1188 1190
          u = _parent[u];
1189 1191
        } else {
1190 1192
          v = _parent[v];
1191 1193
        }
1192 1194
      }
1193 1195
      join = u;
1194 1196
    }
1195 1197

	
1196 1198
    // Find the leaving arc of the cycle and returns true if the
1197 1199
    // leaving arc is not the same as the entering arc
1198 1200
    bool findLeavingArc() {
1199 1201
      // Initialize first and second nodes according to the direction
1200 1202
      // of the cycle
1201 1203
      if (_state[in_arc] == STATE_LOWER) {
1202 1204
        first  = _source[in_arc];
1203 1205
        second = _target[in_arc];
1204 1206
      } else {
1205 1207
        first  = _target[in_arc];
1206 1208
        second = _source[in_arc];
1207 1209
      }
1208 1210
      delta = _cap[in_arc];
1209 1211
      int result = 0;
1210 1212
      Value d;
1211 1213
      int e;
1212 1214

	
1213 1215
      // Search the cycle along the path form the first node to the root
1214 1216
      for (int u = first; u != join; u = _parent[u]) {
1215 1217
        e = _pred[u];
1216 1218
        d = _forward[u] ?
1217
          _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1219
          _flow[e] : (_cap[e] >= MAX ? INF : _cap[e] - _flow[e]);
1218 1220
        if (d < delta) {
1219 1221
          delta = d;
1220 1222
          u_out = u;
1221 1223
          result = 1;
1222 1224
        }
1223 1225
      }
1224 1226
      // Search the cycle along the path form the second node to the root
1225 1227
      for (int u = second; u != join; u = _parent[u]) {
1226 1228
        e = _pred[u];
1227 1229
        d = _forward[u] ? 
1228
          (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1230
          (_cap[e] >= MAX ? INF : _cap[e] - _flow[e]) : _flow[e];
1229 1231
        if (d <= delta) {
1230 1232
          delta = d;
1231 1233
          u_out = u;
1232 1234
          result = 2;
1233 1235
        }
1234 1236
      }
1235 1237

	
1236 1238
      if (result == 1) {
1237 1239
        u_in = first;
1238 1240
        v_in = second;
1239 1241
      } else {
1240 1242
        u_in = second;
1241 1243
        v_in = first;
1242 1244
      }
1243 1245
      return result != 0;
1244 1246
    }
1245 1247

	
1246 1248
    // Change _flow and _state vectors
1247 1249
    void changeFlow(bool change) {
1248 1250
      // Augment along the cycle
1249 1251
      if (delta > 0) {
1250 1252
        Value val = _state[in_arc] * delta;
1251 1253
        _flow[in_arc] += val;
1252 1254
        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1253 1255
          _flow[_pred[u]] += _forward[u] ? -val : val;
1254 1256
        }
1255 1257
        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1256 1258
          _flow[_pred[u]] += _forward[u] ? val : -val;
1257 1259
        }
1258 1260
      }
1259 1261
      // Update the state of the entering and leaving arcs
1260 1262
      if (change) {
1261 1263
        _state[in_arc] = STATE_TREE;
1262 1264
        _state[_pred[u_out]] =
1263 1265
          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1264 1266
      } else {
1265 1267
        _state[in_arc] = -_state[in_arc];
1266 1268
      }
1267 1269
    }
1268 1270

	
1269 1271
    // Update the tree structure
1270 1272
    void updateTreeStructure() {
1271 1273
      int u, w;
1272 1274
      int old_rev_thread = _rev_thread[u_out];
1273 1275
      int old_succ_num = _succ_num[u_out];
1274 1276
      int old_last_succ = _last_succ[u_out];
1275 1277
      v_out = _parent[u_out];
1276 1278

	
1277 1279
      u = _last_succ[u_in];  // the last successor of u_in
1278 1280
      right = _thread[u];    // the node after it
1279 1281

	
1280 1282
      // Handle the case when old_rev_thread equals to v_in
1281 1283
      // (it also means that join and v_out coincide)
1282 1284
      if (old_rev_thread == v_in) {
1283 1285
        last = _thread[_last_succ[u_out]];
1284 1286
      } else {
1285 1287
        last = _thread[v_in];
1286 1288
      }
1287 1289

	
1288 1290
      // Update _thread and _parent along the stem nodes (i.e. the nodes
1289 1291
      // between u_in and u_out, whose parent have to be changed)
1290 1292
      _thread[v_in] = stem = u_in;
1291 1293
      _dirty_revs.clear();
1292 1294
      _dirty_revs.push_back(v_in);
1293 1295
      par_stem = v_in;
1294 1296
      while (stem != u_out) {
1295 1297
        // Insert the next stem node into the thread list
1296 1298
        new_stem = _parent[stem];
1297 1299
        _thread[u] = new_stem;
1298 1300
        _dirty_revs.push_back(u);
1299 1301

	
1300 1302
        // Remove the subtree of stem from the thread list
1301 1303
        w = _rev_thread[stem];
1302 1304
        _thread[w] = right;
1303 1305
        _rev_thread[right] = w;
1304 1306

	
1305 1307
        // Change the parent node and shift stem nodes
1306 1308
        _parent[stem] = par_stem;
1307 1309
        par_stem = stem;
1308 1310
        stem = new_stem;
1309 1311

	
1310 1312
        // Update u and right
1311 1313
        u = _last_succ[stem] == _last_succ[par_stem] ?
1312 1314
          _rev_thread[par_stem] : _last_succ[stem];
1313 1315
        right = _thread[u];
1314 1316
      }
1315 1317
      _parent[u_out] = par_stem;
1316 1318
      _thread[u] = last;
1317 1319
      _rev_thread[last] = u;
1318 1320
      _last_succ[u_out] = u;
1319 1321

	
1320 1322
      // Remove the subtree of u_out from the thread list except for
1321 1323
      // the case when old_rev_thread equals to v_in
1322 1324
      // (it also means that join and v_out coincide)
1323 1325
      if (old_rev_thread != v_in) {
1324 1326
        _thread[old_rev_thread] = right;
1325 1327
        _rev_thread[right] = old_rev_thread;
1326 1328
      }
1327 1329

	
1328 1330
      // Update _rev_thread using the new _thread values
1329 1331
      for (int i = 0; i < int(_dirty_revs.size()); ++i) {
1330 1332
        u = _dirty_revs[i];
1331 1333
        _rev_thread[_thread[u]] = u;
1332 1334
      }
1333 1335

	
1334 1336
      // Update _pred, _forward, _last_succ and _succ_num for the
1335 1337
      // stem nodes from u_out to u_in
1336 1338
      int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1337 1339
      u = u_out;
1338 1340
      while (u != u_in) {
1339 1341
        w = _parent[u];
1340 1342
        _pred[u] = _pred[w];
1341 1343
        _forward[u] = !_forward[w];
1342 1344
        tmp_sc += _succ_num[u] - _succ_num[w];
1343 1345
        _succ_num[u] = tmp_sc;
1344 1346
        _last_succ[w] = tmp_ls;
1345 1347
        u = w;
1346 1348
      }
1347 1349
      _pred[u_in] = in_arc;
1348 1350
      _forward[u_in] = (u_in == _source[in_arc]);
1349 1351
      _succ_num[u_in] = old_succ_num;
1350 1352

	
1351 1353
      // Set limits for updating _last_succ form v_in and v_out
1352 1354
      // towards the root
1353 1355
      int up_limit_in = -1;
1354 1356
      int up_limit_out = -1;
1355 1357
      if (_last_succ[join] == v_in) {
1356 1358
        up_limit_out = join;
1357 1359
      } else {
1358 1360
        up_limit_in = join;
1359 1361
      }
1360 1362

	
1361 1363
      // Update _last_succ from v_in towards the root
1362 1364
      for (u = v_in; u != up_limit_in && _last_succ[u] == v_in;
1363 1365
           u = _parent[u]) {
1364 1366
        _last_succ[u] = _last_succ[u_out];
1365 1367
      }
1366 1368
      // Update _last_succ from v_out towards the root
1367 1369
      if (join != old_rev_thread && v_in != old_rev_thread) {
1368 1370
        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1369 1371
             u = _parent[u]) {
1370 1372
          _last_succ[u] = old_rev_thread;
1371 1373
        }
1372 1374
      } else {
1373 1375
        for (u = v_out; u != up_limit_out && _last_succ[u] == old_last_succ;
1374 1376
             u = _parent[u]) {
1375 1377
          _last_succ[u] = _last_succ[u_out];
1376 1378
        }
1377 1379
      }
1378 1380

	
1379 1381
      // Update _succ_num from v_in to join
1380 1382
      for (u = v_in; u != join; u = _parent[u]) {
1381 1383
        _succ_num[u] += old_succ_num;
1382 1384
      }
1383 1385
      // Update _succ_num from v_out to join
1384 1386
      for (u = v_out; u != join; u = _parent[u]) {
1385 1387
        _succ_num[u] -= old_succ_num;
1386 1388
      }
1387 1389
    }
1388 1390

	
1389 1391
    // Update potentials
1390 1392
    void updatePotential() {
1391 1393
      Cost sigma = _forward[u_in] ?
1392 1394
        _pi[v_in] - _pi[u_in] - _cost[_pred[u_in]] :
1393 1395
        _pi[v_in] - _pi[u_in] + _cost[_pred[u_in]];
1394 1396
      // Update potentials in the subtree, which has been moved
1395 1397
      int end = _thread[_last_succ[u_in]];
1396 1398
      for (int u = u_in; u != end; u = _thread[u]) {
1397 1399
        _pi[u] += sigma;
1398 1400
      }
1399 1401
    }
1400 1402

	
1401 1403
    // Execute the algorithm
1402 1404
    ProblemType start(PivotRule pivot_rule) {
1403 1405
      // Select the pivot rule implementation
1404 1406
      switch (pivot_rule) {
1405 1407
        case FIRST_ELIGIBLE:
1406 1408
          return start<FirstEligiblePivotRule>();
1407 1409
        case BEST_ELIGIBLE:
1408 1410
          return start<BestEligiblePivotRule>();
1409 1411
        case BLOCK_SEARCH:
1410 1412
          return start<BlockSearchPivotRule>();
1411 1413
        case CANDIDATE_LIST:
1412 1414
          return start<CandidateListPivotRule>();
1413 1415
        case ALTERING_LIST:
1414 1416
          return start<AlteringListPivotRule>();
1415 1417
      }
1416 1418
      return INFEASIBLE; // avoid warning
1417 1419
    }
1418 1420

	
1419 1421
    template <typename PivotRuleImpl>
1420 1422
    ProblemType start() {
1421 1423
      PivotRuleImpl pivot(*this);
1422 1424

	
1423 1425
      // Execute the Network Simplex algorithm
1424 1426
      while (pivot.findEnteringArc()) {
1425 1427
        findJoinNode();
1426 1428
        bool change = findLeavingArc();
1427
        if (delta >= INF) return UNBOUNDED;
1429
        if (delta >= MAX) return UNBOUNDED;
1428 1430
        changeFlow(change);
1429 1431
        if (change) {
1430 1432
          updateTreeStructure();
1431 1433
          updatePotential();
1432 1434
        }
1433 1435
      }
1434 1436
      
1435 1437
      // Check feasibility
1436 1438
      for (int e = _search_arc_num; e != _all_arc_num; ++e) {
1437 1439
        if (_flow[e] != 0) return INFEASIBLE;
1438 1440
      }
1439 1441

	
1440 1442
      // Transform the solution and the supply map to the original form
1441 1443
      if (_have_lower) {
1442 1444
        for (int i = 0; i != _arc_num; ++i) {
1443 1445
          Value c = _lower[i];
1444 1446
          if (c != 0) {
1445 1447
            _flow[i] += c;
1446 1448
            _supply[_source[i]] += c;
1447 1449
            _supply[_target[i]] -= c;
1448 1450
          }
1449 1451
        }
1450 1452
      }
1451 1453
      
1452 1454
      // Shift potentials to meet the requirements of the GEQ/LEQ type
1453 1455
      // optimality conditions
1454 1456
      if (_sum_supply == 0) {
1455 1457
        if (_stype == GEQ) {
1456 1458
          Cost max_pot = std::numeric_limits<Cost>::min();
1457 1459
          for (int i = 0; i != _node_num; ++i) {
1458 1460
            if (_pi[i] > max_pot) max_pot = _pi[i];
1459 1461
          }
1460 1462
          if (max_pot > 0) {
1461 1463
            for (int i = 0; i != _node_num; ++i)
1462 1464
              _pi[i] -= max_pot;
1463 1465
          }
1464 1466
        } else {
1465 1467
          Cost min_pot = std::numeric_limits<Cost>::max();
1466 1468
          for (int i = 0; i != _node_num; ++i) {
1467 1469
            if (_pi[i] < min_pot) min_pot = _pi[i];
1468 1470
          }
1469 1471
          if (min_pot < 0) {
1470 1472
            for (int i = 0; i != _node_num; ++i)
1471 1473
              _pi[i] -= min_pot;
1472 1474
          }
1473 1475
        }
1474 1476
      }
1475 1477

	
1476 1478
      return OPTIMAL;
1477 1479
    }
1478 1480

	
1479 1481
  }; //class NetworkSimplex
1480 1482

	
1481 1483
  ///@}
1482 1484

	
1483 1485
} //namespace lemon
1484 1486

	
1485 1487
#endif //LEMON_NETWORK_SIMPLEX_H
0 comments (0 inline)