COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/work/jacint/max_flow.h @ 650:588ff2ca55bd

Last change on this file since 650:588ff2ca55bd was 650:588ff2ca55bd, checked in by marci, 20 years ago

a

File size: 34.2 KB
RevLine 
[478]1// -*- C++ -*-
[480]2#ifndef HUGO_MAX_FLOW_H
3#define HUGO_MAX_FLOW_H
[478]4
5#include <vector>
6#include <queue>
7#include <stack>
8
[557]9#include <hugo/graph_wrapper.h>
[602]10#include <bfs_dfs.h>
[555]11#include <hugo/invalid.h>
12#include <hugo/maps.h>
[640]13#include <hugo/for_each_macros.h>
[478]14
[488]15/// \file
[631]16/// \brief Maximum flow algorithms.
[615]17/// \ingroup galgs
[478]18
19namespace hugo {
20
[631]21  /// \addtogroup galgs
22  /// @{                                                                                                                                       
23  ///Maximum flow algorithms class.
[488]24
[631]25  ///This class provides various algorithms for finding a flow of
26  ///maximum value in a directed graph. The \e source node, the \e
27  ///target node, the \e capacity of the edges and the \e starting \e
[647]28  ///flow value of the edges should be passed to the algorithm through the
[631]29  ///constructor. It is possible to change these quantities using the
30  ///functions \ref resetSource, \ref resetTarget, \ref resetCap and
31  ///\ref resetFlow. Before any subsequent runs of any algorithm of
[647]32  ///the class \ref resetFlow should be called.
33
34  ///After running an algorithm of the class, the actual flow value
35  ///can be obtained by calling \ref flowValue(). The minimum
[631]36  ///value cut can be written into a \c node map of \c bools by
37  ///calling \ref minCut. (\ref minMinCut and \ref maxMinCut writes
38  ///the inclusionwise minimum and maximum of the minimum value
39  ///cuts, resp.)                                                                                                                               
[632]40  ///\param Graph The directed graph type the algorithm runs on.
[631]41  ///\param Num The number type of the capacities and the flow values.
[647]42  ///\param CapMap The capacity map type.
43  ///\param FlowMap The flow map type.                                                                                                           
[631]44  ///\author Marton Makai, Jacint Szabo
[615]45  template <typename Graph, typename Num,
46            typename CapMap=typename Graph::template EdgeMap<Num>,
[478]47            typename FlowMap=typename Graph::template EdgeMap<Num> >
48  class MaxFlow {
[615]49  protected:
[478]50    typedef typename Graph::Node Node;
51    typedef typename Graph::NodeIt NodeIt;
[631]52    typedef typename Graph::EdgeIt EdgeIt;
[478]53    typedef typename Graph::OutEdgeIt OutEdgeIt;
54    typedef typename Graph::InEdgeIt InEdgeIt;
55
56    typedef typename std::vector<std::stack<Node> > VecStack;
57    typedef typename Graph::template NodeMap<Node> NNMap;
58    typedef typename std::vector<Node> VecNode;
59
60    const Graph* g;
61    Node s;
62    Node t;
[615]63    const CapMap* capacity;
[478]64    FlowMap* flow;
65    int n;      //the number of nodes of G
[650]66    //    typedef ResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;   
67    typedef ExpResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
[478]68    typedef typename ResGW::OutEdgeIt ResGWOutEdgeIt;
69    typedef typename ResGW::Edge ResGWEdge;
70    //typedef typename ResGW::template NodeMap<bool> ReachedMap;
71    typedef typename Graph::template NodeMap<int> ReachedMap;
[631]72
73
74    //level works as a bool map in augmenting path algorithms and is
75    //used by bfs for storing reached information.  In preflow, it
76    //shows the levels of nodes.     
[478]77    ReachedMap level;
[631]78
79    //excess is needed only in preflow
[615]80    typename Graph::template NodeMap<Num> excess;
[631]81
82    //fixme   
83//   protected:
[602]84    //     MaxFlow() { }
[615]85    //     void set(const Graph& _G, Node _s, Node _t, const CapMap& _capacity,
86    //       FlowMap& _flow)
[602]87    //       {
[615]88    //  g=&_G;
89    //  s=_s;
90    //  t=_t;
[602]91    //  capacity=&_capacity;
92    //  flow=&_flow;
93    //  n=_G.nodeNum;
[615]94    //  level.set (_G); //kellene vmi ilyesmi fv
[602]95    //  excess(_G,0); //itt is
96    //       }
[478]97
[615]98    // constants used for heuristics
99    static const int H0=20;
100    static const int H1=1;
101
[478]102  public:
[615]103
[631]104    ///Indicates the property of the starting flow.
105
106    ///Indicates the property of the starting flow. The meanings are as follows:
107    ///- \c ZERO_FLOW: constant zero flow
108    ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
109    ///the sum of the out-flows in every node except the \e source and
110    ///the \e target.
111    ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at
112    ///least the sum of the out-flows in every node except the \e source.
113    ///- \c NO_FLOW: indicates an unspecified edge map. \ref flow will be
114    ///set to the constant zero flow in the beginning of the algorithm in this case.
[647]115    enum FlowEnum{
[615]116      ZERO_FLOW,
117      GEN_FLOW,
118      PRE_FLOW,
119      NO_FLOW
[478]120    };
121
[647]122    enum StatusEnum {
123      AFTER_NOTHING,
124      AFTER_AUGMENTING,
125      AFTER_PRE_FLOW_PHASE_1,     
126      AFTER_PRE_FLOW_PHASE_2
127    };
128
129    /// Don not needle this flag only if necessary.
130    StatusEnum status;
131    int number_of_augmentations;
132
133
134    template<typename IntMap>
135    class TrickyReachedMap {
136    protected:
137      IntMap* map;
138      int* number_of_augmentations;
139    public:
140      TrickyReachedMap(IntMap& _map, int& _number_of_augmentations) :
141        map(&_map), number_of_augmentations(&_number_of_augmentations) { }
142      void set(const Node& n, bool b) {
[650]143        if (b)
144          map->set(n, *number_of_augmentations);
145        else
146          map->set(n, *number_of_augmentations-1);
[647]147      }
148      bool operator[](const Node& n) const {
149        return (*map)[n]==*number_of_augmentations;
150      }
151    };
152   
[615]153    MaxFlow(const Graph& _G, Node _s, Node _t, const CapMap& _capacity,
[478]154            FlowMap& _flow) :
[615]155      g(&_G), s(_s), t(_t), capacity(&_capacity),
[647]156      flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0),
157      status(AFTER_NOTHING), number_of_augmentations(0) { }
[478]158
[631]159    ///Runs a maximum flow algorithm.
160
161    ///Runs a preflow algorithm, which is the fastest maximum flow
162    ///algorithm up-to-date. The default for \c fe is ZERO_FLOW.
163    ///\pre The starting flow must be
164    /// - a constant zero flow if \c fe is \c ZERO_FLOW,
165    /// - an arbitary flow if \c fe is \c GEN_FLOW,
166    /// - an arbitary preflow if \c fe is \c PRE_FLOW,
167    /// - any map if \c fe is NO_FLOW.
[647]168    void run(FlowEnum fe=ZERO_FLOW) {
[615]169      preflow(fe);
[478]170    }
[615]171
[647]172                                                                             
[631]173    ///Runs a preflow algorithm. 
174
175    ///Runs a preflow algorithm. The preflow algorithms provide the
176    ///fastest way to compute a maximum flow in a directed graph.
177    ///\pre The starting flow must be
178    /// - a constant zero flow if \c fe is \c ZERO_FLOW,
179    /// - an arbitary flow if \c fe is \c GEN_FLOW,
180    /// - an arbitary preflow if \c fe is \c PRE_FLOW,
181    /// - any map if \c fe is NO_FLOW.
[647]182    void preflow(FlowEnum fe) {
[631]183      preflowPhase1(fe);
184      preflowPhase2();
[478]185    }
[631]186    // Heuristics:
187    //   2 phase
188    //   gap
189    //   list 'level_list' on the nodes on level i implemented by hand
190    //   stack 'active' on the active nodes on level i                                                                                   
191    //   runs heuristic 'highest label' for H1*n relabels
192    //   runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
193    //   Parameters H0 and H1 are initialized to 20 and 1.
[478]194
[631]195    ///Runs the first phase of the preflow algorithm.
[478]196
[631]197    ///The preflow algorithm consists of two phases, this method runs the
198    ///first phase. After the first phase the maximum flow value and a
199    ///minimum value cut can already be computed, though a maximum flow
200    ///is net yet obtained. So after calling this method \ref flowValue
201    ///and \ref actMinCut gives proper results.
202    ///\warning: \ref minCut, \ref minMinCut and \ref maxMinCut do not
203    ///give minimum value cuts unless calling \ref preflowPhase2.
204    ///\pre The starting flow must be
205    /// - a constant zero flow if \c fe is \c ZERO_FLOW,
206    /// - an arbitary flow if \c fe is \c GEN_FLOW,
207    /// - an arbitary preflow if \c fe is \c PRE_FLOW,
208    /// - any map if \c fe is NO_FLOW.
[647]209    void preflowPhase1(FlowEnum fe);
[631]210
211    ///Runs the second phase of the preflow algorithm.
212
213    ///The preflow algorithm consists of two phases, this method runs
214    ///the second phase. After calling \ref preflowPhase1 and then
215    ///\ref preflowPhase2 the methods \ref flowValue, \ref minCut,
216    ///\ref minMinCut and \ref maxMinCut give proper results.
217    ///\pre \ref preflowPhase1 must be called before.
218    void preflowPhase2();
[478]219
[615]220    /// Starting from a flow, this method searches for an augmenting path
221    /// according to the Edmonds-Karp algorithm
222    /// and augments the flow on if any.
[487]223    /// The return value shows if the augmentation was succesful.
[478]224    bool augmentOnShortestPath();
[647]225    bool augmentOnShortestPath2();
[478]226
[615]227    /// Starting from a flow, this method searches for an augmenting blocking
228    /// flow according to Dinits' algorithm and augments the flow on if any.
229    /// The blocking flow is computed in a physically constructed
[485]230    /// residual graph of type \c Mutablegraph.
[487]231    /// The return value show sif the augmentation was succesful.
[478]232    template<typename MutableGraph> bool augmentOnBlockingFlow();
233
[615]234    /// The same as \c augmentOnBlockingFlow<MutableGraph> but the
[485]235    /// residual graph is not constructed physically.
[487]236    /// The return value shows if the augmentation was succesful.
[478]237    bool augmentOnBlockingFlow2();
238
[631]239    /// Returns the maximum value of a flow.
240
241    /// Returns the maximum value of a flow, by counting the
242    /// over-flow of the target node \ref t.
243    /// It can be called already after running \ref preflowPhase1.
[647]244    Num flowValue() const {
[478]245      Num a=0;
[615]246      FOR_EACH_INC_LOC(InEdgeIt, e, *g, t) a+=(*flow)[e];
247      FOR_EACH_INC_LOC(OutEdgeIt, e, *g, t) a-=(*flow)[e];
[478]248      return a;
[631]249      //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan   
[478]250    }
251
[631]252    ///Returns a minimum value cut after calling \ref preflowPhase1.
253
254    ///After the first phase of the preflow algorithm the maximum flow
255    ///value and a minimum value cut can already be computed. This
256    ///method can be called after running \ref preflowPhase1 for
257    ///obtaining a minimum value cut.
258    /// \warning Gives proper result only right after calling \ref
259    /// preflowPhase1.
[615]260    /// \todo We have to make some status variable which shows the
261    /// actual state
262    /// of the class. This enables us to determine which methods are valid
[485]263    /// for MinCut computation
[478]264    template<typename _CutMap>
[647]265    void actMinCut(_CutMap& M) const {
[478]266      NodeIt v;
[647]267      switch (status) {
268        case AFTER_PRE_FLOW_PHASE_1:
269        for(g->first(v); g->valid(v); g->next(v)) {
270          if (level[v] < n) {
271            M.set(v, false);
272          } else {
273            M.set(v, true);
274          }
[485]275        }
[647]276        break;
277        case AFTER_PRE_FLOW_PHASE_2:
278        case AFTER_NOTHING:
279        minMinCut(M);
280        break;
281        case AFTER_AUGMENTING:
282        for(g->first(v); g->valid(v); g->next(v)) {
283          if (level[v]) {
284            M.set(v, true);
285          } else {
286            M.set(v, false);
287          }
288        }
289        break;
[478]290      }
291    }
292
[631]293    ///Returns the inclusionwise minimum of the minimum value cuts.
294
295    ///Sets \c M to the characteristic vector of the minimum value cut
296    ///which is inclusionwise minimum. It is computed by processing
297    ///a bfs from the source node \c s in the residual graph.
298    ///\pre M should be a node map of bools initialized to false.
299    ///\pre \c flow must be a maximum flow.
[478]300    template<typename _CutMap>
[647]301    void minMinCut(_CutMap& M) const {
[478]302      std::queue<Node> queue;
[615]303
304      M.set(s,true);
[478]305      queue.push(s);
306
307      while (!queue.empty()) {
308        Node w=queue.front();
309        queue.pop();
310
311        OutEdgeIt e;
312        for(g->first(e,w) ; g->valid(e); g->next(e)) {
313          Node v=g->head(e);
314          if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
315            queue.push(v);
316            M.set(v, true);
317          }
[615]318        }
[478]319
320        InEdgeIt f;
321        for(g->first(f,w) ; g->valid(f); g->next(f)) {
322          Node v=g->tail(f);
323          if (!M[v] && (*flow)[f] > 0 ) {
324            queue.push(v);
325            M.set(v, true);
326          }
[615]327        }
[478]328      }
329    }
330
[631]331    ///Returns the inclusionwise maximum of the minimum value cuts.
[478]332
[631]333    ///Sets \c M to the characteristic vector of the minimum value cut
334    ///which is inclusionwise maximum. It is computed by processing a
335    ///backward bfs from the target node \c t in the residual graph.
336    ///\pre M should be a node map of bools initialized to false.
337    ///\pre \c flow must be a maximum flow.
[478]338    template<typename _CutMap>
[647]339    void maxMinCut(_CutMap& M) const {
[478]340
341      NodeIt v;
342      for(g->first(v) ; g->valid(v); g->next(v)) {
343        M.set(v, true);
344      }
345
346      std::queue<Node> queue;
[615]347
348      M.set(t,false);
[478]349      queue.push(t);
350
351      while (!queue.empty()) {
352        Node w=queue.front();
353        queue.pop();
354
355        InEdgeIt e;
356        for(g->first(e,w) ; g->valid(e); g->next(e)) {
357          Node v=g->tail(e);
358          if (M[v] && (*flow)[e] < (*capacity)[e] ) {
359            queue.push(v);
360            M.set(v, false);
361          }
362        }
[615]363
[478]364        OutEdgeIt f;
365        for(g->first(f,w) ; g->valid(f); g->next(f)) {
366          Node v=g->head(f);
367          if (M[v] && (*flow)[f] > 0 ) {
368            queue.push(v);
369            M.set(v, false);
370          }
371        }
372      }
373    }
374
[631]375    ///Returns a minimum value cut.
[478]376
[631]377    ///Sets \c M to the characteristic vector of a minimum value cut.
378    ///\pre M should be a node map of bools initialized to false.
379    ///\pre \c flow must be a maximum flow.   
[478]380    template<typename CutMap>
[647]381    void minCut(CutMap& M) const { minMinCut(M); }
[478]382
[631]383    ///Resets the source node to \c _s.
384
385    ///Resets the source node to \c _s.
386    ///
[647]387    void resetSource(Node _s) { s=_s; status=AFTER_NOTHING; }
[631]388
389    ///Resets the target node to \c _t.
390
391    ///Resets the target node to \c _t.
[487]392    ///
[647]393    void resetTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
[615]394
[631]395    /// Resets the edge map of the capacities to _cap.
396
397    /// Resets the edge map of the capacities to _cap.
398    ///
[647]399    void resetCap(const CapMap& _cap) { capacity=&_cap; status=AFTER_NOTHING; }
[615]400
[631]401    /// Resets the edge map of the flows to _flow.
402
403    /// Resets the edge map of the flows to _flow.
404    ///
[647]405    void resetFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
[478]406
407
408  private:
409
410    int push(Node w, VecStack& active) {
[615]411
[478]412      int lev=level[w];
413      Num exc=excess[w];
414      int newlevel=n;       //bound on the next level of w
[615]415
[478]416      OutEdgeIt e;
417      for(g->first(e,w); g->valid(e); g->next(e)) {
[615]418
419        if ( (*flow)[e] >= (*capacity)[e] ) continue;
420        Node v=g->head(e);
421
[478]422        if( lev > level[v] ) { //Push is allowed now
[615]423
[478]424          if ( excess[v]<=0 && v!=t && v!=s ) {
425            int lev_v=level[v];
426            active[lev_v].push(v);
427          }
[615]428
[478]429          Num cap=(*capacity)[e];
430          Num flo=(*flow)[e];
431          Num remcap=cap-flo;
[615]432
[478]433          if ( remcap >= exc ) { //A nonsaturating push.
[615]434
[478]435            flow->set(e, flo+exc);
436            excess.set(v, excess[v]+exc);
437            exc=0;
[615]438            break;
439
[478]440          } else { //A saturating push.
441            flow->set(e, cap);
442            excess.set(v, excess[v]+remcap);
443            exc-=remcap;
444          }
445        } else if ( newlevel > level[v] ) newlevel = level[v];
[615]446      } //for out edges wv
447
448      if ( exc > 0 ) {
[478]449        InEdgeIt e;
450        for(g->first(e,w); g->valid(e); g->next(e)) {
[615]451
452          if( (*flow)[e] <= 0 ) continue;
453          Node v=g->tail(e);
454
[478]455          if( lev > level[v] ) { //Push is allowed now
[615]456
[478]457            if ( excess[v]<=0 && v!=t && v!=s ) {
458              int lev_v=level[v];
459              active[lev_v].push(v);
460            }
[615]461
[478]462            Num flo=(*flow)[e];
[615]463
[478]464            if ( flo >= exc ) { //A nonsaturating push.
[615]465
[478]466              flow->set(e, flo-exc);
467              excess.set(v, excess[v]+exc);
468              exc=0;
[615]469              break;
[478]470            } else {  //A saturating push.
[615]471
[478]472              excess.set(v, excess[v]+flo);
473              exc-=flo;
474              flow->set(e,0);
[615]475            }
[478]476          } else if ( newlevel > level[v] ) newlevel = level[v];
477        } //for in edges vw
[615]478
[478]479      } // if w still has excess after the out edge for cycle
[615]480
[478]481      excess.set(w, exc);
[615]482
[478]483      return newlevel;
[485]484    }
[478]485
486
[647]487    void preflowPreproc(FlowEnum fe, VecStack& active,
[615]488                        VecNode& level_list, NNMap& left, NNMap& right)
[602]489    {
[615]490      std::queue<Node> bfs_queue;
[478]491
[615]492      switch (fe) {
[631]493      case NO_FLOW:   //flow is already set to const zero in this case
[615]494      case ZERO_FLOW:
[602]495        {
496          //Reverse_bfs from t, to find the starting level.
497          level.set(t,0);
498          bfs_queue.push(t);
[615]499
[602]500          while (!bfs_queue.empty()) {
[615]501
502            Node v=bfs_queue.front();
[602]503            bfs_queue.pop();
504            int l=level[v]+1;
[615]505
[602]506            InEdgeIt e;
507            for(g->first(e,v); g->valid(e); g->next(e)) {
508              Node w=g->tail(e);
509              if ( level[w] == n && w != s ) {
510                bfs_queue.push(w);
511                Node first=level_list[l];
512                if ( g->valid(first) ) left.set(first,w);
513                right.set(w,first);
514                level_list[l]=w;
515                level.set(w, l);
516              }
517            }
518          }
[615]519
[602]520          //the starting flow
521          OutEdgeIt e;
[615]522          for(g->first(e,s); g->valid(e); g->next(e))
[602]523            {
524              Num c=(*capacity)[e];
525              if ( c <= 0 ) continue;
526              Node w=g->head(e);
[615]527              if ( level[w] < n ) {
[602]528                if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
[615]529                flow->set(e, c);
[602]530                excess.set(w, excess[w]+c);
531              }
532            }
533          break;
534        }
[615]535
[602]536      case GEN_FLOW:
[615]537      case PRE_FLOW:
[602]538        {
[615]539          //Reverse_bfs from t in the residual graph,
[602]540          //to find the starting level.
541          level.set(t,0);
542          bfs_queue.push(t);
[615]543
[602]544          while (!bfs_queue.empty()) {
[615]545
546            Node v=bfs_queue.front();
[602]547            bfs_queue.pop();
548            int l=level[v]+1;
[615]549
[602]550            InEdgeIt e;
551            for(g->first(e,v); g->valid(e); g->next(e)) {
552              if ( (*capacity)[e] <= (*flow)[e] ) continue;
553              Node w=g->tail(e);
554              if ( level[w] == n && w != s ) {
555                bfs_queue.push(w);
556                Node first=level_list[l];
557                if ( g->valid(first) ) left.set(first,w);
558                right.set(w,first);
559                level_list[l]=w;
560                level.set(w, l);
561              }
562            }
[615]563
[602]564            OutEdgeIt f;
565            for(g->first(f,v); g->valid(f); g->next(f)) {
566              if ( 0 >= (*flow)[f] ) continue;
567              Node w=g->head(f);
568              if ( level[w] == n && w != s ) {
569                bfs_queue.push(w);
570                Node first=level_list[l];
571                if ( g->valid(first) ) left.set(first,w);
572                right.set(w,first);
573                level_list[l]=w;
574                level.set(w, l);
575              }
576            }
577          }
[615]578
579
[602]580          //the starting flow
581          OutEdgeIt e;
[615]582          for(g->first(e,s); g->valid(e); g->next(e))
[602]583            {
584              Num rem=(*capacity)[e]-(*flow)[e];
585              if ( rem <= 0 ) continue;
586              Node w=g->head(e);
[615]587              if ( level[w] < n ) {
[602]588                if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
[615]589                flow->set(e, (*capacity)[e]);
[602]590                excess.set(w, excess[w]+rem);
591              }
592            }
[615]593
[602]594          InEdgeIt f;
[615]595          for(g->first(f,s); g->valid(f); g->next(f))
[602]596            {
597              if ( (*flow)[f] <= 0 ) continue;
598              Node w=g->tail(f);
[615]599              if ( level[w] < n ) {
[602]600                if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
601                excess.set(w, excess[w]+(*flow)[f]);
[615]602                flow->set(f, 0);
[602]603              }
[615]604            }
[602]605          break;
[615]606        } //case PRE_FLOW
[602]607      }
608    } //preflowPreproc
[478]609
610
611
[615]612    void relabel(Node w, int newlevel, VecStack& active,
613                 VecNode& level_list, NNMap& left,
614                 NNMap& right, int& b, int& k, bool what_heur )
[478]615    {
616
[615]617      Num lev=level[w];
618
[478]619      Node right_n=right[w];
620      Node left_n=left[w];
[615]621
[478]622      //unlacing starts
623      if ( g->valid(right_n) ) {
624        if ( g->valid(left_n) ) {
625          right.set(left_n, right_n);
626          left.set(right_n, left_n);
627        } else {
[615]628          level_list[lev]=right_n;
[478]629          left.set(right_n, INVALID);
[615]630        }
[478]631      } else {
632        if ( g->valid(left_n) ) {
633          right.set(left_n, INVALID);
[615]634        } else {
635          level_list[lev]=INVALID;
636        }
637      }
[478]638      //unlacing ends
[615]639
[478]640      if ( !g->valid(level_list[lev]) ) {
[615]641
[478]642        //gapping starts
643        for (int i=lev; i!=k ; ) {
644          Node v=level_list[++i];
645          while ( g->valid(v) ) {
646            level.set(v,n);
647            v=right[v];
648          }
649          level_list[i]=INVALID;
650          if ( !what_heur ) {
651            while ( !active[i].empty() ) {
652              active[i].pop();    //FIXME: ezt szebben kene
653            }
[615]654          }
[478]655        }
[615]656
[478]657        level.set(w,n);
658        b=lev-1;
659        k=b;
660        //gapping ends
[615]661
[478]662      } else {
[615]663
664        if ( newlevel == n ) level.set(w,n);
[478]665        else {
666          level.set(w,++newlevel);
667          active[newlevel].push(w);
668          if ( what_heur ) b=newlevel;
669          if ( k < newlevel ) ++k;      //now k=newlevel
670          Node first=level_list[newlevel];
671          if ( g->valid(first) ) left.set(first,w);
672          right.set(w,first);
673          left.set(w,INVALID);
674          level_list[newlevel]=w;
675        }
676      }
[615]677
[478]678    } //relabel
679
680
[615]681    template<typename MapGraphWrapper>
[478]682    class DistanceMap {
683    protected:
684      const MapGraphWrapper* g;
[615]685      typename MapGraphWrapper::template NodeMap<int> dist;
[478]686    public:
687      DistanceMap(MapGraphWrapper& _g) : g(&_g), dist(*g, g->nodeNum()) { }
[615]688      void set(const typename MapGraphWrapper::Node& n, int a) {
689        dist.set(n, a);
[478]690      }
[647]691      int operator[](const typename MapGraphWrapper::Node& n) const {
692        return dist[n];
693      }
[615]694      //       int get(const typename MapGraphWrapper::Node& n) const {
[485]695      //        return dist[n]; }
[615]696      //       bool get(const typename MapGraphWrapper::Edge& e) const {
[485]697      //        return (dist.get(g->tail(e))<dist.get(g->head(e))); }
[615]698      bool operator[](const typename MapGraphWrapper::Edge& e) const {
699        return (dist[g->tail(e)]<dist[g->head(e)]);
[478]700      }
701    };
[615]702
[478]703  };
704
705
706  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
[647]707  void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase1(FlowEnum fe)
[478]708  {
[615]709
710    int heur0=(int)(H0*n);  //time while running 'bound decrease'
[485]711    int heur1=(int)(H1*n);  //time while running 'highest label'
712    int heur=heur1;         //starting time interval (#of relabels)
713    int numrelabel=0;
[615]714
715    bool what_heur=1;
[485]716    //It is 0 in case 'bound decrease' and 1 in case 'highest label'
[478]717
[615]718    bool end=false;
719    //Needed for 'bound decrease', true means no active nodes are above bound
720    //b.
[478]721
[485]722    int k=n-2;  //bound on the highest level under n containing a node
723    int b=k;    //bound on the highest level under n of an active node
[615]724
[485]725    VecStack active(n);
[615]726
[485]727    NNMap left(*g, INVALID);
728    NNMap right(*g, INVALID);
729    VecNode level_list(n,INVALID);
730    //List of the nodes in level i<n, set to n.
[478]731
[485]732    NodeIt v;
733    for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
734    //setting each node to level n
[615]735
[631]736    if ( fe == NO_FLOW ) {
737      EdgeIt e;
738      for(g->first(e); g->valid(e); g->next(e)) flow->set(e,0);
739    }
740
741    switch (fe) { //computing the excess
[615]742    case PRE_FLOW:
[485]743      {
744        NodeIt v;
745        for(g->first(v); g->valid(v); g->next(v)) {
[478]746          Num exc=0;
[615]747
[478]748          InEdgeIt e;
[485]749          for(g->first(e,v); g->valid(e); g->next(e)) exc+=(*flow)[e];
[478]750          OutEdgeIt f;
[485]751          for(g->first(f,v); g->valid(f); g->next(f)) exc-=(*flow)[f];
[615]752
753          excess.set(v,exc);
754
[485]755          //putting the active nodes into the stack
756          int lev=level[v];
757          if ( exc > 0 && lev < n && v != t ) active[lev].push(v);
[478]758        }
759        break;
760      }
[485]761    case GEN_FLOW:
762      {
[631]763        NodeIt v;
764        for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
765
[485]766        Num exc=0;
767        InEdgeIt e;
768        for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
769        OutEdgeIt f;
770        for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
[615]771        excess.set(t,exc);
[485]772        break;
773      }
[631]774    case ZERO_FLOW:
775    case NO_FLOW:
776      {
777        NodeIt v;
778        for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
779        break;
780      }
[485]781    }
[615]782
783    preflowPreproc(fe, active, level_list, left, right);
784    //End of preprocessing
785
786
[485]787    //Push/relabel on the highest level active nodes.
788    while ( true ) {
789      if ( b == 0 ) {
790        if ( !what_heur && !end && k > 0 ) {
791          b=k;
792          end=true;
793        } else break;
794      }
[615]795
796      if ( active[b].empty() ) --b;
[485]797      else {
[615]798        end=false;
[485]799        Node w=active[b].top();
800        active[b].pop();
801        int newlevel=push(w,active);
[615]802        if ( excess[w] > 0 ) relabel(w, newlevel, active, level_list,
[485]803                                     left, right, b, k, what_heur);
[615]804
805        ++numrelabel;
[485]806        if ( numrelabel >= heur ) {
807          numrelabel=0;
808          if ( what_heur ) {
809            what_heur=0;
810            heur=heur0;
811            end=false;
812          } else {
813            what_heur=1;
814            heur=heur1;
[615]815            b=k;
[485]816          }
[478]817        }
[615]818      }
819    }
[647]820
821    status=AFTER_PRE_FLOW_PHASE_1;
[485]822  }
[478]823
824
825
826  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
[631]827  void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase2()
[478]828  {
[615]829
[485]830    int k=n-2;  //bound on the highest level under n containing a node
831    int b=k;    //bound on the highest level under n of an active node
[615]832
[485]833    VecStack active(n);
834    level.set(s,0);
835    std::queue<Node> bfs_queue;
836    bfs_queue.push(s);
[615]837
[485]838    while (!bfs_queue.empty()) {
[615]839
840      Node v=bfs_queue.front();
[485]841      bfs_queue.pop();
842      int l=level[v]+1;
[615]843
[485]844      InEdgeIt e;
845      for(g->first(e,v); g->valid(e); g->next(e)) {
846        if ( (*capacity)[e] <= (*flow)[e] ) continue;
847        Node u=g->tail(e);
[615]848        if ( level[u] >= n ) {
[485]849          bfs_queue.push(u);
850          level.set(u, l);
851          if ( excess[u] > 0 ) active[l].push(u);
[478]852        }
853      }
[615]854
[485]855      OutEdgeIt f;
856      for(g->first(f,v); g->valid(f); g->next(f)) {
857        if ( 0 >= (*flow)[f] ) continue;
858        Node u=g->head(f);
[615]859        if ( level[u] >= n ) {
[485]860          bfs_queue.push(u);
861          level.set(u, l);
862          if ( excess[u] > 0 ) active[l].push(u);
863        }
864      }
865    }
866    b=n-2;
[478]867
[485]868    while ( true ) {
[615]869
[485]870      if ( b == 0 ) break;
[478]871
[615]872      if ( active[b].empty() ) --b;
[485]873      else {
874        Node w=active[b].top();
875        active[b].pop();
[615]876        int newlevel=push(w,active);
[478]877
[485]878        //relabel
879        if ( excess[w] > 0 ) {
880          level.set(w,++newlevel);
881          active[newlevel].push(w);
882          b=newlevel;
883        }
884      }  // if stack[b] is nonempty
885    } // while(true)
[647]886
887    status=AFTER_PRE_FLOW_PHASE_2;
[485]888  }
[478]889
890
891
892  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
[615]893  bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnShortestPath()
[478]894  {
[485]895    ResGW res_graph(*g, *capacity, *flow);
896    bool _augment=false;
[615]897
[485]898    //ReachedMap level(res_graph);
899    FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
900    BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
901    bfs.pushAndSetReached(s);
[615]902
903    typename ResGW::template NodeMap<ResGWEdge> pred(res_graph);
[485]904    pred.set(s, INVALID);
[615]905
[485]906    typename ResGW::template NodeMap<Num> free(res_graph);
[615]907
[485]908    //searching for augmenting path
[615]909    while ( !bfs.finished() ) {
[485]910      ResGWOutEdgeIt e=bfs;
911      if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
912        Node v=res_graph.tail(e);
913        Node w=res_graph.head(e);
914        pred.set(w, e);
915        if (res_graph.valid(pred[v])) {
916          free.set(w, std::min(free[v], res_graph.resCap(e)));
917        } else {
[615]918          free.set(w, res_graph.resCap(e));
[478]919        }
[485]920        if (res_graph.head(e)==t) { _augment=true; break; }
921      }
[615]922
[485]923      ++bfs;
924    } //end of searching augmenting path
[478]925
[485]926    if (_augment) {
927      Node n=t;
928      Num augment_value=free[t];
[615]929      while (res_graph.valid(pred[n])) {
[485]930        ResGWEdge e=pred[n];
[615]931        res_graph.augment(e, augment_value);
[485]932        n=res_graph.tail(e);
[478]933      }
[485]934    }
[478]935
[647]936    status=AFTER_AUGMENTING;
[485]937    return _augment;
938  }
[478]939
940
[647]941  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
942  bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnShortestPath2()
943  {
944    ResGW res_graph(*g, *capacity, *flow);
945    bool _augment=false;
[478]946
[647]947    if (status!=AFTER_AUGMENTING) {
[650]948      FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 3*n);
949      number_of_augmentations=3*n+1;
[647]950    } else {
951      ++number_of_augmentations;
952    }
953    TrickyReachedMap<ReachedMap>
954      tricky_reached_map(level, number_of_augmentations);
955    //ReachedMap level(res_graph);
956//    FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
957    BfsIterator<ResGW, TrickyReachedMap<ReachedMap> >
958      bfs(res_graph, tricky_reached_map);
959    bfs.pushAndSetReached(s);
[478]960
[647]961    typename ResGW::template NodeMap<ResGWEdge> pred(res_graph);
962    pred.set(s, INVALID);
[478]963
[647]964    typename ResGW::template NodeMap<Num> free(res_graph);
965
966    //searching for augmenting path
967    while ( !bfs.finished() ) {
968      ResGWOutEdgeIt e=bfs;
969      if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
970        Node v=res_graph.tail(e);
971        Node w=res_graph.head(e);
972        pred.set(w, e);
973        if (res_graph.valid(pred[v])) {
974          free.set(w, std::min(free[v], res_graph.resCap(e)));
975        } else {
976          free.set(w, res_graph.resCap(e));
977        }
978        if (res_graph.head(e)==t) { _augment=true; break; }
979      }
980
981      ++bfs;
982    } //end of searching augmenting path
983
984    if (_augment) {
985      Node n=t;
986      Num augment_value=free[t];
987      while (res_graph.valid(pred[n])) {
988        ResGWEdge e=pred[n];
989        res_graph.augment(e, augment_value);
990        n=res_graph.tail(e);
991      }
992    }
993
994    status=AFTER_AUGMENTING;
995    return _augment;
996  }
[478]997
998
999  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
[615]1000  template<typename MutableGraph>
1001  bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow()
1002  {
[485]1003    typedef MutableGraph MG;
1004    bool _augment=false;
[478]1005
[485]1006    ResGW res_graph(*g, *capacity, *flow);
[478]1007
[485]1008    //bfs for distances on the residual graph
1009    //ReachedMap level(res_graph);
1010    FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
1011    BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
1012    bfs.pushAndSetReached(s);
[615]1013    typename ResGW::template NodeMap<int>
[485]1014      dist(res_graph); //filled up with 0's
[478]1015
[485]1016    //F will contain the physical copy of the residual graph
1017    //with the set of edges which are on shortest paths
1018    MG F;
[615]1019    typename ResGW::template NodeMap<typename MG::Node>
[485]1020      res_graph_to_F(res_graph);
1021    {
1022      typename ResGW::NodeIt n;
1023      for(res_graph.first(n); res_graph.valid(n); res_graph.next(n)) {
1024        res_graph_to_F.set(n, F.addNode());
[478]1025      }
[485]1026    }
[478]1027
[485]1028    typename MG::Node sF=res_graph_to_F[s];
1029    typename MG::Node tF=res_graph_to_F[t];
1030    typename MG::template EdgeMap<ResGWEdge> original_edge(F);
1031    typename MG::template EdgeMap<Num> residual_capacity(F);
[478]1032
[615]1033    while ( !bfs.finished() ) {
[485]1034      ResGWOutEdgeIt e=bfs;
1035      if (res_graph.valid(e)) {
1036        if (bfs.isBNodeNewlyReached()) {
1037          dist.set(res_graph.head(e), dist[res_graph.tail(e)]+1);
[615]1038          typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)],
1039                                        res_graph_to_F[res_graph.head(e)]);
[485]1040          original_edge.update();
1041          original_edge.set(f, e);
1042          residual_capacity.update();
1043          residual_capacity.set(f, res_graph.resCap(e));
1044        } else {
1045          if (dist[res_graph.head(e)]==(dist[res_graph.tail(e)]+1)) {
[615]1046            typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)],
1047                                          res_graph_to_F[res_graph.head(e)]);
[478]1048            original_edge.update();
1049            original_edge.set(f, e);
1050            residual_capacity.update();
1051            residual_capacity.set(f, res_graph.resCap(e));
1052          }
1053        }
[485]1054      }
1055      ++bfs;
1056    } //computing distances from s in the residual graph
[478]1057
[485]1058    bool __augment=true;
[478]1059
[485]1060    while (__augment) {
1061      __augment=false;
1062      //computing blocking flow with dfs
1063      DfsIterator< MG, typename MG::template NodeMap<bool> > dfs(F);
1064      typename MG::template NodeMap<typename MG::Edge> pred(F);
1065      pred.set(sF, INVALID);
1066      //invalid iterators for sources
[478]1067
[485]1068      typename MG::template NodeMap<Num> free(F);
[478]1069
[615]1070      dfs.pushAndSetReached(sF);
[485]1071      while (!dfs.finished()) {
1072        ++dfs;
1073        if (F.valid(/*typename MG::OutEdgeIt*/(dfs))) {
1074          if (dfs.isBNodeNewlyReached()) {
1075            typename MG::Node v=F.aNode(dfs);
1076            typename MG::Node w=F.bNode(dfs);
1077            pred.set(w, dfs);
1078            if (F.valid(pred[v])) {
1079              free.set(w, std::min(free[v], residual_capacity[dfs]));
1080            } else {
[615]1081              free.set(w, residual_capacity[dfs]);
[485]1082            }
[615]1083            if (w==tF) {
1084              __augment=true;
[485]1085              _augment=true;
[615]1086              break;
[485]1087            }
[615]1088
[485]1089          } else {
1090            F.erase(/*typename MG::OutEdgeIt*/(dfs));
1091          }
[615]1092        }
[485]1093      }
1094
1095      if (__augment) {
1096        typename MG::Node n=tF;
1097        Num augment_value=free[tF];
[615]1098        while (F.valid(pred[n])) {
[485]1099          typename MG::Edge e=pred[n];
[615]1100          res_graph.augment(original_edge[e], augment_value);
[485]1101          n=F.tail(e);
[615]1102          if (residual_capacity[e]==augment_value)
1103            F.erase(e);
1104          else
[485]1105            residual_capacity.set(e, residual_capacity[e]-augment_value);
[478]1106        }
[485]1107      }
[615]1108
[485]1109    }
[615]1110
[647]1111    status=AFTER_AUGMENTING;
[485]1112    return _augment;
1113  }
[478]1114
1115
1116
1117
1118  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
[615]1119  bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow2()
[478]1120  {
[485]1121    bool _augment=false;
[478]1122
[485]1123    ResGW res_graph(*g, *capacity, *flow);
[615]1124
[485]1125    //ReachedMap level(res_graph);
1126    FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
1127    BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
[478]1128
[485]1129    bfs.pushAndSetReached(s);
1130    DistanceMap<ResGW> dist(res_graph);
[615]1131    while ( !bfs.finished() ) {
[485]1132      ResGWOutEdgeIt e=bfs;
1133      if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
1134        dist.set(res_graph.head(e), dist[res_graph.tail(e)]+1);
1135      }
1136      ++bfs;
1137    } //computing distances from s in the residual graph
[478]1138
1139      //Subgraph containing the edges on some shortest paths
[485]1140    ConstMap<typename ResGW::Node, bool> true_map(true);
[615]1141    typedef SubGraphWrapper<ResGW, ConstMap<typename ResGW::Node, bool>,
[485]1142      DistanceMap<ResGW> > FilterResGW;
1143    FilterResGW filter_res_graph(res_graph, true_map, dist);
[478]1144
[615]1145    //Subgraph, which is able to delete edges which are already
[485]1146    //met by the dfs
[615]1147    typename FilterResGW::template NodeMap<typename FilterResGW::OutEdgeIt>
[485]1148      first_out_edges(filter_res_graph);
1149    typename FilterResGW::NodeIt v;
[615]1150    for(filter_res_graph.first(v); filter_res_graph.valid(v);
1151        filter_res_graph.next(v))
[478]1152      {
1153        typename FilterResGW::OutEdgeIt e;
1154        filter_res_graph.first(e, v);
1155        first_out_edges.set(v, e);
1156      }
[485]1157    typedef ErasingFirstGraphWrapper<FilterResGW, typename FilterResGW::
1158      template NodeMap<typename FilterResGW::OutEdgeIt> > ErasingResGW;
1159    ErasingResGW erasing_res_graph(filter_res_graph, first_out_edges);
[478]1160
[485]1161    bool __augment=true;
[478]1162
[485]1163    while (__augment) {
[478]1164
[485]1165      __augment=false;
1166      //computing blocking flow with dfs
[615]1167      DfsIterator< ErasingResGW,
1168        typename ErasingResGW::template NodeMap<bool> >
[485]1169        dfs(erasing_res_graph);
1170      typename ErasingResGW::
[615]1171        template NodeMap<typename ErasingResGW::OutEdgeIt>
1172        pred(erasing_res_graph);
[485]1173      pred.set(s, INVALID);
1174      //invalid iterators for sources
[478]1175
[615]1176      typename ErasingResGW::template NodeMap<Num>
[485]1177        free1(erasing_res_graph);
[478]1178
[615]1179      dfs.pushAndSetReached
1180        ///\bug hugo 0.2
1181        (typename ErasingResGW::Node
1182         (typename FilterResGW::Node
1183          (typename ResGW::Node(s)
1184           )
1185          )
1186         );
[485]1187      while (!dfs.finished()) {
1188        ++dfs;
[615]1189        if (erasing_res_graph.valid(typename ErasingResGW::OutEdgeIt(dfs)))
1190          {
[478]1191            if (dfs.isBNodeNewlyReached()) {
[615]1192
[478]1193              typename ErasingResGW::Node v=erasing_res_graph.aNode(dfs);
1194              typename ErasingResGW::Node w=erasing_res_graph.bNode(dfs);
1195
1196              pred.set(w, /*typename ErasingResGW::OutEdgeIt*/(dfs));
1197              if (erasing_res_graph.valid(pred[v])) {
[615]1198                free1.set
1199                  (w, std::min(free1[v], res_graph.resCap
1200                               (typename ErasingResGW::OutEdgeIt(dfs))));
[478]1201              } else {
[615]1202                free1.set
1203                  (w, res_graph.resCap
1204                   (typename ErasingResGW::OutEdgeIt(dfs)));
[478]1205              }
[615]1206
1207              if (w==t) {
1208                __augment=true;
[478]1209                _augment=true;
[615]1210                break;
[478]1211              }
1212            } else {
1213              erasing_res_graph.erase(dfs);
1214            }
1215          }
[615]1216      }
[478]1217
[485]1218      if (__augment) {
[615]1219        typename ErasingResGW::Node
1220          n=typename FilterResGW::Node(typename ResGW::Node(t));
[485]1221        //        typename ResGW::NodeMap<Num> a(res_graph);
1222        //        typename ResGW::Node b;
1223        //        Num j=a[b];
1224        //        typename FilterResGW::NodeMap<Num> a1(filter_res_graph);
1225        //        typename FilterResGW::Node b1;
1226        //        Num j1=a1[b1];
1227        //        typename ErasingResGW::NodeMap<Num> a2(erasing_res_graph);
1228        //        typename ErasingResGW::Node b2;
1229        //        Num j2=a2[b2];
1230        Num augment_value=free1[n];
[615]1231        while (erasing_res_graph.valid(pred[n])) {
[485]1232          typename ErasingResGW::OutEdgeIt e=pred[n];
1233          res_graph.augment(e, augment_value);
1234          n=erasing_res_graph.tail(e);
1235          if (res_graph.resCap(e)==0)
1236            erasing_res_graph.erase(e);
[478]1237        }
1238      }
[615]1239
1240    } //while (__augment)
1241
[647]1242    status=AFTER_AUGMENTING;
[485]1243    return _augment;
1244  }
[478]1245
1246
1247} //namespace hugo
1248
[480]1249#endif //HUGO_MAX_FLOW_H
[478]1250
1251
1252
1253
Note: See TracBrowser for help on using the repository browser.