COIN-OR::LEMON - Graph Library

source: lemon-1.2/lemon/preflow.h @ 772:f964a00b9068

Last change on this file since 772:f964a00b9068 was 755:134852d7fb0a, checked in by Peter Kovacs <kpeter@…>, 10 years ago

Insert citations into the doc (#184)

  • Add general citations to modules.
  • Add specific citations for max flow and min cost flow algorithms.
  • Add citations for the supported LP and MIP solvers.
  • Extend the main page.
  • Replace inproceedings entries with the journal versions.
  • Add a new bibtex entry about network simplex.
  • Remove unwanted entries.
File size: 29.9 KB
RevLine 
[389]1/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library.
4 *
[440]5 * Copyright (C) 2003-2009
[389]6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
12 *
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_PREFLOW_H
20#define LEMON_PREFLOW_H
21
22#include <lemon/tolerance.h>
23#include <lemon/elevator.h>
24
25/// \file
26/// \ingroup max_flow
27/// \brief Implementation of the preflow algorithm.
28
29namespace lemon {
30
31  /// \brief Default traits class of Preflow class.
32  ///
33  /// Default traits class of Preflow class.
[492]34  /// \tparam GR Digraph type.
[559]35  /// \tparam CAP Capacity map type.
36  template <typename GR, typename CAP>
[389]37  struct PreflowDefaultTraits {
38
[393]39    /// \brief The type of the digraph the algorithm runs on.
[492]40    typedef GR Digraph;
[389]41
42    /// \brief The type of the map that stores the arc capacities.
43    ///
44    /// The type of the map that stores the arc capacities.
45    /// It must meet the \ref concepts::ReadMap "ReadMap" concept.
[559]46    typedef CAP CapacityMap;
[389]47
[393]48    /// \brief The type of the flow values.
[641]49    typedef typename CapacityMap::Value Value;
[389]50
[393]51    /// \brief The type of the map that stores the flow values.
[389]52    ///
[393]53    /// The type of the map that stores the flow values.
[389]54    /// It must meet the \ref concepts::ReadWriteMap "ReadWriteMap" concept.
[713]55#ifdef DOXYGEN
56    typedef GR::ArcMap<Value> FlowMap;
57#else
[641]58    typedef typename Digraph::template ArcMap<Value> FlowMap;
[713]59#endif
[389]60
61    /// \brief Instantiates a FlowMap.
62    ///
63    /// This function instantiates a \ref FlowMap.
[610]64    /// \param digraph The digraph for which we would like to define
[389]65    /// the flow map.
66    static FlowMap* createFlowMap(const Digraph& digraph) {
67      return new FlowMap(digraph);
68    }
69
[393]70    /// \brief The elevator type used by Preflow algorithm.
[389]71    ///
72    /// The elevator type used by Preflow algorithm.
73    ///
[713]74    /// \sa Elevator, LinkedElevator
75#ifdef DOXYGEN
76    typedef lemon::Elevator<GR, GR::Node> Elevator;
77#else
78    typedef lemon::Elevator<Digraph, typename Digraph::Node> Elevator;
79#endif
[389]80
81    /// \brief Instantiates an Elevator.
82    ///
[393]83    /// This function instantiates an \ref Elevator.
[610]84    /// \param digraph The digraph for which we would like to define
[389]85    /// the elevator.
86    /// \param max_level The maximum level of the elevator.
87    static Elevator* createElevator(const Digraph& digraph, int max_level) {
88      return new Elevator(digraph, max_level);
89    }
90
91    /// \brief The tolerance used by the algorithm
92    ///
93    /// The tolerance used by the algorithm to handle inexact computation.
[641]94    typedef lemon::Tolerance<Value> Tolerance;
[389]95
96  };
97
98
99  /// \ingroup max_flow
100  ///
[393]101  /// \brief %Preflow algorithm class.
[389]102  ///
[393]103  /// This class provides an implementation of Goldberg-Tarjan's \e preflow
[559]104  /// \e push-relabel algorithm producing a \ref max_flow
[755]105  /// "flow of maximum value" in a digraph \ref clrs01algorithms,
106  /// \ref amo93networkflows, \ref goldberg88newapproach.
[559]107  /// The preflow algorithms are the fastest known maximum
[689]108  /// flow algorithms. The current implementation uses a mixture of the
[389]109  /// \e "highest label" and the \e "bound decrease" heuristics.
110  /// The worst case time complexity of the algorithm is \f$O(n^2\sqrt{e})\f$.
111  ///
[393]112  /// The algorithm consists of two phases. After the first phase
113  /// the maximum flow value and the minimum cut is obtained. The
114  /// second phase constructs a feasible maximum flow on each arc.
[389]115  ///
[492]116  /// \tparam GR The type of the digraph the algorithm runs on.
[559]117  /// \tparam CAP The type of the capacity map. The default map
[492]118  /// type is \ref concepts::Digraph::ArcMap "GR::ArcMap<int>".
[389]119#ifdef DOXYGEN
[559]120  template <typename GR, typename CAP, typename TR>
[389]121#else
[492]122  template <typename GR,
[559]123            typename CAP = typename GR::template ArcMap<int>,
124            typename TR = PreflowDefaultTraits<GR, CAP> >
[389]125#endif
126  class Preflow {
127  public:
128
[393]129    ///The \ref PreflowDefaultTraits "traits class" of the algorithm.
[492]130    typedef TR Traits;
[393]131    ///The type of the digraph the algorithm runs on.
[389]132    typedef typename Traits::Digraph Digraph;
[393]133    ///The type of the capacity map.
[389]134    typedef typename Traits::CapacityMap CapacityMap;
[393]135    ///The type of the flow values.
[641]136    typedef typename Traits::Value Value;
[389]137
[393]138    ///The type of the flow map.
[389]139    typedef typename Traits::FlowMap FlowMap;
[393]140    ///The type of the elevator.
[389]141    typedef typename Traits::Elevator Elevator;
[393]142    ///The type of the tolerance.
[389]143    typedef typename Traits::Tolerance Tolerance;
144
145  private:
146
147    TEMPLATE_DIGRAPH_TYPEDEFS(Digraph);
148
149    const Digraph& _graph;
150    const CapacityMap* _capacity;
151
152    int _node_num;
153
154    Node _source, _target;
155
156    FlowMap* _flow;
157    bool _local_flow;
158
159    Elevator* _level;
160    bool _local_level;
161
[641]162    typedef typename Digraph::template NodeMap<Value> ExcessMap;
[389]163    ExcessMap* _excess;
164
165    Tolerance _tolerance;
166
167    bool _phase;
168
169
170    void createStructures() {
171      _node_num = countNodes(_graph);
172
173      if (!_flow) {
174        _flow = Traits::createFlowMap(_graph);
175        _local_flow = true;
176      }
177      if (!_level) {
178        _level = Traits::createElevator(_graph, _node_num);
179        _local_level = true;
180      }
181      if (!_excess) {
182        _excess = new ExcessMap(_graph);
183      }
184    }
185
186    void destroyStructures() {
187      if (_local_flow) {
188        delete _flow;
189      }
190      if (_local_level) {
191        delete _level;
192      }
193      if (_excess) {
194        delete _excess;
195      }
196    }
197
198  public:
199
200    typedef Preflow Create;
201
[393]202    ///\name Named Template Parameters
[389]203
204    ///@{
205
[559]206    template <typename T>
[391]207    struct SetFlowMapTraits : public Traits {
[559]208      typedef T FlowMap;
[389]209      static FlowMap *createFlowMap(const Digraph&) {
[390]210        LEMON_ASSERT(false, "FlowMap is not initialized");
211        return 0; // ignore warnings
[389]212      }
213    };
214
215    /// \brief \ref named-templ-param "Named parameter" for setting
216    /// FlowMap type
217    ///
218    /// \ref named-templ-param "Named parameter" for setting FlowMap
[393]219    /// type.
[559]220    template <typename T>
[391]221    struct SetFlowMap
[559]222      : public Preflow<Digraph, CapacityMap, SetFlowMapTraits<T> > {
[389]223      typedef Preflow<Digraph, CapacityMap,
[559]224                      SetFlowMapTraits<T> > Create;
[389]225    };
226
[559]227    template <typename T>
[391]228    struct SetElevatorTraits : public Traits {
[559]229      typedef T Elevator;
[389]230      static Elevator *createElevator(const Digraph&, int) {
[390]231        LEMON_ASSERT(false, "Elevator is not initialized");
232        return 0; // ignore warnings
[389]233      }
234    };
235
236    /// \brief \ref named-templ-param "Named parameter" for setting
237    /// Elevator type
238    ///
239    /// \ref named-templ-param "Named parameter" for setting Elevator
[393]240    /// type. If this named parameter is used, then an external
241    /// elevator object must be passed to the algorithm using the
242    /// \ref elevator(Elevator&) "elevator()" function before calling
243    /// \ref run() or \ref init().
244    /// \sa SetStandardElevator
[559]245    template <typename T>
[391]246    struct SetElevator
[559]247      : public Preflow<Digraph, CapacityMap, SetElevatorTraits<T> > {
[389]248      typedef Preflow<Digraph, CapacityMap,
[559]249                      SetElevatorTraits<T> > Create;
[389]250    };
251
[559]252    template <typename T>
[391]253    struct SetStandardElevatorTraits : public Traits {
[559]254      typedef T Elevator;
[389]255      static Elevator *createElevator(const Digraph& digraph, int max_level) {
256        return new Elevator(digraph, max_level);
257      }
258    };
259
260    /// \brief \ref named-templ-param "Named parameter" for setting
[393]261    /// Elevator type with automatic allocation
[389]262    ///
263    /// \ref named-templ-param "Named parameter" for setting Elevator
[393]264    /// type with automatic allocation.
265    /// The Elevator should have standard constructor interface to be
266    /// able to automatically created by the algorithm (i.e. the
267    /// digraph and the maximum level should be passed to it).
268    /// However an external elevator object could also be passed to the
269    /// algorithm with the \ref elevator(Elevator&) "elevator()" function
270    /// before calling \ref run() or \ref init().
271    /// \sa SetElevator
[559]272    template <typename T>
[391]273    struct SetStandardElevator
[389]274      : public Preflow<Digraph, CapacityMap,
[559]275                       SetStandardElevatorTraits<T> > {
[389]276      typedef Preflow<Digraph, CapacityMap,
[559]277                      SetStandardElevatorTraits<T> > Create;
[389]278    };
279
280    /// @}
281
282  protected:
283
284    Preflow() {}
285
286  public:
287
288
289    /// \brief The constructor of the class.
290    ///
291    /// The constructor of the class.
292    /// \param digraph The digraph the algorithm runs on.
293    /// \param capacity The capacity of the arcs.
294    /// \param source The source node.
295    /// \param target The target node.
296    Preflow(const Digraph& digraph, const CapacityMap& capacity,
[393]297            Node source, Node target)
[389]298      : _graph(digraph), _capacity(&capacity),
299        _node_num(0), _source(source), _target(target),
300        _flow(0), _local_flow(false),
301        _level(0), _local_level(false),
302        _excess(0), _tolerance(), _phase() {}
303
[393]304    /// \brief Destructor.
[389]305    ///
306    /// Destructor.
307    ~Preflow() {
308      destroyStructures();
309    }
310
311    /// \brief Sets the capacity map.
312    ///
313    /// Sets the capacity map.
[393]314    /// \return <tt>(*this)</tt>
[389]315    Preflow& capacityMap(const CapacityMap& map) {
316      _capacity = &map;
317      return *this;
318    }
319
320    /// \brief Sets the flow map.
321    ///
322    /// Sets the flow map.
[393]323    /// If you don't use this function before calling \ref run() or
324    /// \ref init(), an instance will be allocated automatically.
325    /// The destructor deallocates this automatically allocated map,
326    /// of course.
327    /// \return <tt>(*this)</tt>
[389]328    Preflow& flowMap(FlowMap& map) {
329      if (_local_flow) {
330        delete _flow;
331        _local_flow = false;
332      }
333      _flow = &map;
334      return *this;
335    }
336
[393]337    /// \brief Sets the source node.
[389]338    ///
[393]339    /// Sets the source node.
340    /// \return <tt>(*this)</tt>
341    Preflow& source(const Node& node) {
342      _source = node;
343      return *this;
[389]344    }
345
[393]346    /// \brief Sets the target node.
[389]347    ///
[393]348    /// Sets the target node.
349    /// \return <tt>(*this)</tt>
350    Preflow& target(const Node& node) {
351      _target = node;
352      return *this;
353    }
354
355    /// \brief Sets the elevator used by algorithm.
356    ///
357    /// Sets the elevator used by algorithm.
358    /// If you don't use this function before calling \ref run() or
359    /// \ref init(), an instance will be allocated automatically.
360    /// The destructor deallocates this automatically allocated elevator,
361    /// of course.
362    /// \return <tt>(*this)</tt>
[389]363    Preflow& elevator(Elevator& elevator) {
364      if (_local_level) {
365        delete _level;
366        _local_level = false;
367      }
368      _level = &elevator;
369      return *this;
370    }
371
[393]372    /// \brief Returns a const reference to the elevator.
[389]373    ///
[393]374    /// Returns a const reference to the elevator.
375    ///
376    /// \pre Either \ref run() or \ref init() must be called before
377    /// using this function.
[420]378    const Elevator& elevator() const {
[389]379      return *_level;
380    }
381
[689]382    /// \brief Sets the tolerance used by the algorithm.
[389]383    ///
[689]384    /// Sets the tolerance object used by the algorithm.
385    /// \return <tt>(*this)</tt>
[688]386    Preflow& tolerance(const Tolerance& tolerance) {
[389]387      _tolerance = tolerance;
388      return *this;
389    }
390
[393]391    /// \brief Returns a const reference to the tolerance.
[389]392    ///
[689]393    /// Returns a const reference to the tolerance object used by
394    /// the algorithm.
[389]395    const Tolerance& tolerance() const {
[688]396      return _tolerance;
[389]397    }
398
[393]399    /// \name Execution Control
400    /// The simplest way to execute the preflow algorithm is to use
401    /// \ref run() or \ref runMinCut().\n
[713]402    /// If you need better control on the initial solution or the execution,
403    /// you have to call one of the \ref init() functions first, then
[393]404    /// \ref startFirstPhase() and if you need it \ref startSecondPhase().
[389]405
406    ///@{
407
408    /// \brief Initializes the internal data structures.
409    ///
[393]410    /// Initializes the internal data structures and sets the initial
411    /// flow to zero on each arc.
[389]412    void init() {
413      createStructures();
414
415      _phase = true;
416      for (NodeIt n(_graph); n != INVALID; ++n) {
[581]417        (*_excess)[n] = 0;
[389]418      }
419
420      for (ArcIt e(_graph); e != INVALID; ++e) {
421        _flow->set(e, 0);
422      }
423
424      typename Digraph::template NodeMap<bool> reached(_graph, false);
425
426      _level->initStart();
427      _level->initAddItem(_target);
428
429      std::vector<Node> queue;
[581]430      reached[_source] = true;
[389]431
432      queue.push_back(_target);
[581]433      reached[_target] = true;
[389]434      while (!queue.empty()) {
435        _level->initNewLevel();
436        std::vector<Node> nqueue;
437        for (int i = 0; i < int(queue.size()); ++i) {
438          Node n = queue[i];
439          for (InArcIt e(_graph, n); e != INVALID; ++e) {
440            Node u = _graph.source(e);
441            if (!reached[u] && _tolerance.positive((*_capacity)[e])) {
[581]442              reached[u] = true;
[389]443              _level->initAddItem(u);
444              nqueue.push_back(u);
445            }
446          }
447        }
448        queue.swap(nqueue);
449      }
450      _level->initFinish();
451
452      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
453        if (_tolerance.positive((*_capacity)[e])) {
454          Node u = _graph.target(e);
455          if ((*_level)[u] == _level->maxLevel()) continue;
456          _flow->set(e, (*_capacity)[e]);
[581]457          (*_excess)[u] += (*_capacity)[e];
[389]458          if (u != _target && !_level->active(u)) {
459            _level->activate(u);
460          }
461        }
462      }
463    }
464
[393]465    /// \brief Initializes the internal data structures using the
466    /// given flow map.
[389]467    ///
468    /// Initializes the internal data structures and sets the initial
469    /// flow to the given \c flowMap. The \c flowMap should contain a
[393]470    /// flow or at least a preflow, i.e. at each node excluding the
471    /// source node the incoming flow should greater or equal to the
[389]472    /// outgoing flow.
[393]473    /// \return \c false if the given \c flowMap is not a preflow.
[389]474    template <typename FlowMap>
[392]475    bool init(const FlowMap& flowMap) {
[389]476      createStructures();
477
478      for (ArcIt e(_graph); e != INVALID; ++e) {
479        _flow->set(e, flowMap[e]);
480      }
481
482      for (NodeIt n(_graph); n != INVALID; ++n) {
[641]483        Value excess = 0;
[389]484        for (InArcIt e(_graph, n); e != INVALID; ++e) {
485          excess += (*_flow)[e];
486        }
487        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
488          excess -= (*_flow)[e];
489        }
490        if (excess < 0 && n != _source) return false;
[581]491        (*_excess)[n] = excess;
[389]492      }
493
494      typename Digraph::template NodeMap<bool> reached(_graph, false);
495
496      _level->initStart();
497      _level->initAddItem(_target);
498
499      std::vector<Node> queue;
[581]500      reached[_source] = true;
[389]501
502      queue.push_back(_target);
[581]503      reached[_target] = true;
[389]504      while (!queue.empty()) {
505        _level->initNewLevel();
506        std::vector<Node> nqueue;
507        for (int i = 0; i < int(queue.size()); ++i) {
508          Node n = queue[i];
509          for (InArcIt e(_graph, n); e != INVALID; ++e) {
510            Node u = _graph.source(e);
511            if (!reached[u] &&
512                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
[581]513              reached[u] = true;
[389]514              _level->initAddItem(u);
515              nqueue.push_back(u);
516            }
517          }
518          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
519            Node v = _graph.target(e);
520            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
[581]521              reached[v] = true;
[389]522              _level->initAddItem(v);
523              nqueue.push_back(v);
524            }
525          }
526        }
527        queue.swap(nqueue);
528      }
529      _level->initFinish();
530
531      for (OutArcIt e(_graph, _source); e != INVALID; ++e) {
[641]532        Value rem = (*_capacity)[e] - (*_flow)[e];
[389]533        if (_tolerance.positive(rem)) {
534          Node u = _graph.target(e);
535          if ((*_level)[u] == _level->maxLevel()) continue;
536          _flow->set(e, (*_capacity)[e]);
[581]537          (*_excess)[u] += rem;
[389]538          if (u != _target && !_level->active(u)) {
539            _level->activate(u);
540          }
541        }
542      }
543      for (InArcIt e(_graph, _source); e != INVALID; ++e) {
[641]544        Value rem = (*_flow)[e];
[389]545        if (_tolerance.positive(rem)) {
546          Node v = _graph.source(e);
547          if ((*_level)[v] == _level->maxLevel()) continue;
548          _flow->set(e, 0);
[581]549          (*_excess)[v] += rem;
[389]550          if (v != _target && !_level->active(v)) {
551            _level->activate(v);
552          }
553        }
554      }
555      return true;
556    }
557
558    /// \brief Starts the first phase of the preflow algorithm.
559    ///
560    /// The preflow algorithm consists of two phases, this method runs
561    /// the first phase. After the first phase the maximum flow value
562    /// and a minimum value cut can already be computed, although a
563    /// maximum flow is not yet obtained. So after calling this method
564    /// \ref flowValue() returns the value of a maximum flow and \ref
565    /// minCut() returns a minimum cut.
[393]566    /// \pre One of the \ref init() functions must be called before
567    /// using this function.
[389]568    void startFirstPhase() {
569      _phase = true;
570
571      Node n = _level->highestActive();
572      int level = _level->highestActiveLevel();
573      while (n != INVALID) {
574        int num = _node_num;
575
576        while (num > 0 && n != INVALID) {
[641]577          Value excess = (*_excess)[n];
[389]578          int new_level = _level->maxLevel();
579
580          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
[641]581            Value rem = (*_capacity)[e] - (*_flow)[e];
[389]582            if (!_tolerance.positive(rem)) continue;
583            Node v = _graph.target(e);
584            if ((*_level)[v] < level) {
585              if (!_level->active(v) && v != _target) {
586                _level->activate(v);
587              }
588              if (!_tolerance.less(rem, excess)) {
589                _flow->set(e, (*_flow)[e] + excess);
[581]590                (*_excess)[v] += excess;
[389]591                excess = 0;
592                goto no_more_push_1;
593              } else {
594                excess -= rem;
[581]595                (*_excess)[v] += rem;
[389]596                _flow->set(e, (*_capacity)[e]);
597              }
598            } else if (new_level > (*_level)[v]) {
599              new_level = (*_level)[v];
600            }
601          }
602
603          for (InArcIt e(_graph, n); e != INVALID; ++e) {
[641]604            Value rem = (*_flow)[e];
[389]605            if (!_tolerance.positive(rem)) continue;
606            Node v = _graph.source(e);
607            if ((*_level)[v] < level) {
608              if (!_level->active(v) && v != _target) {
609                _level->activate(v);
610              }
611              if (!_tolerance.less(rem, excess)) {
612                _flow->set(e, (*_flow)[e] - excess);
[581]613                (*_excess)[v] += excess;
[389]614                excess = 0;
615                goto no_more_push_1;
616              } else {
617                excess -= rem;
[581]618                (*_excess)[v] += rem;
[389]619                _flow->set(e, 0);
620              }
621            } else if (new_level > (*_level)[v]) {
622              new_level = (*_level)[v];
623            }
624          }
625
626        no_more_push_1:
627
[581]628          (*_excess)[n] = excess;
[389]629
630          if (excess != 0) {
631            if (new_level + 1 < _level->maxLevel()) {
632              _level->liftHighestActive(new_level + 1);
633            } else {
634              _level->liftHighestActiveToTop();
635            }
636            if (_level->emptyLevel(level)) {
637              _level->liftToTop(level);
638            }
639          } else {
640            _level->deactivate(n);
641          }
642
643          n = _level->highestActive();
644          level = _level->highestActiveLevel();
645          --num;
646        }
647
648        num = _node_num * 20;
649        while (num > 0 && n != INVALID) {
[641]650          Value excess = (*_excess)[n];
[389]651          int new_level = _level->maxLevel();
652
653          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
[641]654            Value rem = (*_capacity)[e] - (*_flow)[e];
[389]655            if (!_tolerance.positive(rem)) continue;
656            Node v = _graph.target(e);
657            if ((*_level)[v] < level) {
658              if (!_level->active(v) && v != _target) {
659                _level->activate(v);
660              }
661              if (!_tolerance.less(rem, excess)) {
662                _flow->set(e, (*_flow)[e] + excess);
[581]663                (*_excess)[v] += excess;
[389]664                excess = 0;
665                goto no_more_push_2;
666              } else {
667                excess -= rem;
[581]668                (*_excess)[v] += rem;
[389]669                _flow->set(e, (*_capacity)[e]);
670              }
671            } else if (new_level > (*_level)[v]) {
672              new_level = (*_level)[v];
673            }
674          }
675
676          for (InArcIt e(_graph, n); e != INVALID; ++e) {
[641]677            Value rem = (*_flow)[e];
[389]678            if (!_tolerance.positive(rem)) continue;
679            Node v = _graph.source(e);
680            if ((*_level)[v] < level) {
681              if (!_level->active(v) && v != _target) {
682                _level->activate(v);
683              }
684              if (!_tolerance.less(rem, excess)) {
685                _flow->set(e, (*_flow)[e] - excess);
[581]686                (*_excess)[v] += excess;
[389]687                excess = 0;
688                goto no_more_push_2;
689              } else {
690                excess -= rem;
[581]691                (*_excess)[v] += rem;
[389]692                _flow->set(e, 0);
693              }
694            } else if (new_level > (*_level)[v]) {
695              new_level = (*_level)[v];
696            }
697          }
698
699        no_more_push_2:
700
[581]701          (*_excess)[n] = excess;
[389]702
703          if (excess != 0) {
704            if (new_level + 1 < _level->maxLevel()) {
705              _level->liftActiveOn(level, new_level + 1);
706            } else {
707              _level->liftActiveToTop(level);
708            }
709            if (_level->emptyLevel(level)) {
710              _level->liftToTop(level);
711            }
712          } else {
713            _level->deactivate(n);
714          }
715
716          while (level >= 0 && _level->activeFree(level)) {
717            --level;
718          }
719          if (level == -1) {
720            n = _level->highestActive();
721            level = _level->highestActiveLevel();
722          } else {
723            n = _level->activeOn(level);
724          }
725          --num;
726        }
727      }
728    }
729
730    /// \brief Starts the second phase of the preflow algorithm.
731    ///
732    /// The preflow algorithm consists of two phases, this method runs
[393]733    /// the second phase. After calling one of the \ref init() functions
734    /// and \ref startFirstPhase() and then \ref startSecondPhase(),
735    /// \ref flowMap() returns a maximum flow, \ref flowValue() returns the
[389]736    /// value of a maximum flow, \ref minCut() returns a minimum cut
[393]737    /// \pre One of the \ref init() functions and \ref startFirstPhase()
738    /// must be called before using this function.
[389]739    void startSecondPhase() {
740      _phase = false;
741
742      typename Digraph::template NodeMap<bool> reached(_graph);
743      for (NodeIt n(_graph); n != INVALID; ++n) {
[581]744        reached[n] = (*_level)[n] < _level->maxLevel();
[389]745      }
746
747      _level->initStart();
748      _level->initAddItem(_source);
749
750      std::vector<Node> queue;
751      queue.push_back(_source);
[581]752      reached[_source] = true;
[389]753
754      while (!queue.empty()) {
755        _level->initNewLevel();
756        std::vector<Node> nqueue;
757        for (int i = 0; i < int(queue.size()); ++i) {
758          Node n = queue[i];
759          for (OutArcIt e(_graph, n); e != INVALID; ++e) {
760            Node v = _graph.target(e);
761            if (!reached[v] && _tolerance.positive((*_flow)[e])) {
[581]762              reached[v] = true;
[389]763              _level->initAddItem(v);
764              nqueue.push_back(v);
765            }
766          }
767          for (InArcIt e(_graph, n); e != INVALID; ++e) {
768            Node u = _graph.source(e);
769            if (!reached[u] &&
770                _tolerance.positive((*_capacity)[e] - (*_flow)[e])) {
[581]771              reached[u] = true;
[389]772              _level->initAddItem(u);
773              nqueue.push_back(u);
774            }
775          }
776        }
777        queue.swap(nqueue);
778      }
779      _level->initFinish();
780
781      for (NodeIt n(_graph); n != INVALID; ++n) {
782        if (!reached[n]) {
783          _level->dirtyTopButOne(n);
784        } else if ((*_excess)[n] > 0 && _target != n) {
785          _level->activate(n);
786        }
787      }
788
789      Node n;
790      while ((n = _level->highestActive()) != INVALID) {
[641]791        Value excess = (*_excess)[n];
[389]792        int level = _level->highestActiveLevel();
793        int new_level = _level->maxLevel();
794
795        for (OutArcIt e(_graph, n); e != INVALID; ++e) {
[641]796          Value rem = (*_capacity)[e] - (*_flow)[e];
[389]797          if (!_tolerance.positive(rem)) continue;
798          Node v = _graph.target(e);
799          if ((*_level)[v] < level) {
800            if (!_level->active(v) && v != _source) {
801              _level->activate(v);
802            }
803            if (!_tolerance.less(rem, excess)) {
804              _flow->set(e, (*_flow)[e] + excess);
[581]805              (*_excess)[v] += excess;
[389]806              excess = 0;
807              goto no_more_push;
808            } else {
809              excess -= rem;
[581]810              (*_excess)[v] += rem;
[389]811              _flow->set(e, (*_capacity)[e]);
812            }
813          } else if (new_level > (*_level)[v]) {
814            new_level = (*_level)[v];
815          }
816        }
817
818        for (InArcIt e(_graph, n); e != INVALID; ++e) {
[641]819          Value rem = (*_flow)[e];
[389]820          if (!_tolerance.positive(rem)) continue;
821          Node v = _graph.source(e);
822          if ((*_level)[v] < level) {
823            if (!_level->active(v) && v != _source) {
824              _level->activate(v);
825            }
826            if (!_tolerance.less(rem, excess)) {
827              _flow->set(e, (*_flow)[e] - excess);
[581]828              (*_excess)[v] += excess;
[389]829              excess = 0;
830              goto no_more_push;
831            } else {
832              excess -= rem;
[581]833              (*_excess)[v] += rem;
[389]834              _flow->set(e, 0);
835            }
836          } else if (new_level > (*_level)[v]) {
837            new_level = (*_level)[v];
838          }
839        }
840
841      no_more_push:
842
[581]843        (*_excess)[n] = excess;
[389]844
845        if (excess != 0) {
846          if (new_level + 1 < _level->maxLevel()) {
847            _level->liftHighestActive(new_level + 1);
848          } else {
849            // Calculation error
850            _level->liftHighestActiveToTop();
851          }
852          if (_level->emptyLevel(level)) {
853            // Calculation error
854            _level->liftToTop(level);
855          }
856        } else {
857          _level->deactivate(n);
858        }
859
860      }
861    }
862
863    /// \brief Runs the preflow algorithm.
864    ///
865    /// Runs the preflow algorithm.
866    /// \note pf.run() is just a shortcut of the following code.
867    /// \code
868    ///   pf.init();
869    ///   pf.startFirstPhase();
870    ///   pf.startSecondPhase();
871    /// \endcode
872    void run() {
873      init();
874      startFirstPhase();
875      startSecondPhase();
876    }
877
878    /// \brief Runs the preflow algorithm to compute the minimum cut.
879    ///
880    /// Runs the preflow algorithm to compute the minimum cut.
881    /// \note pf.runMinCut() is just a shortcut of the following code.
882    /// \code
883    ///   pf.init();
884    ///   pf.startFirstPhase();
885    /// \endcode
886    void runMinCut() {
887      init();
888      startFirstPhase();
889    }
890
891    /// @}
892
893    /// \name Query Functions
[393]894    /// The results of the preflow algorithm can be obtained using these
[389]895    /// functions.\n
[393]896    /// Either one of the \ref run() "run*()" functions or one of the
897    /// \ref startFirstPhase() "start*()" functions should be called
898    /// before using them.
[389]899
900    ///@{
901
902    /// \brief Returns the value of the maximum flow.
903    ///
904    /// Returns the value of the maximum flow by returning the excess
[393]905    /// of the target node. This value equals to the value of
906    /// the maximum flow already after the first phase of the algorithm.
907    ///
908    /// \pre Either \ref run() or \ref init() must be called before
909    /// using this function.
[641]910    Value flowValue() const {
[389]911      return (*_excess)[_target];
912    }
913
[641]914    /// \brief Returns the flow value on the given arc.
[389]915    ///
[641]916    /// Returns the flow value on the given arc. This method can
[393]917    /// be called after the second phase of the algorithm.
918    ///
919    /// \pre Either \ref run() or \ref init() must be called before
920    /// using this function.
[641]921    Value flow(const Arc& arc) const {
[393]922      return (*_flow)[arc];
923    }
924
925    /// \brief Returns a const reference to the flow map.
926    ///
927    /// Returns a const reference to the arc map storing the found flow.
928    /// This method can be called after the second phase of the algorithm.
929    ///
930    /// \pre Either \ref run() or \ref init() must be called before
931    /// using this function.
[420]932    const FlowMap& flowMap() const {
[393]933      return *_flow;
934    }
935
936    /// \brief Returns \c true when the node is on the source side of the
937    /// minimum cut.
938    ///
939    /// Returns true when the node is on the source side of the found
940    /// minimum cut. This method can be called both after running \ref
[389]941    /// startFirstPhase() and \ref startSecondPhase().
[393]942    ///
943    /// \pre Either \ref run() or \ref init() must be called before
944    /// using this function.
[389]945    bool minCut(const Node& node) const {
946      return ((*_level)[node] == _level->maxLevel()) == _phase;
947    }
948
[393]949    /// \brief Gives back a minimum value cut.
[389]950    ///
[393]951    /// Sets \c cutMap to the characteristic vector of a minimum value
952    /// cut. \c cutMap should be a \ref concepts::WriteMap "writable"
953    /// node map with \c bool (or convertible) value type.
954    ///
955    /// This method can be called both after running \ref startFirstPhase()
956    /// and \ref startSecondPhase(). The result after the second phase
957    /// could be slightly different if inexact computation is used.
958    ///
959    /// \note This function calls \ref minCut() for each node, so it runs in
[559]960    /// O(n) time.
[393]961    ///
962    /// \pre Either \ref run() or \ref init() must be called before
963    /// using this function.
[389]964    template <typename CutMap>
965    void minCutMap(CutMap& cutMap) const {
966      for (NodeIt n(_graph); n != INVALID; ++n) {
967        cutMap.set(n, minCut(n));
968      }
969    }
970
971    /// @}
972  };
973}
974
975#endif
Note: See TracBrowser for help on using the repository browser.