COIN-OR::LEMON - Graph Library

source: lemon/lemon/preflow.h @ 985:f63fd24c0aea

1.2
Last change on this file since 985:f63fd24c0aea was 985:f63fd24c0aea, checked in by Alpar Juttner <alpar@…>, 14 years ago

Merge bugfix #372 to branch 1.2

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