COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/work/jacint/max_flow.h @ 656:9971eb8bfbe8

Last change on this file since 656:9971eb8bfbe8 was 656:9971eb8bfbe8, checked in by marci, 17 years ago

max_flow.h bug correction

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