gravatar
kpeter (Peter Kovacs)
kpeter@inf.elte.hu
Rename Flow to Value in the flow algorithms (#266) We agreed that using Flow for the value type is misleading, since a flow should be rather a function on the arcs, not a single value. This patch reverts the changes of [dacc2cee2b4c] for Preflow and Circulation.
0 3 0
default
3 files changed with 73 insertions and 73 deletions:
↑ Collapse diff ↑
Ignore white space 6 line context
1 1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library.
4 4
 *
5 5
 * Copyright (C) 2003-2009
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#ifndef LEMON_CIRCULATION_H
20 20
#define LEMON_CIRCULATION_H
21 21

	
22 22
#include <lemon/tolerance.h>
23 23
#include <lemon/elevator.h>
24 24
#include <limits>
25 25

	
26 26
///\ingroup max_flow
27 27
///\file
28 28
///\brief Push-relabel algorithm for finding a feasible circulation.
29 29
///
30 30
namespace lemon {
31 31

	
32 32
  /// \brief Default traits class of Circulation class.
33 33
  ///
34 34
  /// Default traits class of Circulation class.
35 35
  ///
36 36
  /// \tparam GR Type of the digraph the algorithm runs on.
37 37
  /// \tparam LM The type of the lower bound map.
38 38
  /// \tparam UM The type of the upper bound (capacity) map.
39 39
  /// \tparam SM The type of the supply map.
40 40
  template <typename GR, typename LM,
41 41
            typename UM, typename SM>
42 42
  struct CirculationDefaultTraits {
43 43

	
44 44
    /// \brief The type of the digraph the algorithm runs on.
45 45
    typedef GR Digraph;
46 46

	
47 47
    /// \brief The type of the lower bound map.
48 48
    ///
49 49
    /// The type of the map that stores the lower bounds on the arcs.
50 50
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
51 51
    typedef LM LowerMap;
52 52

	
53 53
    /// \brief The type of the upper bound (capacity) map.
54 54
    ///
55 55
    /// The type of the map that stores the upper bounds (capacities)
56 56
    /// on the arcs.
57 57
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
58 58
    typedef UM UpperMap;
59 59

	
60 60
    /// \brief The type of supply map.
61 61
    ///
62 62
    /// The type of the map that stores the signed supply values of the 
63 63
    /// nodes. 
64 64
    /// It must conform to the \ref concepts::ReadMap "ReadMap" concept.
65 65
    typedef SM SupplyMap;
66 66

	
67
    /// \brief The type of the flow values.
68
    typedef typename SupplyMap::Value Flow;
67
    /// \brief The type of the flow and supply values.
68
    typedef typename SupplyMap::Value Value;
69 69

	
70 70
    /// \brief The type of the map that stores the flow values.
71 71
    ///
72 72
    /// The type of the map that stores the flow values.
73 73
    /// It must conform to the \ref concepts::ReadWriteMap "ReadWriteMap"
74 74
    /// concept.
75
    typedef typename Digraph::template ArcMap<Flow> FlowMap;
75
    typedef typename Digraph::template ArcMap<Value> FlowMap;
76 76

	
77 77
    /// \brief Instantiates a FlowMap.
78 78
    ///
79 79
    /// This function instantiates a \ref FlowMap.
80 80
    /// \param digraph The digraph for which we would like to define
81 81
    /// the flow map.
82 82
    static FlowMap* createFlowMap(const Digraph& digraph) {
83 83
      return new FlowMap(digraph);
84 84
    }
85 85

	
86 86
    /// \brief The elevator type used by the algorithm.
87 87
    ///
88 88
    /// The elevator type used by the algorithm.
89 89
    ///
90 90
    /// \sa Elevator
91 91
    /// \sa LinkedElevator
92 92
    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
93 93

	
94 94
    /// \brief Instantiates an Elevator.
95 95
    ///
96 96
    /// This function instantiates an \ref Elevator.
97 97
    /// \param digraph The digraph for which we would like to define
98 98
    /// the elevator.
99 99
    /// \param max_level The maximum level of the elevator.
100 100
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
101 101
      return new Elevator(digraph, max_level);
102 102
    }
103 103

	
104 104
    /// \brief The tolerance used by the algorithm
105 105
    ///
106 106
    /// The tolerance used by the algorithm to handle inexact computation.
107
    typedef lemon::Tolerance<Flow> Tolerance;
107
    typedef lemon::Tolerance<Value> Tolerance;
108 108

	
109 109
  };
110 110

	
111 111
  /**
112 112
     \brief Push-relabel algorithm for the network circulation problem.
113 113

	
114 114
     \ingroup max_flow
115 115
     This class implements a push-relabel algorithm for the \e network
116 116
     \e circulation problem.
117 117
     It is to find a feasible circulation when lower and upper bounds
118 118
     are given for the flow values on the arcs and lower bounds are
119 119
     given for the difference between the outgoing and incoming flow
120 120
     at the nodes.
121 121

	
122 122
     The exact formulation of this problem is the following.
123 123
     Let \f$G=(V,A)\f$ be a digraph, \f$lower: A\rightarrow\mathbf{R}\f$
124 124
     \f$upper: A\rightarrow\mathbf{R}\cup\{\infty\}\f$ denote the lower and
125 125
     upper bounds on the arcs, for which \f$lower(uv) \leq upper(uv)\f$
126 126
     holds for all \f$uv\in A\f$, and \f$sup: V\rightarrow\mathbf{R}\f$
127 127
     denotes the signed supply values of the nodes.
128 128
     If \f$sup(u)>0\f$, then \f$u\f$ is a supply node with \f$sup(u)\f$
129 129
     supply, if \f$sup(u)<0\f$, then \f$u\f$ is a demand node with
130 130
     \f$-sup(u)\f$ demand.
131 131
     A feasible circulation is an \f$f: A\rightarrow\mathbf{R}\f$
132 132
     solution of the following problem.
133 133

	
134 134
     \f[ \sum_{uv\in A} f(uv) - \sum_{vu\in A} f(vu)
135 135
     \geq sup(u) \quad \forall u\in V, \f]
136 136
     \f[ lower(uv) \leq f(uv) \leq upper(uv) \quad \forall uv\in A. \f]
137 137
     
138 138
     The sum of the supply values, i.e. \f$\sum_{u\in V} sup(u)\f$ must be
139 139
     zero or negative in order to have a feasible solution (since the sum
140 140
     of the expressions on the left-hand side of the inequalities is zero).
141 141
     It means that the total demand must be greater or equal to the total
142 142
     supply and all the supplies have to be carried out from the supply nodes,
143 143
     but there could be demands that are not satisfied.
144 144
     If \f$\sum_{u\in V} sup(u)\f$ is zero, then all the supply/demand
145 145
     constraints have to be satisfied with equality, i.e. all demands
146 146
     have to be satisfied and all supplies have to be used.
147 147
     
148 148
     If you need the opposite inequalities in the supply/demand constraints
149 149
     (i.e. the total demand is less than the total supply and all the demands
150 150
     have to be satisfied while there could be supplies that are not used),
151 151
     then you could easily transform the problem to the above form by reversing
152 152
     the direction of the arcs and taking the negative of the supply values
153 153
     (e.g. using \ref ReverseDigraph and \ref NegMap adaptors).
154 154

	
155 155
     This algorithm either calculates a feasible circulation, or provides
156 156
     a \ref barrier() "barrier", which prooves that a feasible soultion
157 157
     cannot exist.
158 158

	
159 159
     Note that this algorithm also provides a feasible solution for the
160 160
     \ref min_cost_flow "minimum cost flow problem".
161 161

	
162 162
     \tparam GR The type of the digraph the algorithm runs on.
163 163
     \tparam LM The type of the lower bound map. The default
164 164
     map type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
165 165
     \tparam UM The type of the upper bound (capacity) map.
166 166
     The default map type is \c LM.
167 167
     \tparam SM The type of the supply map. The default map type is
168 168
     \ref concepts::Digraph::NodeMap "GR::NodeMap<UM::Value>".
169 169
  */
170 170
#ifdef DOXYGEN
171 171
template< typename GR,
172 172
          typename LM,
173 173
          typename UM,
174 174
          typename SM,
175 175
          typename TR >
176 176
#else
177 177
template< typename GR,
178 178
          typename LM = typename GR::template ArcMap<int>,
179 179
          typename UM = LM,
180 180
          typename SM = typename GR::template NodeMap<typename UM::Value>,
181 181
          typename TR = CirculationDefaultTraits<GR, LM, UM, SM> >
182 182
#endif
183 183
  class Circulation {
184 184
  public:
185 185

	
186 186
    ///The \ref CirculationDefaultTraits "traits class" of the algorithm.
187 187
    typedef TR Traits;
188 188
    ///The type of the digraph the algorithm runs on.
189 189
    typedef typename Traits::Digraph Digraph;
190
    ///The type of the flow values.
191
    typedef typename Traits::Flow Flow;
190
    ///The type of the flow and supply values.
191
    typedef typename Traits::Value Value;
192 192

	
193 193
    ///The type of the lower bound map.
194 194
    typedef typename Traits::LowerMap LowerMap;
195 195
    ///The type of the upper bound (capacity) map.
196 196
    typedef typename Traits::UpperMap UpperMap;
197 197
    ///The type of the supply map.
198 198
    typedef typename Traits::SupplyMap SupplyMap;
199 199
    ///The type of the flow map.
200 200
    typedef typename Traits::FlowMap FlowMap;
201 201

	
202 202
    ///The type of the elevator.
203 203
    typedef typename Traits::Elevator Elevator;
204 204
    ///The type of the tolerance.
205 205
    typedef typename Traits::Tolerance Tolerance;
206 206

	
207 207
  private:
208 208

	
209 209
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
210 210

	
211 211
    const Digraph &_g;
212 212
    int _node_num;
213 213

	
214 214
    const LowerMap *_lo;
215 215
    const UpperMap *_up;
216 216
    const SupplyMap *_supply;
217 217

	
218 218
    FlowMap *_flow;
219 219
    bool _local_flow;
220 220

	
221 221
    Elevator* _level;
222 222
    bool _local_level;
223 223

	
224
    typedef typename Digraph::template NodeMap<Flow> ExcessMap;
224
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
225 225
    ExcessMap* _excess;
226 226

	
227 227
    Tolerance _tol;
228 228
    int _el;
229 229

	
230 230
  public:
231 231

	
232 232
    typedef Circulation Create;
233 233

	
234 234
    ///\name Named Template Parameters
235 235

	
236 236
    ///@{
237 237

	
238 238
    template <typename T>
239 239
    struct SetFlowMapTraits : public Traits {
240 240
      typedef T FlowMap;
241 241
      static FlowMap *createFlowMap(const Digraph&) {
242 242
        LEMON_ASSERT(false, "FlowMap is not initialized");
243 243
        return 0; // ignore warnings
244 244
      }
245 245
    };
246 246

	
247 247
    /// \brief \ref named-templ-param "Named parameter" for setting
248 248
    /// FlowMap type
249 249
    ///
250 250
    /// \ref named-templ-param "Named parameter" for setting FlowMap
251 251
    /// type.
252 252
    template <typename T>
253 253
    struct SetFlowMap
254 254
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
255 255
                           SetFlowMapTraits<T> > {
256 256
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
257 257
                          SetFlowMapTraits<T> > Create;
258 258
    };
259 259

	
260 260
    template <typename T>
261 261
    struct SetElevatorTraits : public Traits {
262 262
      typedef T Elevator;
263 263
      static Elevator *createElevator(const Digraph&, int) {
264 264
        LEMON_ASSERT(false, "Elevator is not initialized");
265 265
        return 0; // ignore warnings
266 266
      }
267 267
    };
268 268

	
269 269
    /// \brief \ref named-templ-param "Named parameter" for setting
270 270
    /// Elevator type
271 271
    ///
272 272
    /// \ref named-templ-param "Named parameter" for setting Elevator
273 273
    /// type. If this named parameter is used, then an external
274 274
    /// elevator object must be passed to the algorithm using the
275 275
    /// \ref elevator(Elevator&) "elevator()" function before calling
276 276
    /// \ref run() or \ref init().
277 277
    /// \sa SetStandardElevator
278 278
    template <typename T>
279 279
    struct SetElevator
280 280
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
281 281
                           SetElevatorTraits<T> > {
282 282
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
283 283
                          SetElevatorTraits<T> > Create;
284 284
    };
285 285

	
286 286
    template <typename T>
287 287
    struct SetStandardElevatorTraits : public Traits {
288 288
      typedef T Elevator;
289 289
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
290 290
        return new Elevator(digraph, max_level);
291 291
      }
292 292
    };
293 293

	
294 294
    /// \brief \ref named-templ-param "Named parameter" for setting
295 295
    /// Elevator type with automatic allocation
296 296
    ///
297 297
    /// \ref named-templ-param "Named parameter" for setting Elevator
298 298
    /// type with automatic allocation.
299 299
    /// The Elevator should have standard constructor interface to be
300 300
    /// able to automatically created by the algorithm (i.e. the
301 301
    /// digraph and the maximum level should be passed to it).
302 302
    /// However an external elevator object could also be passed to the
303 303
    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
304 304
    /// before calling \ref run() or \ref init().
305 305
    /// \sa SetElevator
306 306
    template <typename T>
307 307
    struct SetStandardElevator
308 308
      : public Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
309 309
                       SetStandardElevatorTraits<T> > {
310 310
      typedef Circulation<Digraph, LowerMap, UpperMap, SupplyMap,
311 311
                      SetStandardElevatorTraits<T> > Create;
312 312
    };
313 313

	
314 314
    /// @}
315 315

	
316 316
  protected:
317 317

	
318 318
    Circulation() {}
319 319

	
320 320
  public:
... ...
@@ -437,358 +437,358 @@
437 437
        _local_level = false;
438 438
      }
439 439
      _level = &elevator;
440 440
      return *this;
441 441
    }
442 442

	
443 443
    /// \brief Returns a const reference to the elevator.
444 444
    ///
445 445
    /// Returns a const reference to the elevator.
446 446
    ///
447 447
    /// \pre Either \ref run() or \ref init() must be called before
448 448
    /// using this function.
449 449
    const Elevator& elevator() const {
450 450
      return *_level;
451 451
    }
452 452

	
453 453
    /// \brief Sets the tolerance used by algorithm.
454 454
    ///
455 455
    /// Sets the tolerance used by algorithm.
456 456
    Circulation& tolerance(const Tolerance& tolerance) const {
457 457
      _tol = tolerance;
458 458
      return *this;
459 459
    }
460 460

	
461 461
    /// \brief Returns a const reference to the tolerance.
462 462
    ///
463 463
    /// Returns a const reference to the tolerance.
464 464
    const Tolerance& tolerance() const {
465 465
      return tolerance;
466 466
    }
467 467

	
468 468
    /// \name Execution Control
469 469
    /// The simplest way to execute the algorithm is to call \ref run().\n
470 470
    /// If you need more control on the initial solution or the execution,
471 471
    /// first you have to call one of the \ref init() functions, then
472 472
    /// the \ref start() function.
473 473

	
474 474
    ///@{
475 475

	
476 476
    /// Initializes the internal data structures.
477 477

	
478 478
    /// Initializes the internal data structures and sets all flow values
479 479
    /// to the lower bound.
480 480
    void init()
481 481
    {
482 482
      LEMON_DEBUG(checkBoundMaps(),
483 483
        "Upper bounds must be greater or equal to the lower bounds");
484 484

	
485 485
      createStructures();
486 486

	
487 487
      for(NodeIt n(_g);n!=INVALID;++n) {
488 488
        (*_excess)[n] = (*_supply)[n];
489 489
      }
490 490

	
491 491
      for (ArcIt e(_g);e!=INVALID;++e) {
492 492
        _flow->set(e, (*_lo)[e]);
493 493
        (*_excess)[_g.target(e)] += (*_flow)[e];
494 494
        (*_excess)[_g.source(e)] -= (*_flow)[e];
495 495
      }
496 496

	
497 497
      // global relabeling tested, but in general case it provides
498 498
      // worse performance for random digraphs
499 499
      _level->initStart();
500 500
      for(NodeIt n(_g);n!=INVALID;++n)
501 501
        _level->initAddItem(n);
502 502
      _level->initFinish();
503 503
      for(NodeIt n(_g);n!=INVALID;++n)
504 504
        if(_tol.positive((*_excess)[n]))
505 505
          _level->activate(n);
506 506
    }
507 507

	
508 508
    /// Initializes the internal data structures using a greedy approach.
509 509

	
510 510
    /// Initializes the internal data structures using a greedy approach
511 511
    /// to construct the initial solution.
512 512
    void greedyInit()
513 513
    {
514 514
      LEMON_DEBUG(checkBoundMaps(),
515 515
        "Upper bounds must be greater or equal to the lower bounds");
516 516

	
517 517
      createStructures();
518 518

	
519 519
      for(NodeIt n(_g);n!=INVALID;++n) {
520 520
        (*_excess)[n] = (*_supply)[n];
521 521
      }
522 522

	
523 523
      for (ArcIt e(_g);e!=INVALID;++e) {
524 524
        if (!_tol.less(-(*_excess)[_g.target(e)], (*_up)[e])) {
525 525
          _flow->set(e, (*_up)[e]);
526 526
          (*_excess)[_g.target(e)] += (*_up)[e];
527 527
          (*_excess)[_g.source(e)] -= (*_up)[e];
528 528
        } else if (_tol.less(-(*_excess)[_g.target(e)], (*_lo)[e])) {
529 529
          _flow->set(e, (*_lo)[e]);
530 530
          (*_excess)[_g.target(e)] += (*_lo)[e];
531 531
          (*_excess)[_g.source(e)] -= (*_lo)[e];
532 532
        } else {
533
          Flow fc = -(*_excess)[_g.target(e)];
533
          Value fc = -(*_excess)[_g.target(e)];
534 534
          _flow->set(e, fc);
535 535
          (*_excess)[_g.target(e)] = 0;
536 536
          (*_excess)[_g.source(e)] -= fc;
537 537
        }
538 538
      }
539 539

	
540 540
      _level->initStart();
541 541
      for(NodeIt n(_g);n!=INVALID;++n)
542 542
        _level->initAddItem(n);
543 543
      _level->initFinish();
544 544
      for(NodeIt n(_g);n!=INVALID;++n)
545 545
        if(_tol.positive((*_excess)[n]))
546 546
          _level->activate(n);
547 547
    }
548 548

	
549 549
    ///Executes the algorithm
550 550

	
551 551
    ///This function executes the algorithm.
552 552
    ///
553 553
    ///\return \c true if a feasible circulation is found.
554 554
    ///
555 555
    ///\sa barrier()
556 556
    ///\sa barrierMap()
557 557
    bool start()
558 558
    {
559 559

	
560 560
      Node act;
561 561
      Node bact=INVALID;
562 562
      Node last_activated=INVALID;
563 563
      while((act=_level->highestActive())!=INVALID) {
564 564
        int actlevel=(*_level)[act];
565 565
        int mlevel=_node_num;
566
        Flow exc=(*_excess)[act];
566
        Value exc=(*_excess)[act];
567 567

	
568 568
        for(OutArcIt e(_g,act);e!=INVALID; ++e) {
569 569
          Node v = _g.target(e);
570
          Flow fc=(*_up)[e]-(*_flow)[e];
570
          Value fc=(*_up)[e]-(*_flow)[e];
571 571
          if(!_tol.positive(fc)) continue;
572 572
          if((*_level)[v]<actlevel) {
573 573
            if(!_tol.less(fc, exc)) {
574 574
              _flow->set(e, (*_flow)[e] + exc);
575 575
              (*_excess)[v] += exc;
576 576
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
577 577
                _level->activate(v);
578 578
              (*_excess)[act] = 0;
579 579
              _level->deactivate(act);
580 580
              goto next_l;
581 581
            }
582 582
            else {
583 583
              _flow->set(e, (*_up)[e]);
584 584
              (*_excess)[v] += fc;
585 585
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
586 586
                _level->activate(v);
587 587
              exc-=fc;
588 588
            }
589 589
          }
590 590
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
591 591
        }
592 592
        for(InArcIt e(_g,act);e!=INVALID; ++e) {
593 593
          Node v = _g.source(e);
594
          Flow fc=(*_flow)[e]-(*_lo)[e];
594
          Value fc=(*_flow)[e]-(*_lo)[e];
595 595
          if(!_tol.positive(fc)) continue;
596 596
          if((*_level)[v]<actlevel) {
597 597
            if(!_tol.less(fc, exc)) {
598 598
              _flow->set(e, (*_flow)[e] - exc);
599 599
              (*_excess)[v] += exc;
600 600
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
601 601
                _level->activate(v);
602 602
              (*_excess)[act] = 0;
603 603
              _level->deactivate(act);
604 604
              goto next_l;
605 605
            }
606 606
            else {
607 607
              _flow->set(e, (*_lo)[e]);
608 608
              (*_excess)[v] += fc;
609 609
              if(!_level->active(v) && _tol.positive((*_excess)[v]))
610 610
                _level->activate(v);
611 611
              exc-=fc;
612 612
            }
613 613
          }
614 614
          else if((*_level)[v]<mlevel) mlevel=(*_level)[v];
615 615
        }
616 616

	
617 617
        (*_excess)[act] = exc;
618 618
        if(!_tol.positive(exc)) _level->deactivate(act);
619 619
        else if(mlevel==_node_num) {
620 620
          _level->liftHighestActiveToTop();
621 621
          _el = _node_num;
622 622
          return false;
623 623
        }
624 624
        else {
625 625
          _level->liftHighestActive(mlevel+1);
626 626
          if(_level->onLevel(actlevel)==0) {
627 627
            _el = actlevel;
628 628
            return false;
629 629
          }
630 630
        }
631 631
      next_l:
632 632
        ;
633 633
      }
634 634
      return true;
635 635
    }
636 636

	
637 637
    /// Runs the algorithm.
638 638

	
639 639
    /// This function runs the algorithm.
640 640
    ///
641 641
    /// \return \c true if a feasible circulation is found.
642 642
    ///
643 643
    /// \note Apart from the return value, c.run() is just a shortcut of
644 644
    /// the following code.
645 645
    /// \code
646 646
    ///   c.greedyInit();
647 647
    ///   c.start();
648 648
    /// \endcode
649 649
    bool run() {
650 650
      greedyInit();
651 651
      return start();
652 652
    }
653 653

	
654 654
    /// @}
655 655

	
656 656
    /// \name Query Functions
657 657
    /// The results of the circulation algorithm can be obtained using
658 658
    /// these functions.\n
659 659
    /// Either \ref run() or \ref start() should be called before
660 660
    /// using them.
661 661

	
662 662
    ///@{
663 663

	
664
    /// \brief Returns the flow on the given arc.
664
    /// \brief Returns the flow value on the given arc.
665 665
    ///
666
    /// Returns the flow on the given arc.
666
    /// Returns the flow value on the given arc.
667 667
    ///
668 668
    /// \pre Either \ref run() or \ref init() must be called before
669 669
    /// using this function.
670
    Flow flow(const Arc& arc) const {
670
    Value flow(const Arc& arc) const {
671 671
      return (*_flow)[arc];
672 672
    }
673 673

	
674 674
    /// \brief Returns a const reference to the flow map.
675 675
    ///
676 676
    /// Returns a const reference to the arc map storing the found flow.
677 677
    ///
678 678
    /// \pre Either \ref run() or \ref init() must be called before
679 679
    /// using this function.
680 680
    const FlowMap& flowMap() const {
681 681
      return *_flow;
682 682
    }
683 683

	
684 684
    /**
685 685
       \brief Returns \c true if the given node is in a barrier.
686 686

	
687 687
       Barrier is a set \e B of nodes for which
688 688

	
689 689
       \f[ \sum_{uv\in A: u\in B} upper(uv) -
690 690
           \sum_{uv\in A: v\in B} lower(uv) < \sum_{v\in B} sup(v) \f]
691 691

	
692 692
       holds. The existence of a set with this property prooves that a
693 693
       feasible circualtion cannot exist.
694 694

	
695 695
       This function returns \c true if the given node is in the found
696 696
       barrier. If a feasible circulation is found, the function
697 697
       gives back \c false for every node.
698 698

	
699 699
       \pre Either \ref run() or \ref init() must be called before
700 700
       using this function.
701 701

	
702 702
       \sa barrierMap()
703 703
       \sa checkBarrier()
704 704
    */
705 705
    bool barrier(const Node& node) const
706 706
    {
707 707
      return (*_level)[node] >= _el;
708 708
    }
709 709

	
710 710
    /// \brief Gives back a barrier.
711 711
    ///
712 712
    /// This function sets \c bar to the characteristic vector of the
713 713
    /// found barrier. \c bar should be a \ref concepts::WriteMap "writable"
714 714
    /// node map with \c bool (or convertible) value type.
715 715
    ///
716 716
    /// If a feasible circulation is found, the function gives back an
717 717
    /// empty set, so \c bar[v] will be \c false for all nodes \c v.
718 718
    ///
719 719
    /// \note This function calls \ref barrier() for each node,
720 720
    /// so it runs in O(n) time.
721 721
    ///
722 722
    /// \pre Either \ref run() or \ref init() must be called before
723 723
    /// using this function.
724 724
    ///
725 725
    /// \sa barrier()
726 726
    /// \sa checkBarrier()
727 727
    template<class BarrierMap>
728 728
    void barrierMap(BarrierMap &bar) const
729 729
    {
730 730
      for(NodeIt n(_g);n!=INVALID;++n)
731 731
        bar.set(n, (*_level)[n] >= _el);
732 732
    }
733 733

	
734 734
    /// @}
735 735

	
736 736
    /// \name Checker Functions
737 737
    /// The feasibility of the results can be checked using
738 738
    /// these functions.\n
739 739
    /// Either \ref run() or \ref start() should be called before
740 740
    /// using them.
741 741

	
742 742
    ///@{
743 743

	
744 744
    ///Check if the found flow is a feasible circulation
745 745

	
746 746
    ///Check if the found flow is a feasible circulation,
747 747
    ///
748 748
    bool checkFlow() const {
749 749
      for(ArcIt e(_g);e!=INVALID;++e)
750 750
        if((*_flow)[e]<(*_lo)[e]||(*_flow)[e]>(*_up)[e]) return false;
751 751
      for(NodeIt n(_g);n!=INVALID;++n)
752 752
        {
753
          Flow dif=-(*_supply)[n];
753
          Value dif=-(*_supply)[n];
754 754
          for(InArcIt e(_g,n);e!=INVALID;++e) dif-=(*_flow)[e];
755 755
          for(OutArcIt e(_g,n);e!=INVALID;++e) dif+=(*_flow)[e];
756 756
          if(_tol.negative(dif)) return false;
757 757
        }
758 758
      return true;
759 759
    }
760 760

	
761 761
    ///Check whether or not the last execution provides a barrier
762 762

	
763 763
    ///Check whether or not the last execution provides a barrier.
764 764
    ///\sa barrier()
765 765
    ///\sa barrierMap()
766 766
    bool checkBarrier() const
767 767
    {
768
      Flow delta=0;
769
      Flow inf_cap = std::numeric_limits<Flow>::has_infinity ?
770
        std::numeric_limits<Flow>::infinity() :
771
        std::numeric_limits<Flow>::max();
768
      Value delta=0;
769
      Value inf_cap = std::numeric_limits<Value>::has_infinity ?
770
        std::numeric_limits<Value>::infinity() :
771
        std::numeric_limits<Value>::max();
772 772
      for(NodeIt n(_g);n!=INVALID;++n)
773 773
        if(barrier(n))
774 774
          delta-=(*_supply)[n];
775 775
      for(ArcIt e(_g);e!=INVALID;++e)
776 776
        {
777 777
          Node s=_g.source(e);
778 778
          Node t=_g.target(e);
779 779
          if(barrier(s)&&!barrier(t)) {
780 780
            if (_tol.less(inf_cap - (*_up)[e], delta)) return false;
781 781
            delta+=(*_up)[e];
782 782
          }
783 783
          else if(barrier(t)&&!barrier(s)) delta-=(*_lo)[e];
784 784
        }
785 785
      return _tol.negative(delta);
786 786
    }
787 787

	
788 788
    /// @}
789 789

	
790 790
  };
791 791

	
792 792
}
793 793

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

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

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

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

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

	
34 34
namespace lemon {
35 35

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

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

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

	
91 91
  public:
92 92

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

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

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

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

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

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

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

	
198 198
      /// The Altering Candidate List pivot rule.
199 199
      /// It is a modified version of the Candidate List method.
200 200
      /// It keeps only the several best eligible arcs from the former
201 201
      /// candidate list and extends this list in every iteration.
202 202
      ALTERING_LIST
203 203
    };
204 204
    
205 205
  private:
206 206

	
207 207
    TEMPLATE_DIGRAPH_TYPEDEFS(GR);
208 208

	
209
    typedef typename GR::template ArcMap<Flow> FlowArcMap;
209
    typedef typename GR::template ArcMap<Value> ValueArcMap;
210 210
    typedef typename GR::template ArcMap<Cost> CostArcMap;
211
    typedef typename GR::template NodeMap<Flow> FlowNodeMap;
211
    typedef typename GR::template NodeMap<Value> ValueNodeMap;
212 212

	
213 213
    typedef std::vector<Arc> ArcVector;
214 214
    typedef std::vector<Node> NodeVector;
215 215
    typedef std::vector<int> IntVector;
216 216
    typedef std::vector<bool> BoolVector;
217
    typedef std::vector<Flow> FlowVector;
217
    typedef std::vector<Value> FlowVector;
218 218
    typedef std::vector<Cost> CostVector;
219 219

	
220 220
    // State constants for arcs
221 221
    enum ArcStateEnum {
222 222
      STATE_UPPER = -1,
223 223
      STATE_TREE  =  0,
224 224
      STATE_LOWER =  1
225 225
    };
226 226

	
227 227
  private:
228 228

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

	
234 234
    // Parameters of the problem
235
    FlowArcMap *_plower;
236
    FlowArcMap *_pupper;
235
    ValueArcMap *_plower;
236
    ValueArcMap *_pupper;
237 237
    CostArcMap *_pcost;
238
    FlowNodeMap *_psupply;
238
    ValueNodeMap *_psupply;
239 239
    bool _pstsup;
240 240
    Node _psource, _ptarget;
241
    Flow _pstflow;
241
    Value _pstflow;
242 242
    SupplyType _stype;
243 243
    
244
    Flow _sum_supply;
244
    Value _sum_supply;
245 245

	
246 246
    // Result maps
247 247
    FlowMap *_flow_map;
248 248
    PotentialMap *_potential_map;
249 249
    bool _local_flow;
250 250
    bool _local_potential;
251 251

	
252 252
    // Data structures for storing the digraph
253 253
    IntNodeMap _node_id;
254 254
    ArcVector _arc_ref;
255 255
    IntVector _source;
256 256
    IntVector _target;
257 257

	
258 258
    // Node and arc data
259 259
    FlowVector _cap;
260 260
    CostVector _cost;
261 261
    FlowVector _supply;
262 262
    FlowVector _flow;
263 263
    CostVector _pi;
264 264

	
265 265
    // Data for storing the spanning tree structure
266 266
    IntVector _parent;
267 267
    IntVector _pred;
268 268
    IntVector _thread;
269 269
    IntVector _rev_thread;
270 270
    IntVector _succ_num;
271 271
    IntVector _last_succ;
272 272
    IntVector _dirty_revs;
273 273
    BoolVector _forward;
274 274
    IntVector _state;
275 275
    int _root;
276 276

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

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

	
292 292
  private:
293 293

	
294 294
    // Implementation of the First Eligible pivot rule
295 295
    class FirstEligiblePivotRule
296 296
    {
297 297
    private:
298 298

	
299 299
      // References to the NetworkSimplex class
300 300
      const IntVector  &_source;
301 301
      const IntVector  &_target;
302 302
      const CostVector &_cost;
303 303
      const IntVector  &_state;
304 304
      const CostVector &_pi;
305 305
      int &_in_arc;
306 306
      int _arc_num;
307 307

	
308 308
      // Pivot rule data
309 309
      int _next_arc;
310 310

	
311 311
    public:
312 312

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

	
320 320
      // Find next entering arc
321 321
      bool findEnteringArc() {
322 322
        Cost c;
323 323
        for (int e = _next_arc; e < _arc_num; ++e) {
324 324
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
325 325
          if (c < 0) {
326 326
            _in_arc = e;
327 327
            _next_arc = e + 1;
328 328
            return true;
329 329
          }
330 330
        }
331 331
        for (int e = 0; e < _next_arc; ++e) {
332 332
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
333 333
          if (c < 0) {
334 334
            _in_arc = e;
335 335
            _next_arc = e + 1;
336 336
            return true;
337 337
          }
338 338
        }
339 339
        return false;
340 340
      }
341 341

	
342 342
    }; //class FirstEligiblePivotRule
343 343

	
344 344

	
345 345
    // Implementation of the Best Eligible pivot rule
346 346
    class BestEligiblePivotRule
347 347
    {
348 348
    private:
349 349

	
350 350
      // References to the NetworkSimplex class
351 351
      const IntVector  &_source;
352 352
      const IntVector  &_target;
353 353
      const CostVector &_cost;
354 354
      const IntVector  &_state;
355 355
      const CostVector &_pi;
356 356
      int &_in_arc;
357 357
      int _arc_num;
358 358

	
359 359
    public:
360 360

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

	
368 368
      // Find next entering arc
369 369
      bool findEnteringArc() {
370 370
        Cost c, min = 0;
371 371
        for (int e = 0; e < _arc_num; ++e) {
372 372
          c = _state[e] * (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
373 373
          if (c < min) {
374 374
            min = c;
375 375
            _in_arc = e;
376 376
          }
377 377
        }
378 378
        return min < 0;
379 379
      }
380 380

	
381 381
    }; //class BestEligiblePivotRule
382 382

	
383 383

	
384 384
    // Implementation of the Block Search pivot rule
385 385
    class BlockSearchPivotRule
386 386
    {
... ...
@@ -602,321 +602,321 @@
602 602
        _cost(ns._cost), _state(ns._state), _pi(ns._pi),
603 603
        _in_arc(ns.in_arc), _arc_num(ns._arc_num),
604 604
        _next_arc(0), _cand_cost(ns._arc_num), _sort_func(_cand_cost)
605 605
      {
606 606
        // The main parameters of the pivot rule
607 607
        const double BLOCK_SIZE_FACTOR = 1.5;
608 608
        const int MIN_BLOCK_SIZE = 10;
609 609
        const double HEAD_LENGTH_FACTOR = 0.1;
610 610
        const int MIN_HEAD_LENGTH = 3;
611 611

	
612 612
        _block_size = std::max( int(BLOCK_SIZE_FACTOR *
613 613
                                    std::sqrt(double(_arc_num))),
614 614
                                MIN_BLOCK_SIZE );
615 615
        _head_length = std::max( int(HEAD_LENGTH_FACTOR * _block_size),
616 616
                                 MIN_HEAD_LENGTH );
617 617
        _candidates.resize(_head_length + _block_size);
618 618
        _curr_length = 0;
619 619
      }
620 620

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

	
634 634
        // Extend the list
635 635
        int cnt = _block_size;
636 636
        int last_arc = 0;
637 637
        int limit = _head_length;
638 638

	
639 639
        for (int e = _next_arc; e < _arc_num; ++e) {
640 640
          _cand_cost[e] = _state[e] *
641 641
            (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
642 642
          if (_cand_cost[e] < 0) {
643 643
            _candidates[_curr_length++] = e;
644 644
            last_arc = e;
645 645
          }
646 646
          if (--cnt == 0) {
647 647
            if (_curr_length > limit) break;
648 648
            limit = 0;
649 649
            cnt = _block_size;
650 650
          }
651 651
        }
652 652
        if (_curr_length <= limit) {
653 653
          for (int e = 0; e < _next_arc; ++e) {
654 654
            _cand_cost[e] = _state[e] *
655 655
              (_cost[e] + _pi[_source[e]] - _pi[_target[e]]);
656 656
            if (_cand_cost[e] < 0) {
657 657
              _candidates[_curr_length++] = e;
658 658
              last_arc = e;
659 659
            }
660 660
            if (--cnt == 0) {
661 661
              if (_curr_length > limit) break;
662 662
              limit = 0;
663 663
              cnt = _block_size;
664 664
            }
665 665
          }
666 666
        }
667 667
        if (_curr_length == 0) return false;
668 668
        _next_arc = last_arc + 1;
669 669

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

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

	
682 682
    }; //class AlteringListPivotRule
683 683

	
684 684
  public:
685 685

	
686 686
    /// \brief Constructor.
687 687
    ///
688 688
    /// The constructor of the class.
689 689
    ///
690 690
    /// \param graph The digraph the algorithm runs on.
691 691
    NetworkSimplex(const GR& graph) :
692 692
      _graph(graph),
693 693
      _plower(NULL), _pupper(NULL), _pcost(NULL),
694 694
      _psupply(NULL), _pstsup(false), _stype(GEQ),
695 695
      _flow_map(NULL), _potential_map(NULL),
696 696
      _local_flow(false), _local_potential(false),
697 697
      _node_id(graph),
698
      INF(std::numeric_limits<Flow>::has_infinity ?
699
          std::numeric_limits<Flow>::infinity() :
700
          std::numeric_limits<Flow>::max())
698
      INF(std::numeric_limits<Value>::has_infinity ?
699
          std::numeric_limits<Value>::infinity() :
700
          std::numeric_limits<Value>::max())
701 701
    {
702 702
      // Check the value types
703
      LEMON_ASSERT(std::numeric_limits<Flow>::is_signed,
703
      LEMON_ASSERT(std::numeric_limits<Value>::is_signed,
704 704
        "The flow type of NetworkSimplex must be signed");
705 705
      LEMON_ASSERT(std::numeric_limits<Cost>::is_signed,
706 706
        "The cost type of NetworkSimplex must be signed");
707 707
    }
708 708

	
709 709
    /// Destructor.
710 710
    ~NetworkSimplex() {
711 711
      if (_local_flow) delete _flow_map;
712 712
      if (_local_potential) delete _potential_map;
713 713
    }
714 714

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

	
719 719
    /// @{
720 720

	
721 721
    /// \brief Set the lower bounds on the arcs.
722 722
    ///
723 723
    /// This function sets the lower bounds on the arcs.
724 724
    /// If it is not used before calling \ref run(), the lower bounds
725 725
    /// will be set to zero on all arcs.
726 726
    ///
727 727
    /// \param map An arc map storing the lower bounds.
728
    /// Its \c Value type must be convertible to the \c Flow type
728
    /// Its \c Value type must be convertible to the \c Value type
729 729
    /// of the algorithm.
730 730
    ///
731 731
    /// \return <tt>(*this)</tt>
732 732
    template <typename LowerMap>
733 733
    NetworkSimplex& lowerMap(const LowerMap& map) {
734 734
      delete _plower;
735
      _plower = new FlowArcMap(_graph);
735
      _plower = new ValueArcMap(_graph);
736 736
      for (ArcIt a(_graph); a != INVALID; ++a) {
737 737
        (*_plower)[a] = map[a];
738 738
      }
739 739
      return *this;
740 740
    }
741 741

	
742 742
    /// \brief Set the upper bounds (capacities) on the arcs.
743 743
    ///
744 744
    /// This function sets the upper bounds (capacities) on the arcs.
745 745
    /// If it is not used before calling \ref run(), the upper bounds
746 746
    /// will be set to \ref INF on all arcs (i.e. the flow value will be
747 747
    /// unbounded from above on each arc).
748 748
    ///
749 749
    /// \param map An arc map storing the upper bounds.
750
    /// Its \c Value type must be convertible to the \c Flow type
750
    /// Its \c Value type must be convertible to the \c Value type
751 751
    /// of the algorithm.
752 752
    ///
753 753
    /// \return <tt>(*this)</tt>
754 754
    template<typename UpperMap>
755 755
    NetworkSimplex& upperMap(const UpperMap& map) {
756 756
      delete _pupper;
757
      _pupper = new FlowArcMap(_graph);
757
      _pupper = new ValueArcMap(_graph);
758 758
      for (ArcIt a(_graph); a != INVALID; ++a) {
759 759
        (*_pupper)[a] = map[a];
760 760
      }
761 761
      return *this;
762 762
    }
763 763

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

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

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

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

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

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

	
890 890
    /// @{
891 891

	
892 892
    /// \brief Run the algorithm.
893 893
    ///
894 894
    /// This function runs the algorithm.
895 895
    /// The paramters can be specified using functions \ref lowerMap(),
896 896
    /// \ref upperMap(), \ref costMap(), \ref supplyMap(), \ref stSupply(), 
897 897
    /// \ref supplyType(), \ref flowMap() and \ref potentialMap().
898 898
    /// For example,
899 899
    /// \code
900 900
    ///   NetworkSimplex<ListDigraph> ns(graph);
901 901
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
902 902
    ///     .supplyMap(sup).run();
903 903
    /// \endcode
904 904
    ///
905 905
    /// This function can be called more than once. All the parameters
906 906
    /// that have been given are kept for the next call, unless
907 907
    /// \ref reset() is called, thus only the modified parameters
908 908
    /// have to be set again. See \ref reset() for examples.
909 909
    ///
910 910
    /// \param pivot_rule The pivot rule that will be used during the
911 911
    /// algorithm. For more information see \ref PivotRule.
912 912
    ///
913 913
    /// \return \c INFEASIBLE if no feasible flow exists,
914 914
    /// \n \c OPTIMAL if the problem has optimal solution
915 915
    /// (i.e. it is feasible and bounded), and the algorithm has found
916 916
    /// optimal flow and node potentials (primal and dual solutions),
917 917
    /// \n \c UNBOUNDED if the objective function of the problem is
918 918
    /// unbounded, i.e. there is a directed cycle having negative total
919 919
    /// cost and infinite upper bound.
920 920
    ///
921 921
    /// \see ProblemType, PivotRule
922 922
    ProblemType run(PivotRule pivot_rule = BLOCK_SEARCH) {
... ...
@@ -932,483 +932,483 @@
932 932
    /// \ref flowMap() and \ref potentialMap().
933 933
    ///
934 934
    /// It is useful for multiple run() calls. If this function is not
935 935
    /// used, all the parameters given before are kept for the next
936 936
    /// \ref run() call.
937 937
    ///
938 938
    /// For example,
939 939
    /// \code
940 940
    ///   NetworkSimplex<ListDigraph> ns(graph);
941 941
    ///
942 942
    ///   // First run
943 943
    ///   ns.lowerMap(lower).upperMap(upper).costMap(cost)
944 944
    ///     .supplyMap(sup).run();
945 945
    ///
946 946
    ///   // Run again with modified cost map (reset() is not called,
947 947
    ///   // so only the cost map have to be set again)
948 948
    ///   cost[e] += 100;
949 949
    ///   ns.costMap(cost).run();
950 950
    ///
951 951
    ///   // Run again from scratch using reset()
952 952
    ///   // (the lower bounds will be set to zero on all arcs)
953 953
    ///   ns.reset();
954 954
    ///   ns.upperMap(capacity).costMap(cost)
955 955
    ///     .supplyMap(sup).run();
956 956
    /// \endcode
957 957
    ///
958 958
    /// \return <tt>(*this)</tt>
959 959
    NetworkSimplex& reset() {
960 960
      delete _plower;
961 961
      delete _pupper;
962 962
      delete _pcost;
963 963
      delete _psupply;
964 964
      _plower = NULL;
965 965
      _pupper = NULL;
966 966
      _pcost = NULL;
967 967
      _psupply = NULL;
968 968
      _pstsup = false;
969 969
      _stype = GEQ;
970 970
      if (_local_flow) delete _flow_map;
971 971
      if (_local_potential) delete _potential_map;
972 972
      _flow_map = NULL;
973 973
      _potential_map = NULL;
974 974
      _local_flow = false;
975 975
      _local_potential = false;
976 976

	
977 977
      return *this;
978 978
    }
979 979

	
980 980
    /// @}
981 981

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

	
987 987
    /// @{
988 988

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

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

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

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

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

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

	
1064 1064
    /// @}
1065 1065

	
1066 1066
  private:
1067 1067

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

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

	
1087 1087
      _arc_ref.resize(_arc_num);
1088 1088
      _source.resize(all_arc_num);
1089 1089
      _target.resize(all_arc_num);
1090 1090

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

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

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

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

	
1146 1146
      // Set data for the artificial root node
1147 1147
      _root = _node_num;
1148 1148
      _parent[_root] = -1;
1149 1149
      _pred[_root] = -1;
1150 1150
      _thread[_root] = 0;
1151 1151
      _rev_thread[0] = _root;
1152 1152
      _succ_num[_root] = all_node_num;
1153 1153
      _last_succ[_root] = _root - 1;
1154 1154
      _supply[_root] = -_sum_supply;
1155 1155
      if (_sum_supply < 0) {
1156 1156
        _pi[_root] = -ART_COST;
1157 1157
      } else {
1158 1158
        _pi[_root] = ART_COST;
1159 1159
      }
1160 1160

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

	
1169 1169
      // Initialize arc maps
1170 1170
      if (_pupper && _pcost) {
1171 1171
        for (int i = 0; i != _arc_num; ++i) {
1172 1172
          Arc e = _arc_ref[i];
1173 1173
          _source[i] = _node_id[_graph.source(e)];
1174 1174
          _target[i] = _node_id[_graph.target(e)];
1175 1175
          _cap[i] = (*_pupper)[e];
1176 1176
          _cost[i] = (*_pcost)[e];
1177 1177
          _flow[i] = 0;
1178 1178
          _state[i] = STATE_LOWER;
1179 1179
        }
1180 1180
      } else {
1181 1181
        for (int i = 0; i != _arc_num; ++i) {
1182 1182
          Arc e = _arc_ref[i];
1183 1183
          _source[i] = _node_id[_graph.source(e)];
1184 1184
          _target[i] = _node_id[_graph.target(e)];
1185 1185
          _flow[i] = 0;
1186 1186
          _state[i] = STATE_LOWER;
1187 1187
        }
1188 1188
        if (_pupper) {
1189 1189
          for (int i = 0; i != _arc_num; ++i)
1190 1190
            _cap[i] = (*_pupper)[_arc_ref[i]];
1191 1191
        } else {
1192 1192
          for (int i = 0; i != _arc_num; ++i)
1193 1193
            _cap[i] = INF;
1194 1194
        }
1195 1195
        if (_pcost) {
1196 1196
          for (int i = 0; i != _arc_num; ++i)
1197 1197
            _cost[i] = (*_pcost)[_arc_ref[i]];
1198 1198
        } else {
1199 1199
          for (int i = 0; i != _arc_num; ++i)
1200 1200
            _cost[i] = 1;
1201 1201
        }
1202 1202
      }
1203 1203
      
1204 1204
      // Remove non-zero lower bounds
1205 1205
      if (_plower) {
1206 1206
        for (int i = 0; i != _arc_num; ++i) {
1207
          Flow c = (*_plower)[_arc_ref[i]];
1207
          Value c = (*_plower)[_arc_ref[i]];
1208 1208
          if (c > 0) {
1209 1209
            if (_cap[i] < INF) _cap[i] -= c;
1210 1210
            _supply[_source[i]] -= c;
1211 1211
            _supply[_target[i]] += c;
1212 1212
          }
1213 1213
          else if (c < 0) {
1214 1214
            if (_cap[i] < INF + c) {
1215 1215
              _cap[i] -= c;
1216 1216
            } else {
1217 1217
              _cap[i] = INF;
1218 1218
            }
1219 1219
            _supply[_source[i]] -= c;
1220 1220
            _supply[_target[i]] += c;
1221 1221
          }
1222 1222
        }
1223 1223
      }
1224 1224

	
1225 1225
      // Add artificial arcs and initialize the spanning tree data structure
1226 1226
      for (int u = 0, e = _arc_num; u != _node_num; ++u, ++e) {
1227 1227
        _thread[u] = u + 1;
1228 1228
        _rev_thread[u + 1] = u;
1229 1229
        _succ_num[u] = 1;
1230 1230
        _last_succ[u] = u;
1231 1231
        _parent[u] = _root;
1232 1232
        _pred[u] = e;
1233 1233
        _cost[e] = ART_COST;
1234 1234
        _cap[e] = INF;
1235 1235
        _state[e] = STATE_TREE;
1236 1236
        if (_supply[u] > 0 || (_supply[u] == 0 && _sum_supply <= 0)) {
1237 1237
          _flow[e] = _supply[u];
1238 1238
          _forward[u] = true;
1239 1239
          _pi[u] = -ART_COST + _pi[_root];
1240 1240
        } else {
1241 1241
          _flow[e] = -_supply[u];
1242 1242
          _forward[u] = false;
1243 1243
          _pi[u] = ART_COST + _pi[_root];
1244 1244
        }
1245 1245
      }
1246 1246

	
1247 1247
      return true;
1248 1248
    }
1249 1249

	
1250 1250
    // Find the join node
1251 1251
    void findJoinNode() {
1252 1252
      int u = _source[in_arc];
1253 1253
      int v = _target[in_arc];
1254 1254
      while (u != v) {
1255 1255
        if (_succ_num[u] < _succ_num[v]) {
1256 1256
          u = _parent[u];
1257 1257
        } else {
1258 1258
          v = _parent[v];
1259 1259
        }
1260 1260
      }
1261 1261
      join = u;
1262 1262
    }
1263 1263

	
1264 1264
    // Find the leaving arc of the cycle and returns true if the
1265 1265
    // leaving arc is not the same as the entering arc
1266 1266
    bool findLeavingArc() {
1267 1267
      // Initialize first and second nodes according to the direction
1268 1268
      // of the cycle
1269 1269
      if (_state[in_arc] == STATE_LOWER) {
1270 1270
        first  = _source[in_arc];
1271 1271
        second = _target[in_arc];
1272 1272
      } else {
1273 1273
        first  = _target[in_arc];
1274 1274
        second = _source[in_arc];
1275 1275
      }
1276 1276
      delta = _cap[in_arc];
1277 1277
      int result = 0;
1278
      Flow d;
1278
      Value d;
1279 1279
      int e;
1280 1280

	
1281 1281
      // Search the cycle along the path form the first node to the root
1282 1282
      for (int u = first; u != join; u = _parent[u]) {
1283 1283
        e = _pred[u];
1284 1284
        d = _forward[u] ?
1285 1285
          _flow[e] : (_cap[e] == INF ? INF : _cap[e] - _flow[e]);
1286 1286
        if (d < delta) {
1287 1287
          delta = d;
1288 1288
          u_out = u;
1289 1289
          result = 1;
1290 1290
        }
1291 1291
      }
1292 1292
      // Search the cycle along the path form the second node to the root
1293 1293
      for (int u = second; u != join; u = _parent[u]) {
1294 1294
        e = _pred[u];
1295 1295
        d = _forward[u] ? 
1296 1296
          (_cap[e] == INF ? INF : _cap[e] - _flow[e]) : _flow[e];
1297 1297
        if (d <= delta) {
1298 1298
          delta = d;
1299 1299
          u_out = u;
1300 1300
          result = 2;
1301 1301
        }
1302 1302
      }
1303 1303

	
1304 1304
      if (result == 1) {
1305 1305
        u_in = first;
1306 1306
        v_in = second;
1307 1307
      } else {
1308 1308
        u_in = second;
1309 1309
        v_in = first;
1310 1310
      }
1311 1311
      return result != 0;
1312 1312
    }
1313 1313

	
1314 1314
    // Change _flow and _state vectors
1315 1315
    void changeFlow(bool change) {
1316 1316
      // Augment along the cycle
1317 1317
      if (delta > 0) {
1318
        Flow val = _state[in_arc] * delta;
1318
        Value val = _state[in_arc] * delta;
1319 1319
        _flow[in_arc] += val;
1320 1320
        for (int u = _source[in_arc]; u != join; u = _parent[u]) {
1321 1321
          _flow[_pred[u]] += _forward[u] ? -val : val;
1322 1322
        }
1323 1323
        for (int u = _target[in_arc]; u != join; u = _parent[u]) {
1324 1324
          _flow[_pred[u]] += _forward[u] ? val : -val;
1325 1325
        }
1326 1326
      }
1327 1327
      // Update the state of the entering and leaving arcs
1328 1328
      if (change) {
1329 1329
        _state[in_arc] = STATE_TREE;
1330 1330
        _state[_pred[u_out]] =
1331 1331
          (_flow[_pred[u_out]] == 0) ? STATE_LOWER : STATE_UPPER;
1332 1332
      } else {
1333 1333
        _state[in_arc] = -_state[in_arc];
1334 1334
      }
1335 1335
    }
1336 1336

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

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

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

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

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

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

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

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

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

	
1402 1402
      // Update _pred, _forward, _last_succ and _succ_num for the
1403 1403
      // stem nodes from u_out to u_in
1404 1404
      int tmp_sc = 0, tmp_ls = _last_succ[u_out];
1405 1405
      u = u_out;
1406 1406
      while (u != u_in) {
1407 1407
        w = _parent[u];
1408 1408
        _pred[u] = _pred[w];
1409 1409
        _forward[u] = !_forward[w];
1410 1410
        tmp_sc += _succ_num[u] - _succ_num[w];
1411 1411
        _succ_num[u] = tmp_sc;
1412 1412
        _last_succ[w] = tmp_ls;
1413 1413
        u = w;
1414 1414
      }
Ignore white space 192 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_PREFLOW_H
20 20
#define LEMON_PREFLOW_H
21 21

	
22 22
#include <lemon/tolerance.h>
23 23
#include <lemon/elevator.h>
24 24

	
25 25
/// \file
26 26
/// \ingroup max_flow
27 27
/// \brief Implementation of the preflow algorithm.
28 28

	
29 29
namespace lemon {
30 30

	
31 31
  /// \brief Default traits class of Preflow class.
32 32
  ///
33 33
  /// Default traits class of Preflow class.
34 34
  /// \tparam GR Digraph type.
35 35
  /// \tparam CAP Capacity map type.
36 36
  template <typename GR, typename CAP>
37 37
  struct PreflowDefaultTraits {
38 38

	
39 39
    /// \brief The type of the digraph the algorithm runs on.
40 40
    typedef GR Digraph;
41 41

	
42 42
    /// \brief The type of the map that stores the arc capacities.
43 43
    ///
44 44
    /// The type of the map that stores the arc capacities.
45 45
    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
46 46
    typedef CAP CapacityMap;
47 47

	
48 48
    /// \brief The type of the flow values.
49
    typedef typename CapacityMap::Value Flow;
49
    typedef typename CapacityMap::Value Value;
50 50

	
51 51
    /// \brief The type of the map that stores the flow values.
52 52
    ///
53 53
    /// The type of the map that stores the flow values.
54 54
    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
55
    typedef typename Digraph::template ArcMap<Flow> FlowMap;
55
    typedef typename Digraph::template ArcMap<Value> FlowMap;
56 56

	
57 57
    /// \brief Instantiates a FlowMap.
58 58
    ///
59 59
    /// This function instantiates a \ref FlowMap.
60 60
    /// \param digraph The digraph for which we would like to define
61 61
    /// the flow map.
62 62
    static FlowMap* createFlowMap(const Digraph& digraph) {
63 63
      return new FlowMap(digraph);
64 64
    }
65 65

	
66 66
    /// \brief The elevator type used by Preflow algorithm.
67 67
    ///
68 68
    /// The elevator type used by Preflow algorithm.
69 69
    ///
70 70
    /// \sa Elevator
71 71
    /// \sa LinkedElevator
72 72
    typedef LinkedElevator<Digraph, typename Digraph::Node> Elevator;
73 73

	
74 74
    /// \brief Instantiates an Elevator.
75 75
    ///
76 76
    /// This function instantiates an \ref Elevator.
77 77
    /// \param digraph The digraph for which we would like to define
78 78
    /// the elevator.
79 79
    /// \param max_level The maximum level of the elevator.
80 80
    static Elevator* createElevator(const Digraph& digraph, int max_level) {
81 81
      return new Elevator(digraph, max_level);
82 82
    }
83 83

	
84 84
    /// \brief The tolerance used by the algorithm
85 85
    ///
86 86
    /// The tolerance used by the algorithm to handle inexact computation.
87
    typedef lemon::Tolerance<Flow> Tolerance;
87
    typedef lemon::Tolerance<Value> Tolerance;
88 88

	
89 89
  };
90 90

	
91 91

	
92 92
  /// \ingroup max_flow
93 93
  ///
94 94
  /// \brief %Preflow algorithm class.
95 95
  ///
96 96
  /// This class provides an implementation of Goldberg-Tarjan's \e preflow
97 97
  /// \e push-relabel algorithm producing a \ref max_flow
98 98
  /// "flow of maximum value" in a digraph.
99 99
  /// The preflow algorithms are the fastest known maximum
100 100
  /// flow algorithms. The current implementation use a mixture of the
101 101
  /// \e "highest label" and the \e "bound decrease" heuristics.
102 102
  /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
103 103
  ///
104 104
  /// The algorithm consists of two phases. After the first phase
105 105
  /// the maximum flow value and the minimum cut is obtained. The
106 106
  /// second phase constructs a feasible maximum flow on each arc.
107 107
  ///
108 108
  /// \tparam GR The type of the digraph the algorithm runs on.
109 109
  /// \tparam CAP The type of the capacity map. The default map
110 110
  /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
111 111
#ifdef DOXYGEN
112 112
  template <typename GR, typename CAP, typename TR>
113 113
#else
114 114
  template <typename GR,
115 115
            typename CAP = typename GR::template ArcMap<int>,
116 116
            typename TR = PreflowDefaultTraits<GR, CAP> >
117 117
#endif
118 118
  class Preflow {
119 119
  public:
120 120

	
121 121
    ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
122 122
    typedef TR Traits;
123 123
    ///The type of the digraph the algorithm runs on.
124 124
    typedef typename Traits::Digraph Digraph;
125 125
    ///The type of the capacity map.
126 126
    typedef typename Traits::CapacityMap CapacityMap;
127 127
    ///The type of the flow values.
128
    typedef typename Traits::Flow Flow;
128
    typedef typename Traits::Value Value;
129 129

	
130 130
    ///The type of the flow map.
131 131
    typedef typename Traits::FlowMap FlowMap;
132 132
    ///The type of the elevator.
133 133
    typedef typename Traits::Elevator Elevator;
134 134
    ///The type of the tolerance.
135 135
    typedef typename Traits::Tolerance Tolerance;
136 136

	
137 137
  private:
138 138

	
139 139
    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
140 140

	
141 141
    const Digraph& _graph;
142 142
    const CapacityMap* _capacity;
143 143

	
144 144
    int _node_num;
145 145

	
146 146
    Node _source, _target;
147 147

	
148 148
    FlowMap* _flow;
149 149
    bool _local_flow;
150 150

	
151 151
    Elevator* _level;
152 152
    bool _local_level;
153 153

	
154
    typedef typename Digraph::template NodeMap<Flow> ExcessMap;
154
    typedef typename Digraph::template NodeMap<Value> ExcessMap;
155 155
    ExcessMap* _excess;
156 156

	
157 157
    Tolerance _tolerance;
158 158

	
159 159
    bool _phase;
160 160

	
161 161

	
162 162
    void createStructures() {
163 163
      _node_num = countNodes(_graph);
164 164

	
165 165
      if (!_flow) {
166 166
        _flow = Traits::createFlowMap(_graph);
167 167
        _local_flow = true;
168 168
      }
169 169
      if (!_level) {
170 170
        _level = Traits::createElevator(_graph, _node_num);
171 171
        _local_level = true;
172 172
      }
173 173
      if (!_excess) {
174 174
        _excess = new ExcessMap(_graph);
175 175
      }
176 176
    }
177 177

	
178 178
    void destroyStructures() {
179 179
      if (_local_flow) {
180 180
        delete _flow;
181 181
      }
182 182
      if (_local_level) {
183 183
        delete _level;
184 184
      }
185 185
      if (_excess) {
186 186
        delete _excess;
187 187
      }
188 188
    }
189 189

	
190 190
  public:
191 191

	
192 192
    typedef Preflow Create;
193 193

	
194 194
    ///\name Named Template Parameters
195 195

	
196 196
    ///@{
197 197

	
198 198
    template <typename T>
199 199
    struct SetFlowMapTraits : public Traits {
200 200
      typedef T FlowMap;
201 201
      static FlowMap *createFlowMap(const Digraph&) {
202 202
        LEMON_ASSERT(false, "FlowMap is not initialized");
203 203
        return 0; // ignore warnings
204 204
      }
205 205
    };
206 206

	
207 207
    /// \brief \ref named-templ-param "Named parameter" for setting
208 208
    /// FlowMap type
209 209
    ///
210 210
    /// \ref named-templ-param "Named parameter" for setting FlowMap
211 211
    /// type.
212 212
    template <typename T>
213 213
    struct SetFlowMap
214 214
      : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<T> > {
215 215
      typedef Preflow<Digraph, CapacityMap,
216 216
                      SetFlowMapTraits<T> > Create;
217 217
    };
218 218

	
219 219
    template <typename T>
220 220
    struct SetElevatorTraits : public Traits {
221 221
      typedef T Elevator;
222 222
      static Elevator *createElevator(const Digraph&, int) {
223 223
        LEMON_ASSERT(false, "Elevator is not initialized");
224 224
        return 0; // ignore warnings
225 225
      }
226 226
    };
227 227

	
228 228
    /// \brief \ref named-templ-param "Named parameter" for setting
229 229
    /// Elevator type
230 230
    ///
231 231
    /// \ref named-templ-param "Named parameter" for setting Elevator
232 232
    /// type. If this named parameter is used, then an external
233 233
    /// elevator object must be passed to the algorithm using the
234 234
    /// \ref elevator(Elevator&) "elevator()" function before calling
235 235
    /// \ref run() or \ref init().
236 236
    /// \sa SetStandardElevator
237 237
    template <typename T>
238 238
    struct SetElevator
239 239
      : public Preflow<Digraph, CapacityMap, SetElevatorTraits<T> > {
240 240
      typedef Preflow<Digraph, CapacityMap,
241 241
                      SetElevatorTraits<T> > Create;
242 242
    };
243 243

	
244 244
    template <typename T>
245 245
    struct SetStandardElevatorTraits : public Traits {
246 246
      typedef T Elevator;
247 247
      static Elevator *createElevator(const Digraph& digraph, int max_level) {
248 248
        return new Elevator(digraph, max_level);
249 249
      }
250 250
    };
... ...
@@ -377,589 +377,589 @@
377 377
    Preflow& tolerance(const Tolerance& tolerance) const {
378 378
      _tolerance = tolerance;
379 379
      return *this;
380 380
    }
381 381

	
382 382
    /// \brief Returns a const reference to the tolerance.
383 383
    ///
384 384
    /// Returns a const reference to the tolerance.
385 385
    const Tolerance& tolerance() const {
386 386
      return tolerance;
387 387
    }
388 388

	
389 389
    /// \name Execution Control
390 390
    /// The simplest way to execute the preflow algorithm is to use
391 391
    /// \ref run() or \ref runMinCut().\n
392 392
    /// If you need more control on the initial solution or the execution,
393 393
    /// first you have to call one of the \ref init() functions, then
394 394
    /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
395 395

	
396 396
    ///@{
397 397

	
398 398
    /// \brief Initializes the internal data structures.
399 399
    ///
400 400
    /// Initializes the internal data structures and sets the initial
401 401
    /// flow to zero on each arc.
402 402
    void init() {
403 403
      createStructures();
404 404

	
405 405
      _phase = true;
406 406
      for (NodeIt n(_graph); n != INVALID; ++n) {
407 407
        (*_excess)[n] = 0;
408 408
      }
409 409

	
410 410
      for (ArcIt e(_graph); e != INVALID; ++e) {
411 411
        _flow->set(e, 0);
412 412
      }
413 413

	
414 414
      typename Digraph::template NodeMap<bool> reached(_graph, false);
415 415

	
416 416
      _level->initStart();
417 417
      _level->initAddItem(_target);
418 418

	
419 419
      std::vector<Node> queue;
420 420
      reached[_source] = true;
421 421

	
422 422
      queue.push_back(_target);
423 423
      reached[_target] = true;
424 424
      while (!queue.empty()) {
425 425
        _level->initNewLevel();
426 426
        std::vector<Node> nqueue;
427 427
        for (int i = 0; i < int(queue.size()); ++i) {
428 428
          Node n = queue[i];
429 429
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
430 430
            Node u = _graph.source(e);
431 431
            if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
432 432
              reached[u] = true;
433 433
              _level->initAddItem(u);
434 434
              nqueue.push_back(u);
435 435
            }
436 436
          }
437 437
        }
438 438
        queue.swap(nqueue);
439 439
      }
440 440
      _level->initFinish();
441 441

	
442 442
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
443 443
        if (_tolerance.positive((*_capacity)[e])) {
444 444
          Node u = _graph.target(e);
445 445
          if ((*_level)[u] == _level->maxLevel()) continue;
446 446
          _flow->set(e, (*_capacity)[e]);
447 447
          (*_excess)[u] += (*_capacity)[e];
448 448
          if (u != _target && !_level->active(u)) {
449 449
            _level->activate(u);
450 450
          }
451 451
        }
452 452
      }
453 453
    }
454 454

	
455 455
    /// \brief Initializes the internal data structures using the
456 456
    /// given flow map.
457 457
    ///
458 458
    /// Initializes the internal data structures and sets the initial
459 459
    /// flow to the given \c flowMap. The \c flowMap should contain a
460 460
    /// flow or at least a preflow, i.e. at each node excluding the
461 461
    /// source node the incoming flow should greater or equal to the
462 462
    /// outgoing flow.
463 463
    /// \return \c false if the given \c flowMap is not a preflow.
464 464
    template <typename FlowMap>
465 465
    bool init(const FlowMap& flowMap) {
466 466
      createStructures();
467 467

	
468 468
      for (ArcIt e(_graph); e != INVALID; ++e) {
469 469
        _flow->set(e, flowMap[e]);
470 470
      }
471 471

	
472 472
      for (NodeIt n(_graph); n != INVALID; ++n) {
473
        Flow excess = 0;
473
        Value excess = 0;
474 474
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
475 475
          excess += (*_flow)[e];
476 476
        }
477 477
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
478 478
          excess -= (*_flow)[e];
479 479
        }
480 480
        if (excess < 0 && n != _source) return false;
481 481
        (*_excess)[n] = excess;
482 482
      }
483 483

	
484 484
      typename Digraph::template NodeMap<bool> reached(_graph, false);
485 485

	
486 486
      _level->initStart();
487 487
      _level->initAddItem(_target);
488 488

	
489 489
      std::vector<Node> queue;
490 490
      reached[_source] = true;
491 491

	
492 492
      queue.push_back(_target);
493 493
      reached[_target] = true;
494 494
      while (!queue.empty()) {
495 495
        _level->initNewLevel();
496 496
        std::vector<Node> nqueue;
497 497
        for (int i = 0; i < int(queue.size()); ++i) {
498 498
          Node n = queue[i];
499 499
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
500 500
            Node u = _graph.source(e);
501 501
            if (!reached[u] &&
502 502
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
503 503
              reached[u] = true;
504 504
              _level->initAddItem(u);
505 505
              nqueue.push_back(u);
506 506
            }
507 507
          }
508 508
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
509 509
            Node v = _graph.target(e);
510 510
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
511 511
              reached[v] = true;
512 512
              _level->initAddItem(v);
513 513
              nqueue.push_back(v);
514 514
            }
515 515
          }
516 516
        }
517 517
        queue.swap(nqueue);
518 518
      }
519 519
      _level->initFinish();
520 520

	
521 521
      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
522
        Flow rem = (*_capacity)[e] - (*_flow)[e];
522
        Value rem = (*_capacity)[e] - (*_flow)[e];
523 523
        if (_tolerance.positive(rem)) {
524 524
          Node u = _graph.target(e);
525 525
          if ((*_level)[u] == _level->maxLevel()) continue;
526 526
          _flow->set(e, (*_capacity)[e]);
527 527
          (*_excess)[u] += rem;
528 528
          if (u != _target && !_level->active(u)) {
529 529
            _level->activate(u);
530 530
          }
531 531
        }
532 532
      }
533 533
      for (InArcIt e(_graph, _source); e != INVALID; ++e) {
534
        Flow rem = (*_flow)[e];
534
        Value rem = (*_flow)[e];
535 535
        if (_tolerance.positive(rem)) {
536 536
          Node v = _graph.source(e);
537 537
          if ((*_level)[v] == _level->maxLevel()) continue;
538 538
          _flow->set(e, 0);
539 539
          (*_excess)[v] += rem;
540 540
          if (v != _target && !_level->active(v)) {
541 541
            _level->activate(v);
542 542
          }
543 543
        }
544 544
      }
545 545
      return true;
546 546
    }
547 547

	
548 548
    /// \brief Starts the first phase of the preflow algorithm.
549 549
    ///
550 550
    /// The preflow algorithm consists of two phases, this method runs
551 551
    /// the first phase. After the first phase the maximum flow value
552 552
    /// and a minimum value cut can already be computed, although a
553 553
    /// maximum flow is not yet obtained. So after calling this method
554 554
    /// \ref flowValue() returns the value of a maximum flow and \ref
555 555
    /// minCut() returns a minimum cut.
556 556
    /// \pre One of the \ref init() functions must be called before
557 557
    /// using this function.
558 558
    void startFirstPhase() {
559 559
      _phase = true;
560 560

	
561 561
      Node n = _level->highestActive();
562 562
      int level = _level->highestActiveLevel();
563 563
      while (n != INVALID) {
564 564
        int num = _node_num;
565 565

	
566 566
        while (num > 0 && n != INVALID) {
567
          Flow excess = (*_excess)[n];
567
          Value excess = (*_excess)[n];
568 568
          int new_level = _level->maxLevel();
569 569

	
570 570
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
571
            Flow rem = (*_capacity)[e] - (*_flow)[e];
571
            Value rem = (*_capacity)[e] - (*_flow)[e];
572 572
            if (!_tolerance.positive(rem)) continue;
573 573
            Node v = _graph.target(e);
574 574
            if ((*_level)[v] < level) {
575 575
              if (!_level->active(v) && v != _target) {
576 576
                _level->activate(v);
577 577
              }
578 578
              if (!_tolerance.less(rem, excess)) {
579 579
                _flow->set(e, (*_flow)[e] + excess);
580 580
                (*_excess)[v] += excess;
581 581
                excess = 0;
582 582
                goto no_more_push_1;
583 583
              } else {
584 584
                excess -= rem;
585 585
                (*_excess)[v] += rem;
586 586
                _flow->set(e, (*_capacity)[e]);
587 587
              }
588 588
            } else if (new_level > (*_level)[v]) {
589 589
              new_level = (*_level)[v];
590 590
            }
591 591
          }
592 592

	
593 593
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
594
            Flow rem = (*_flow)[e];
594
            Value rem = (*_flow)[e];
595 595
            if (!_tolerance.positive(rem)) continue;
596 596
            Node v = _graph.source(e);
597 597
            if ((*_level)[v] < level) {
598 598
              if (!_level->active(v) && v != _target) {
599 599
                _level->activate(v);
600 600
              }
601 601
              if (!_tolerance.less(rem, excess)) {
602 602
                _flow->set(e, (*_flow)[e] - excess);
603 603
                (*_excess)[v] += excess;
604 604
                excess = 0;
605 605
                goto no_more_push_1;
606 606
              } else {
607 607
                excess -= rem;
608 608
                (*_excess)[v] += rem;
609 609
                _flow->set(e, 0);
610 610
              }
611 611
            } else if (new_level > (*_level)[v]) {
612 612
              new_level = (*_level)[v];
613 613
            }
614 614
          }
615 615

	
616 616
        no_more_push_1:
617 617

	
618 618
          (*_excess)[n] = excess;
619 619

	
620 620
          if (excess != 0) {
621 621
            if (new_level + 1 < _level->maxLevel()) {
622 622
              _level->liftHighestActive(new_level + 1);
623 623
            } else {
624 624
              _level->liftHighestActiveToTop();
625 625
            }
626 626
            if (_level->emptyLevel(level)) {
627 627
              _level->liftToTop(level);
628 628
            }
629 629
          } else {
630 630
            _level->deactivate(n);
631 631
          }
632 632

	
633 633
          n = _level->highestActive();
634 634
          level = _level->highestActiveLevel();
635 635
          --num;
636 636
        }
637 637

	
638 638
        num = _node_num * 20;
639 639
        while (num > 0 && n != INVALID) {
640
          Flow excess = (*_excess)[n];
640
          Value excess = (*_excess)[n];
641 641
          int new_level = _level->maxLevel();
642 642

	
643 643
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
644
            Flow rem = (*_capacity)[e] - (*_flow)[e];
644
            Value rem = (*_capacity)[e] - (*_flow)[e];
645 645
            if (!_tolerance.positive(rem)) continue;
646 646
            Node v = _graph.target(e);
647 647
            if ((*_level)[v] < level) {
648 648
              if (!_level->active(v) && v != _target) {
649 649
                _level->activate(v);
650 650
              }
651 651
              if (!_tolerance.less(rem, excess)) {
652 652
                _flow->set(e, (*_flow)[e] + excess);
653 653
                (*_excess)[v] += excess;
654 654
                excess = 0;
655 655
                goto no_more_push_2;
656 656
              } else {
657 657
                excess -= rem;
658 658
                (*_excess)[v] += rem;
659 659
                _flow->set(e, (*_capacity)[e]);
660 660
              }
661 661
            } else if (new_level > (*_level)[v]) {
662 662
              new_level = (*_level)[v];
663 663
            }
664 664
          }
665 665

	
666 666
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
667
            Flow rem = (*_flow)[e];
667
            Value rem = (*_flow)[e];
668 668
            if (!_tolerance.positive(rem)) continue;
669 669
            Node v = _graph.source(e);
670 670
            if ((*_level)[v] < level) {
671 671
              if (!_level->active(v) && v != _target) {
672 672
                _level->activate(v);
673 673
              }
674 674
              if (!_tolerance.less(rem, excess)) {
675 675
                _flow->set(e, (*_flow)[e] - excess);
676 676
                (*_excess)[v] += excess;
677 677
                excess = 0;
678 678
                goto no_more_push_2;
679 679
              } else {
680 680
                excess -= rem;
681 681
                (*_excess)[v] += rem;
682 682
                _flow->set(e, 0);
683 683
              }
684 684
            } else if (new_level > (*_level)[v]) {
685 685
              new_level = (*_level)[v];
686 686
            }
687 687
          }
688 688

	
689 689
        no_more_push_2:
690 690

	
691 691
          (*_excess)[n] = excess;
692 692

	
693 693
          if (excess != 0) {
694 694
            if (new_level + 1 < _level->maxLevel()) {
695 695
              _level->liftActiveOn(level, new_level + 1);
696 696
            } else {
697 697
              _level->liftActiveToTop(level);
698 698
            }
699 699
            if (_level->emptyLevel(level)) {
700 700
              _level->liftToTop(level);
701 701
            }
702 702
          } else {
703 703
            _level->deactivate(n);
704 704
          }
705 705

	
706 706
          while (level >= 0 && _level->activeFree(level)) {
707 707
            --level;
708 708
          }
709 709
          if (level == -1) {
710 710
            n = _level->highestActive();
711 711
            level = _level->highestActiveLevel();
712 712
          } else {
713 713
            n = _level->activeOn(level);
714 714
          }
715 715
          --num;
716 716
        }
717 717
      }
718 718
    }
719 719

	
720 720
    /// \brief Starts the second phase of the preflow algorithm.
721 721
    ///
722 722
    /// The preflow algorithm consists of two phases, this method runs
723 723
    /// the second phase. After calling one of the \ref init() functions
724 724
    /// and \ref startFirstPhase() and then \ref startSecondPhase(),
725 725
    /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
726 726
    /// value of a maximum flow, \ref minCut() returns a minimum cut
727 727
    /// \pre One of the \ref init() functions and \ref startFirstPhase()
728 728
    /// must be called before using this function.
729 729
    void startSecondPhase() {
730 730
      _phase = false;
731 731

	
732 732
      typename Digraph::template NodeMap<bool> reached(_graph);
733 733
      for (NodeIt n(_graph); n != INVALID; ++n) {
734 734
        reached[n] = (*_level)[n] < _level->maxLevel();
735 735
      }
736 736

	
737 737
      _level->initStart();
738 738
      _level->initAddItem(_source);
739 739

	
740 740
      std::vector<Node> queue;
741 741
      queue.push_back(_source);
742 742
      reached[_source] = true;
743 743

	
744 744
      while (!queue.empty()) {
745 745
        _level->initNewLevel();
746 746
        std::vector<Node> nqueue;
747 747
        for (int i = 0; i < int(queue.size()); ++i) {
748 748
          Node n = queue[i];
749 749
          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
750 750
            Node v = _graph.target(e);
751 751
            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
752 752
              reached[v] = true;
753 753
              _level->initAddItem(v);
754 754
              nqueue.push_back(v);
755 755
            }
756 756
          }
757 757
          for (InArcIt e(_graph, n); e != INVALID; ++e) {
758 758
            Node u = _graph.source(e);
759 759
            if (!reached[u] &&
760 760
                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
761 761
              reached[u] = true;
762 762
              _level->initAddItem(u);
763 763
              nqueue.push_back(u);
764 764
            }
765 765
          }
766 766
        }
767 767
        queue.swap(nqueue);
768 768
      }
769 769
      _level->initFinish();
770 770

	
771 771
      for (NodeIt n(_graph); n != INVALID; ++n) {
772 772
        if (!reached[n]) {
773 773
          _level->dirtyTopButOne(n);
774 774
        } else if ((*_excess)[n] > 0 && _target != n) {
775 775
          _level->activate(n);
776 776
        }
777 777
      }
778 778

	
779 779
      Node n;
780 780
      while ((n = _level->highestActive()) != INVALID) {
781
        Flow excess = (*_excess)[n];
781
        Value excess = (*_excess)[n];
782 782
        int level = _level->highestActiveLevel();
783 783
        int new_level = _level->maxLevel();
784 784

	
785 785
        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
786
          Flow rem = (*_capacity)[e] - (*_flow)[e];
786
          Value rem = (*_capacity)[e] - (*_flow)[e];
787 787
          if (!_tolerance.positive(rem)) continue;
788 788
          Node v = _graph.target(e);
789 789
          if ((*_level)[v] < level) {
790 790
            if (!_level->active(v) && v != _source) {
791 791
              _level->activate(v);
792 792
            }
793 793
            if (!_tolerance.less(rem, excess)) {
794 794
              _flow->set(e, (*_flow)[e] + excess);
795 795
              (*_excess)[v] += excess;
796 796
              excess = 0;
797 797
              goto no_more_push;
798 798
            } else {
799 799
              excess -= rem;
800 800
              (*_excess)[v] += rem;
801 801
              _flow->set(e, (*_capacity)[e]);
802 802
            }
803 803
          } else if (new_level > (*_level)[v]) {
804 804
            new_level = (*_level)[v];
805 805
          }
806 806
        }
807 807

	
808 808
        for (InArcIt e(_graph, n); e != INVALID; ++e) {
809
          Flow rem = (*_flow)[e];
809
          Value rem = (*_flow)[e];
810 810
          if (!_tolerance.positive(rem)) continue;
811 811
          Node v = _graph.source(e);
812 812
          if ((*_level)[v] < level) {
813 813
            if (!_level->active(v) && v != _source) {
814 814
              _level->activate(v);
815 815
            }
816 816
            if (!_tolerance.less(rem, excess)) {
817 817
              _flow->set(e, (*_flow)[e] - excess);
818 818
              (*_excess)[v] += excess;
819 819
              excess = 0;
820 820
              goto no_more_push;
821 821
            } else {
822 822
              excess -= rem;
823 823
              (*_excess)[v] += rem;
824 824
              _flow->set(e, 0);
825 825
            }
826 826
          } else if (new_level > (*_level)[v]) {
827 827
            new_level = (*_level)[v];
828 828
          }
829 829
        }
830 830

	
831 831
      no_more_push:
832 832

	
833 833
        (*_excess)[n] = excess;
834 834

	
835 835
        if (excess != 0) {
836 836
          if (new_level + 1 < _level->maxLevel()) {
837 837
            _level->liftHighestActive(new_level + 1);
838 838
          } else {
839 839
            // Calculation error
840 840
            _level->liftHighestActiveToTop();
841 841
          }
842 842
          if (_level->emptyLevel(level)) {
843 843
            // Calculation error
844 844
            _level->liftToTop(level);
845 845
          }
846 846
        } else {
847 847
          _level->deactivate(n);
848 848
        }
849 849

	
850 850
      }
851 851
    }
852 852

	
853 853
    /// \brief Runs the preflow algorithm.
854 854
    ///
855 855
    /// Runs the preflow algorithm.
856 856
    /// \note pf.run() is just a shortcut of the following code.
857 857
    /// \code
858 858
    ///   pf.init();
859 859
    ///   pf.startFirstPhase();
860 860
    ///   pf.startSecondPhase();
861 861
    /// \endcode
862 862
    void run() {
863 863
      init();
864 864
      startFirstPhase();
865 865
      startSecondPhase();
866 866
    }
867 867

	
868 868
    /// \brief Runs the preflow algorithm to compute the minimum cut.
869 869
    ///
870 870
    /// Runs the preflow algorithm to compute the minimum cut.
871 871
    /// \note pf.runMinCut() is just a shortcut of the following code.
872 872
    /// \code
873 873
    ///   pf.init();
874 874
    ///   pf.startFirstPhase();
875 875
    /// \endcode
876 876
    void runMinCut() {
877 877
      init();
878 878
      startFirstPhase();
879 879
    }
880 880

	
881 881
    /// @}
882 882

	
883 883
    /// \name Query Functions
884 884
    /// The results of the preflow algorithm can be obtained using these
885 885
    /// functions.\n
886 886
    /// Either one of the \ref run() "run*()" functions or one of the
887 887
    /// \ref startFirstPhase() "start*()" functions should be called
888 888
    /// before using them.
889 889

	
890 890
    ///@{
891 891

	
892 892
    /// \brief Returns the value of the maximum flow.
893 893
    ///
894 894
    /// Returns the value of the maximum flow by returning the excess
895 895
    /// of the target node. This value equals to the value of
896 896
    /// the maximum flow already after the first phase of the algorithm.
897 897
    ///
898 898
    /// \pre Either \ref run() or \ref init() must be called before
899 899
    /// using this function.
900
    Flow flowValue() const {
900
    Value flowValue() const {
901 901
      return (*_excess)[_target];
902 902
    }
903 903

	
904
    /// \brief Returns the flow on the given arc.
904
    /// \brief Returns the flow value on the given arc.
905 905
    ///
906
    /// Returns the flow on the given arc. This method can
906
    /// Returns the flow value on the given arc. This method can
907 907
    /// be called after the second phase of the algorithm.
908 908
    ///
909 909
    /// \pre Either \ref run() or \ref init() must be called before
910 910
    /// using this function.
911
    Flow flow(const Arc& arc) const {
911
    Value flow(const Arc& arc) const {
912 912
      return (*_flow)[arc];
913 913
    }
914 914

	
915 915
    /// \brief Returns a const reference to the flow map.
916 916
    ///
917 917
    /// Returns a const reference to the arc map storing the found flow.
918 918
    /// This method can be called after the second phase of the algorithm.
919 919
    ///
920 920
    /// \pre Either \ref run() or \ref init() must be called before
921 921
    /// using this function.
922 922
    const FlowMap& flowMap() const {
923 923
      return *_flow;
924 924
    }
925 925

	
926 926
    /// \brief Returns \c true when the node is on the source side of the
927 927
    /// minimum cut.
928 928
    ///
929 929
    /// Returns true when the node is on the source side of the found
930 930
    /// minimum cut. This method can be called both after running \ref
931 931
    /// startFirstPhase() and \ref startSecondPhase().
932 932
    ///
933 933
    /// \pre Either \ref run() or \ref init() must be called before
934 934
    /// using this function.
935 935
    bool minCut(const Node& node) const {
936 936
      return ((*_level)[node] == _level->maxLevel()) == _phase;
937 937
    }
938 938

	
939 939
    /// \brief Gives back a minimum value cut.
940 940
    ///
941 941
    /// Sets \c cutMap to the characteristic vector of a minimum value
942 942
    /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
943 943
    /// node map with \c bool (or convertible) value type.
944 944
    ///
945 945
    /// This method can be called both after running \ref startFirstPhase()
946 946
    /// and \ref startSecondPhase(). The result after the second phase
947 947
    /// could be slightly different if inexact computation is used.
948 948
    ///
949 949
    /// \note This function calls \ref minCut() for each node, so it runs in
950 950
    /// O(n) time.
951 951
    ///
952 952
    /// \pre Either \ref run() or \ref init() must be called before
953 953
    /// using this function.
954 954
    template <typename CutMap>
955 955
    void minCutMap(CutMap& cutMap) const {
956 956
      for (NodeIt n(_graph); n != INVALID; ++n) {
957 957
        cutMap.set(n, minCut(n));
958 958
      }
959 959
    }
960 960

	
961 961
    /// @}
962 962
  };
963 963
}
964 964

	
965 965
#endif
0 comments (0 inline)