COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/work/jacint/max_flow.h @ 815:468c9ec86928

Last change on this file since 815:468c9ec86928 was 709:7a518df79892, checked in by Alpar Juttner, 20 years ago

docfix

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