COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/work/jacint/max_flow.h @ 640:d426dca0aaf7

Last change on this file since 640:d426dca0aaf7 was 640:d426dca0aaf7, checked in by marci, 20 years ago

for_each_macros.h in include

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