# source:lemon-0.x/src/work/jacint/max_flow.h@647:19dd325da0e8

Last change on this file since 647:19dd325da0e8 was 647:19dd325da0e8, checked in by marci, 18 years ago

the same

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