COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/work/jacint/max_flow.h @ 632:3f3e184252d2

Last change on this file since 632:3f3e184252d2 was 632:3f3e184252d2, checked in by marci, 20 years ago

undir -> dir in docs

File size: 31.3 KB
Line 
1// -*- C++ -*-
2#ifndef HUGO_MAX_FLOW_H
3#define HUGO_MAX_FLOW_H
4
5#include <vector>
6#include <queue>
7#include <stack>
8
9#include <hugo/graph_wrapper.h>
10#include <bfs_dfs.h>
11#include <hugo/invalid.h>
12#include <hugo/maps.h>
13#include <for_each_macros.h>
14
15/// \file
16/// \brief Maximum flow algorithms.
17/// \ingroup galgs
18
19namespace hugo {
20
21  /// \addtogroup galgs
22  /// @{                                                                                                                                       
23  ///Maximum flow algorithms class.
24
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.)                                                                                                                               
40  ///\param Graph The directed graph type the algorithm runs on.
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
45  template <typename Graph, typename Num,
46            typename CapMap=typename Graph::template EdgeMap<Num>,
47            typename FlowMap=typename Graph::template EdgeMap<Num> >
48  class MaxFlow {
49  protected:
50    typedef typename Graph::Node Node;
51    typedef typename Graph::NodeIt NodeIt;
52    typedef typename Graph::EdgeIt EdgeIt;
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;
63    const CapMap* capacity;
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;
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.     
76    ReachedMap level;
77
78    //excess is needed only in preflow
79    typename Graph::template NodeMap<Num> excess;
80
81    //fixme   
82//   protected:
83    //     MaxFlow() { }
84    //     void set(const Graph& _G, Node _s, Node _t, const CapMap& _capacity,
85    //       FlowMap& _flow)
86    //       {
87    //  g=&_G;
88    //  s=_s;
89    //  t=_t;
90    //  capacity=&_capacity;
91    //  flow=&_flow;
92    //  n=_G.nodeNum;
93    //  level.set (_G); //kellene vmi ilyesmi fv
94    //  excess(_G,0); //itt is
95    //       }
96
97    // constants used for heuristics
98    static const int H0=20;
99    static const int H1=1;
100
101  public:
102
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.
114    enum flowEnum{
115      ZERO_FLOW,
116      GEN_FLOW,
117      PRE_FLOW,
118      NO_FLOW
119    };
120
121    MaxFlow(const Graph& _G, Node _s, Node _t, const CapMap& _capacity,
122            FlowMap& _flow) :
123      g(&_G), s(_s), t(_t), capacity(&_capacity),
124      flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0) {}
125
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.
135    void run(flowEnum fe=ZERO_FLOW) {
136      preflow(fe);
137    }
138
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.
149    void preflow(flowEnum fe) {
150      preflowPhase1(fe);
151      preflowPhase2();
152    }
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.
161
162    ///Runs the first phase of the preflow algorithm.
163
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();
186
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.
190    /// The return value shows if the augmentation was succesful.
191    bool augmentOnShortestPath();
192
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
196    /// residual graph of type \c Mutablegraph.
197    /// The return value show sif the augmentation was succesful.
198    template<typename MutableGraph> bool augmentOnBlockingFlow();
199
200    /// The same as \c augmentOnBlockingFlow<MutableGraph> but the
201    /// residual graph is not constructed physically.
202    /// The return value shows if the augmentation was succesful.
203    bool augmentOnBlockingFlow2();
204
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.
210    Num flowValue() {
211      Num a=0;
212      FOR_EACH_INC_LOC(InEdgeIt, e, *g, t) a+=(*flow)[e];
213      FOR_EACH_INC_LOC(OutEdgeIt, e, *g, t) a-=(*flow)[e];
214      return a;
215      //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan   
216    }
217
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.
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
229    /// for MinCut computation
230    template<typename _CutMap>
231    void actMinCut(_CutMap& M) {
232      NodeIt v;
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        }
239      }
240    }
241
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.
249    template<typename _CutMap>
250    void minMinCut(_CutMap& M) {
251
252      std::queue<Node> queue;
253
254      M.set(s,true);
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          }
268        }
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          }
277        }
278      }
279    }
280
281    ///Returns the inclusionwise maximum of the minimum value cuts.
282
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.
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;
297
298      M.set(t,false);
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        }
313
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
325    ///Returns a minimum value cut.
326
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.   
330    template<typename CutMap>
331    void minCut(CutMap& M) { minMinCut(M); }
332
333    ///Resets the source node to \c _s.
334
335    ///Resets the source node to \c _s.
336    ///
337    void resetSource(Node _s) { s=_s; }
338
339    ///Resets the target node to \c _t.
340
341    ///Resets the target node to \c _t.
342    ///
343    void resetTarget(Node _t) { t=_t; }
344
345    /// Resets the edge map of the capacities to _cap.
346
347    /// Resets the edge map of the capacities to _cap.
348    ///
349    void resetCap(const CapMap& _cap) { capacity=&_cap; }
350
351    /// Resets the edge map of the flows to _flow.
352
353    /// Resets the edge map of the flows to _flow.
354    ///
355    void resetFlow(FlowMap& _flow) { flow=&_flow; }
356
357
358  private:
359
360    int push(Node w, VecStack& active) {
361
362      int lev=level[w];
363      Num exc=excess[w];
364      int newlevel=n;       //bound on the next level of w
365
366      OutEdgeIt e;
367      for(g->first(e,w); g->valid(e); g->next(e)) {
368
369        if ( (*flow)[e] >= (*capacity)[e] ) continue;
370        Node v=g->head(e);
371
372        if( lev > level[v] ) { //Push is allowed now
373
374          if ( excess[v]<=0 && v!=t && v!=s ) {
375            int lev_v=level[v];
376            active[lev_v].push(v);
377          }
378
379          Num cap=(*capacity)[e];
380          Num flo=(*flow)[e];
381          Num remcap=cap-flo;
382
383          if ( remcap >= exc ) { //A nonsaturating push.
384
385            flow->set(e, flo+exc);
386            excess.set(v, excess[v]+exc);
387            exc=0;
388            break;
389
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];
396      } //for out edges wv
397
398      if ( exc > 0 ) {
399        InEdgeIt e;
400        for(g->first(e,w); g->valid(e); g->next(e)) {
401
402          if( (*flow)[e] <= 0 ) continue;
403          Node v=g->tail(e);
404
405          if( lev > level[v] ) { //Push is allowed now
406
407            if ( excess[v]<=0 && v!=t && v!=s ) {
408              int lev_v=level[v];
409              active[lev_v].push(v);
410            }
411
412            Num flo=(*flow)[e];
413
414            if ( flo >= exc ) { //A nonsaturating push.
415
416              flow->set(e, flo-exc);
417              excess.set(v, excess[v]+exc);
418              exc=0;
419              break;
420            } else {  //A saturating push.
421
422              excess.set(v, excess[v]+flo);
423              exc-=flo;
424              flow->set(e,0);
425            }
426          } else if ( newlevel > level[v] ) newlevel = level[v];
427        } //for in edges vw
428
429      } // if w still has excess after the out edge for cycle
430
431      excess.set(w, exc);
432
433      return newlevel;
434    }
435
436
437    void preflowPreproc(flowEnum fe, VecStack& active,
438                        VecNode& level_list, NNMap& left, NNMap& right)
439    {
440      std::queue<Node> bfs_queue;
441
442      switch (fe) {
443      case NO_FLOW:   //flow is already set to const zero in this case
444      case ZERO_FLOW:
445        {
446          //Reverse_bfs from t, to find the starting level.
447          level.set(t,0);
448          bfs_queue.push(t);
449
450          while (!bfs_queue.empty()) {
451
452            Node v=bfs_queue.front();
453            bfs_queue.pop();
454            int l=level[v]+1;
455
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          }
469
470          //the starting flow
471          OutEdgeIt e;
472          for(g->first(e,s); g->valid(e); g->next(e))
473            {
474              Num c=(*capacity)[e];
475              if ( c <= 0 ) continue;
476              Node w=g->head(e);
477              if ( level[w] < n ) {
478                if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
479                flow->set(e, c);
480                excess.set(w, excess[w]+c);
481              }
482            }
483          break;
484        }
485
486      case GEN_FLOW:
487      case PRE_FLOW:
488        {
489          //Reverse_bfs from t in the residual graph,
490          //to find the starting level.
491          level.set(t,0);
492          bfs_queue.push(t);
493
494          while (!bfs_queue.empty()) {
495
496            Node v=bfs_queue.front();
497            bfs_queue.pop();
498            int l=level[v]+1;
499
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            }
513
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          }
528
529
530          //the starting flow
531          OutEdgeIt e;
532          for(g->first(e,s); g->valid(e); g->next(e))
533            {
534              Num rem=(*capacity)[e]-(*flow)[e];
535              if ( rem <= 0 ) continue;
536              Node w=g->head(e);
537              if ( level[w] < n ) {
538                if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
539                flow->set(e, (*capacity)[e]);
540                excess.set(w, excess[w]+rem);
541              }
542            }
543
544          InEdgeIt f;
545          for(g->first(f,s); g->valid(f); g->next(f))
546            {
547              if ( (*flow)[f] <= 0 ) continue;
548              Node w=g->tail(f);
549              if ( level[w] < n ) {
550                if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
551                excess.set(w, excess[w]+(*flow)[f]);
552                flow->set(f, 0);
553              }
554            }
555          break;
556        } //case PRE_FLOW
557      }
558    } //preflowPreproc
559
560
561
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 )
565    {
566
567      Num lev=level[w];
568
569      Node right_n=right[w];
570      Node left_n=left[w];
571
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 {
578          level_list[lev]=right_n;
579          left.set(right_n, INVALID);
580        }
581      } else {
582        if ( g->valid(left_n) ) {
583          right.set(left_n, INVALID);
584        } else {
585          level_list[lev]=INVALID;
586        }
587      }
588      //unlacing ends
589
590      if ( !g->valid(level_list[lev]) ) {
591
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            }
604          }
605        }
606
607        level.set(w,n);
608        b=lev-1;
609        k=b;
610        //gapping ends
611
612      } else {
613
614        if ( newlevel == n ) level.set(w,n);
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      }
627
628    } //relabel
629
630
631    template<typename MapGraphWrapper>
632    class DistanceMap {
633    protected:
634      const MapGraphWrapper* g;
635      typename MapGraphWrapper::template NodeMap<int> dist;
636    public:
637      DistanceMap(MapGraphWrapper& _g) : g(&_g), dist(*g, g->nodeNum()) { }
638      void set(const typename MapGraphWrapper::Node& n, int a) {
639        dist.set(n, a);
640      }
641      int operator[](const typename MapGraphWrapper::Node& n)
642      { return dist[n]; }
643      //       int get(const typename MapGraphWrapper::Node& n) const {
644      //        return dist[n]; }
645      //       bool get(const typename MapGraphWrapper::Edge& e) const {
646      //        return (dist.get(g->tail(e))<dist.get(g->head(e))); }
647      bool operator[](const typename MapGraphWrapper::Edge& e) const {
648        return (dist[g->tail(e)]<dist[g->head(e)]);
649      }
650    };
651
652  };
653
654
655  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
656  void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase1( flowEnum fe )
657  {
658
659    int heur0=(int)(H0*n);  //time while running 'bound decrease'
660    int heur1=(int)(H1*n);  //time while running 'highest label'
661    int heur=heur1;         //starting time interval (#of relabels)
662    int numrelabel=0;
663
664    bool what_heur=1;
665    //It is 0 in case 'bound decrease' and 1 in case 'highest label'
666
667    bool end=false;
668    //Needed for 'bound decrease', true means no active nodes are above bound
669    //b.
670
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
673
674    VecStack active(n);
675
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.
680
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
684
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
691    case PRE_FLOW:
692      {
693        NodeIt v;
694        for(g->first(v); g->valid(v); g->next(v)) {
695          Num exc=0;
696
697          InEdgeIt e;
698          for(g->first(e,v); g->valid(e); g->next(e)) exc+=(*flow)[e];
699          OutEdgeIt f;
700          for(g->first(f,v); g->valid(f); g->next(f)) exc-=(*flow)[f];
701
702          excess.set(v,exc);
703
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);
707        }
708        break;
709      }
710    case GEN_FLOW:
711      {
712        NodeIt v;
713        for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
714
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];
720        excess.set(t,exc);
721        break;
722      }
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      }
730    }
731
732    preflowPreproc(fe, active, level_list, left, right);
733    //End of preprocessing
734
735
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      }
744
745      if ( active[b].empty() ) --b;
746      else {
747        end=false;
748        Node w=active[b].top();
749        active[b].pop();
750        int newlevel=push(w,active);
751        if ( excess[w] > 0 ) relabel(w, newlevel, active, level_list,
752                                     left, right, b, k, what_heur);
753
754        ++numrelabel;
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;
764            b=k;
765          }
766        }
767      }
768    }
769  }
770
771
772
773  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
774  void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase2()
775  {
776
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
779
780    VecStack active(n);
781    level.set(s,0);
782    std::queue<Node> bfs_queue;
783    bfs_queue.push(s);
784
785    while (!bfs_queue.empty()) {
786
787      Node v=bfs_queue.front();
788      bfs_queue.pop();
789      int l=level[v]+1;
790
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);
795        if ( level[u] >= n ) {
796          bfs_queue.push(u);
797          level.set(u, l);
798          if ( excess[u] > 0 ) active[l].push(u);
799        }
800      }
801
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);
806        if ( level[u] >= n ) {
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;
814
815    while ( true ) {
816
817      if ( b == 0 ) break;
818
819      if ( active[b].empty() ) --b;
820      else {
821        Node w=active[b].top();
822        active[b].pop();
823        int newlevel=push(w,active);
824
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  }
834
835
836
837  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
838  bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnShortestPath()
839  {
840    ResGW res_graph(*g, *capacity, *flow);
841    bool _augment=false;
842
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);
847
848    typename ResGW::template NodeMap<ResGWEdge> pred(res_graph);
849    pred.set(s, INVALID);
850
851    typename ResGW::template NodeMap<Num> free(res_graph);
852
853    //searching for augmenting path
854    while ( !bfs.finished() ) {
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 {
863          free.set(w, res_graph.resCap(e));
864        }
865        if (res_graph.head(e)==t) { _augment=true; break; }
866      }
867
868      ++bfs;
869    } //end of searching augmenting path
870
871    if (_augment) {
872      Node n=t;
873      Num augment_value=free[t];
874      while (res_graph.valid(pred[n])) {
875        ResGWEdge e=pred[n];
876        res_graph.augment(e, augment_value);
877        n=res_graph.tail(e);
878      }
879    }
880
881    return _augment;
882  }
883
884
885
886
887
888
889
890  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
891  template<typename MutableGraph>
892  bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow()
893  {
894    typedef MutableGraph MG;
895    bool _augment=false;
896
897    ResGW res_graph(*g, *capacity, *flow);
898
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);
904    typename ResGW::template NodeMap<int>
905      dist(res_graph); //filled up with 0's
906
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;
910    typename ResGW::template NodeMap<typename MG::Node>
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());
916      }
917    }
918
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);
923
924    while ( !bfs.finished() ) {
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);
929          typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)],
930                                        res_graph_to_F[res_graph.head(e)]);
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)) {
937            typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)],
938                                          res_graph_to_F[res_graph.head(e)]);
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        }
945      }
946      ++bfs;
947    } //computing distances from s in the residual graph
948
949    bool __augment=true;
950
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
958
959      typename MG::template NodeMap<Num> free(F);
960
961      dfs.pushAndSetReached(sF);
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 {
972              free.set(w, residual_capacity[dfs]);
973            }
974            if (w==tF) {
975              __augment=true;
976              _augment=true;
977              break;
978            }
979
980          } else {
981            F.erase(/*typename MG::OutEdgeIt*/(dfs));
982          }
983        }
984      }
985
986      if (__augment) {
987        typename MG::Node n=tF;
988        Num augment_value=free[tF];
989        while (F.valid(pred[n])) {
990          typename MG::Edge e=pred[n];
991          res_graph.augment(original_edge[e], augment_value);
992          n=F.tail(e);
993          if (residual_capacity[e]==augment_value)
994            F.erase(e);
995          else
996            residual_capacity.set(e, residual_capacity[e]-augment_value);
997        }
998      }
999
1000    }
1001
1002    return _augment;
1003  }
1004
1005
1006
1007
1008  template <typename Graph, typename Num, typename CapMap, typename FlowMap>
1009  bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow2()
1010  {
1011    bool _augment=false;
1012
1013    ResGW res_graph(*g, *capacity, *flow);
1014
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);
1018
1019    bfs.pushAndSetReached(s);
1020    DistanceMap<ResGW> dist(res_graph);
1021    while ( !bfs.finished() ) {
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
1028
1029      //Subgraph containing the edges on some shortest paths
1030    ConstMap<typename ResGW::Node, bool> true_map(true);
1031    typedef SubGraphWrapper<ResGW, ConstMap<typename ResGW::Node, bool>,
1032      DistanceMap<ResGW> > FilterResGW;
1033    FilterResGW filter_res_graph(res_graph, true_map, dist);
1034
1035    //Subgraph, which is able to delete edges which are already
1036    //met by the dfs
1037    typename FilterResGW::template NodeMap<typename FilterResGW::OutEdgeIt>
1038      first_out_edges(filter_res_graph);
1039    typename FilterResGW::NodeIt v;
1040    for(filter_res_graph.first(v); filter_res_graph.valid(v);
1041        filter_res_graph.next(v))
1042      {
1043        typename FilterResGW::OutEdgeIt e;
1044        filter_res_graph.first(e, v);
1045        first_out_edges.set(v, e);
1046      }
1047    typedef ErasingFirstGraphWrapper<FilterResGW, typename FilterResGW::
1048      template NodeMap<typename FilterResGW::OutEdgeIt> > ErasingResGW;
1049    ErasingResGW erasing_res_graph(filter_res_graph, first_out_edges);
1050
1051    bool __augment=true;
1052
1053    while (__augment) {
1054
1055      __augment=false;
1056      //computing blocking flow with dfs
1057      DfsIterator< ErasingResGW,
1058        typename ErasingResGW::template NodeMap<bool> >
1059        dfs(erasing_res_graph);
1060      typename ErasingResGW::
1061        template NodeMap<typename ErasingResGW::OutEdgeIt>
1062        pred(erasing_res_graph);
1063      pred.set(s, INVALID);
1064      //invalid iterators for sources
1065
1066      typename ErasingResGW::template NodeMap<Num>
1067        free1(erasing_res_graph);
1068
1069      dfs.pushAndSetReached
1070        ///\bug hugo 0.2
1071        (typename ErasingResGW::Node
1072         (typename FilterResGW::Node
1073          (typename ResGW::Node(s)
1074           )
1075          )
1076         );
1077      while (!dfs.finished()) {
1078        ++dfs;
1079        if (erasing_res_graph.valid(typename ErasingResGW::OutEdgeIt(dfs)))
1080          {
1081            if (dfs.isBNodeNewlyReached()) {
1082
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])) {
1088                free1.set
1089                  (w, std::min(free1[v], res_graph.resCap
1090                               (typename ErasingResGW::OutEdgeIt(dfs))));
1091              } else {
1092                free1.set
1093                  (w, res_graph.resCap
1094                   (typename ErasingResGW::OutEdgeIt(dfs)));
1095              }
1096
1097              if (w==t) {
1098                __augment=true;
1099                _augment=true;
1100                break;
1101              }
1102            } else {
1103              erasing_res_graph.erase(dfs);
1104            }
1105          }
1106      }
1107
1108      if (__augment) {
1109        typename ErasingResGW::Node
1110          n=typename FilterResGW::Node(typename ResGW::Node(t));
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];
1121        while (erasing_res_graph.valid(pred[n])) {
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);
1127        }
1128      }
1129
1130    } //while (__augment)
1131
1132    return _augment;
1133  }
1134
1135
1136} //namespace hugo
1137
1138#endif //HUGO_MAX_FLOW_H
1139
1140
1141
1142
Note: See TracBrowser for help on using the repository browser.