COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/hugo/max_flow.h @ 773:ce9438c5a82d

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

bug fix, test...

File size: 24.3 KB
Line 
1// -*- C++ -*-
2#ifndef HUGO_MAX_FLOW_H
3#define HUGO_MAX_FLOW_H
4
5#include <vector>
6#include <queue>
7
8#include <hugo/graph_wrapper.h>
9#include <hugo/invalid.h>
10#include <hugo/maps.h>
11
12/// \file
13/// \ingroup flowalgs
14
15namespace hugo {
16
17  /// \addtogroup flowalgs
18  /// @{                                                   
19
20  ///Maximum flow algorithms class.
21
22  ///This class provides various algorithms for finding a flow of
23  ///maximum value in a directed graph. The \e source node, the \e
24  ///target node, the \e capacity of the edges and the \e starting \e
25  ///flow value of the edges should be passed to the algorithm through the
26  ///constructor. It is possible to change these quantities using the
27  ///functions \ref setSource, \ref setTarget, \ref setCap and
28  ///\ref setFlow. Before any subsequent runs of any algorithm of
29  ///the class \ref setFlow should be called.
30  ///
31  ///After running an algorithm of the class, the actual flow value
32  ///can be obtained by calling \ref flowValue(). The minimum
33  ///value cut can be written into a \c node map of \c bools by
34  ///calling \ref minCut. (\ref minMinCut and \ref maxMinCut writes
35  ///the inclusionwise minimum and maximum of the minimum value
36  ///cuts, resp.)
37  ///
38  ///\param Graph The directed graph type the algorithm runs on.
39  ///\param Num The number type of the capacities and the flow values.
40  ///\param CapMap The capacity map type.
41  ///\param FlowMap The flow map type.
42  ///
43  ///\author Marton Makai, Jacint Szabo
44  template <typename Graph, typename Num,
45            typename CapMap=typename Graph::template EdgeMap<Num>,
46            typename FlowMap=typename Graph::template EdgeMap<Num> >
47  class MaxFlow {
48  protected:
49    typedef typename Graph::Node Node;
50    typedef typename Graph::NodeIt NodeIt;
51    typedef typename Graph::EdgeIt EdgeIt;
52    typedef typename Graph::OutEdgeIt OutEdgeIt;
53    typedef typename Graph::InEdgeIt InEdgeIt;
54
55    typedef typename std::vector<Node> VecFirst;
56    typedef typename Graph::template NodeMap<Node> NNMap;
57    typedef typename std::vector<Node> VecNode;
58
59    const Graph* g;
60    Node s;
61    Node t;
62    const CapMap* capacity;
63    FlowMap* flow;
64    int n;      //the number of nodes of G
65    typedef ResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;   
66    //typedef ExpResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
67    typedef typename ResGW::OutEdgeIt ResGWOutEdgeIt;
68    typedef typename ResGW::Edge ResGWEdge;
69    typedef typename Graph::template NodeMap<int> ReachedMap;
70
71
72    //level works as a bool map in augmenting path algorithms and is
73    //used by bfs for storing reached information.  In preflow, it
74    //shows the levels of nodes.     
75    ReachedMap level;
76
77    //excess is needed only in preflow
78    typename Graph::template NodeMap<Num> excess;
79
80    // constants used for heuristics
81    static const int H0=20;
82    static const int H1=1;
83
84  public:
85
86    ///Indicates the property of the starting flow.
87
88    ///Indicates the property of the starting flow. The meanings are as follows:
89    ///- \c ZERO_FLOW: constant zero flow
90    ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
91    ///the sum of the out-flows in every node except the \e source and
92    ///the \e target.
93    ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at
94    ///least the sum of the out-flows in every node except the \e source.
95    ///- \c NO_FLOW: indicates an unspecified edge map. \ref flow will be
96    ///set to the constant zero flow in the beginning of the algorithm in this case.
97    enum FlowEnum{
98      ZERO_FLOW,
99      GEN_FLOW,
100      PRE_FLOW,
101      NO_FLOW
102    };
103
104    enum StatusEnum {
105      AFTER_NOTHING,
106      AFTER_AUGMENTING,
107      AFTER_FAST_AUGMENTING,
108      AFTER_PRE_FLOW_PHASE_1,     
109      AFTER_PRE_FLOW_PHASE_2
110    };
111
112    /// Do not needle this flag only if necessary.
113    StatusEnum status;
114
115//     int number_of_augmentations;
116
117
118//     template<typename IntMap>
119//     class TrickyReachedMap {
120//     protected:
121//       IntMap* map;
122//       int* number_of_augmentations;
123//     public:
124//       TrickyReachedMap(IntMap& _map, int& _number_of_augmentations) :
125//      map(&_map), number_of_augmentations(&_number_of_augmentations) { }
126//       void set(const Node& n, bool b) {
127//      if (b)
128//        map->set(n, *number_of_augmentations);
129//      else
130//        map->set(n, *number_of_augmentations-1);
131//       }
132//       bool operator[](const Node& n) const {
133//      return (*map)[n]==*number_of_augmentations;
134//       }
135//     };
136   
137    ///Constructor
138
139    ///\todo Document, please.
140    ///
141    MaxFlow(const Graph& _G, Node _s, Node _t,
142            const CapMap& _capacity, FlowMap& _flow) :
143      g(&_G), s(_s), t(_t), capacity(&_capacity),
144      flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0),
145      status(AFTER_NOTHING) { }
146
147    ///Runs a maximum flow algorithm.
148
149    ///Runs a preflow algorithm, which is the fastest maximum flow
150    ///algorithm up-to-date. The default for \c fe is ZERO_FLOW.
151    ///\pre The starting flow must be
152    /// - a constant zero flow if \c fe is \c ZERO_FLOW,
153    /// - an arbitary flow if \c fe is \c GEN_FLOW,
154    /// - an arbitary preflow if \c fe is \c PRE_FLOW,
155    /// - any map if \c fe is NO_FLOW.
156    void run(FlowEnum fe=ZERO_FLOW) {
157      preflow(fe);
158    }
159
160                                                                             
161    ///Runs a preflow algorithm. 
162
163    ///Runs a preflow algorithm. The preflow algorithms provide the
164    ///fastest way to compute a maximum flow in a directed graph.
165    ///\pre The starting flow must be
166    /// - a constant zero flow if \c fe is \c ZERO_FLOW,
167    /// - an arbitary flow if \c fe is \c GEN_FLOW,
168    /// - an arbitary preflow if \c fe is \c PRE_FLOW,
169    /// - any map if \c fe is NO_FLOW.
170    ///
171    ///\todo NO_FLOW should be the default flow.
172    void preflow(FlowEnum fe) {
173      preflowPhase1(fe);
174      preflowPhase2();
175    }
176    // Heuristics:
177    //   2 phase
178    //   gap
179    //   list 'level_list' on the nodes on level i implemented by hand
180    //   stack 'active' on the active nodes on level i                                                                                   
181    //   runs heuristic 'highest label' for H1*n relabels
182    //   runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
183    //   Parameters H0 and H1 are initialized to 20 and 1.
184
185    ///Runs the first phase of the preflow algorithm.
186
187    ///The preflow algorithm consists of two phases, this method runs the
188    ///first phase. After the first phase the maximum flow value and a
189    ///minimum value cut can already be computed, though a maximum flow
190    ///is not yet obtained. So after calling this method \ref flowValue
191    ///and \ref actMinCut gives proper results.
192    ///\warning: \ref minCut, \ref minMinCut and \ref maxMinCut do not
193    ///give minimum value cuts unless calling \ref preflowPhase2.
194    ///\pre The starting flow must be
195    /// - a constant zero flow if \c fe is \c ZERO_FLOW,
196    /// - an arbitary flow if \c fe is \c GEN_FLOW,
197    /// - an arbitary preflow if \c fe is \c PRE_FLOW,
198    /// - any map if \c fe is NO_FLOW.
199    void preflowPhase1(FlowEnum fe)
200    {
201
202      int heur0=(int)(H0*n);  //time while running 'bound decrease'
203      int heur1=(int)(H1*n);  //time while running 'highest label'
204      int heur=heur1;         //starting time interval (#of relabels)
205      int numrelabel=0;
206
207      bool what_heur=1;
208      //It is 0 in case 'bound decrease' and 1 in case 'highest label'
209
210      bool end=false;
211      //Needed for 'bound decrease', true means no active nodes are above bound
212      //b.
213
214      int k=n-2;  //bound on the highest level under n containing a node
215      int b=k;    //bound on the highest level under n of an active node
216
217      VecFirst first(n, INVALID);
218      NNMap next(*g, INVALID); //maybe INVALID is not needed
219
220      NNMap left(*g, INVALID);
221      NNMap right(*g, INVALID);
222      VecNode level_list(n,INVALID);
223      //List of the nodes in level i<n, set to n.
224
225      preflowPreproc(fe, next, first, level_list, left, right);
226      //End of preprocessing
227
228      //Push/relabel on the highest level active nodes.
229      while ( true ) {
230        if ( b == 0 ) {
231          if ( !what_heur && !end && k > 0 ) {
232            b=k;
233            end=true;
234          } else break;
235        }
236
237        if ( !g->valid(first[b]) ) --b;
238        else {
239          end=false;
240          Node w=first[b];
241          first[b]=next[w];
242          int newlevel=push(w, next, first);
243          if ( excess[w] > 0 ) relabel(w, newlevel, next, first, level_list,
244                                       left, right, b, k, what_heur);
245
246          ++numrelabel;
247          if ( numrelabel >= heur ) {
248            numrelabel=0;
249            if ( what_heur ) {
250              what_heur=0;
251              heur=heur0;
252              end=false;
253            } else {
254              what_heur=1;
255              heur=heur1;
256              b=k;
257            }
258          }
259        }
260      }
261
262      status=AFTER_PRE_FLOW_PHASE_1;
263    }
264
265
266    ///Runs the second phase of the preflow algorithm.
267
268    ///The preflow algorithm consists of two phases, this method runs
269    ///the second phase. After calling \ref preflowPhase1 and then
270    ///\ref preflowPhase2 the methods \ref flowValue, \ref minCut,
271    ///\ref minMinCut and \ref maxMinCut give proper results.
272    ///\pre \ref preflowPhase1 must be called before.
273    void preflowPhase2()
274    {
275
276      int k=n-2;  //bound on the highest level under n containing a node
277      int b=k;    //bound on the highest level under n of an active node
278
279   
280      VecFirst first(n, INVALID);
281      NNMap next(*g, INVALID); //maybe INVALID is not needed
282      level.set(s,0);
283      std::queue<Node> bfs_queue;
284      bfs_queue.push(s);
285
286      while (!bfs_queue.empty()) {
287
288        Node v=bfs_queue.front();
289        bfs_queue.pop();
290        int l=level[v]+1;
291
292        InEdgeIt e;
293        for(g->first(e,v); g->valid(e); g->next(e)) {
294          if ( (*capacity)[e] <= (*flow)[e] ) continue;
295          Node u=g->tail(e);
296          if ( level[u] >= n ) {
297            bfs_queue.push(u);
298            level.set(u, l);
299            if ( excess[u] > 0 ) {
300              next.set(u,first[l]);
301              first[l]=u;
302            }
303          }
304        }
305
306        OutEdgeIt f;
307        for(g->first(f,v); g->valid(f); g->next(f)) {
308          if ( 0 >= (*flow)[f] ) continue;
309          Node u=g->head(f);
310          if ( level[u] >= n ) {
311            bfs_queue.push(u);
312            level.set(u, l);
313            if ( excess[u] > 0 ) {
314              next.set(u,first[l]);
315              first[l]=u;
316            }
317          }
318        }
319      }
320      b=n-2;
321
322      while ( true ) {
323
324        if ( b == 0 ) break;
325
326        if ( !g->valid(first[b]) ) --b;
327        else {
328
329          Node w=first[b];
330          first[b]=next[w];
331          int newlevel=push(w,next, first/*active*/);
332
333          //relabel
334          if ( excess[w] > 0 ) {
335            level.set(w,++newlevel);
336            next.set(w,first[newlevel]);
337            first[newlevel]=w;
338            b=newlevel;
339          }
340        }
341      } // while(true)
342
343      status=AFTER_PRE_FLOW_PHASE_2;
344    }
345
346
347    /// Returns the value of the maximum flow.
348
349    /// Returns the excess of the target node \ref t.
350    /// After running \ref preflowPhase1, this is the value of
351    /// the maximum flow.
352    /// It can be called already after running \ref preflowPhase1.
353    Num flowValue() const {
354//       Num a=0;
355//       for(InEdgeIt e(*g,t);g->valid(e);g->next(e)) a+=(*flow)[e];
356//       for(OutEdgeIt e(*g,t);g->valid(e);g->next(e)) a-=(*flow)[e];
357//       return a;
358      return excess[t];
359      //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan   
360    }
361
362
363    ///Returns a minimum value cut after calling \ref preflowPhase1.
364
365    ///After the first phase of the preflow algorithm the maximum flow
366    ///value and a minimum value cut can already be computed. This
367    ///method can be called after running \ref preflowPhase1 for
368    ///obtaining a minimum value cut.
369    /// \warning Gives proper result only right after calling \ref
370    /// preflowPhase1.
371    /// \todo We have to make some status variable which shows the
372    /// actual state
373    /// of the class. This enables us to determine which methods are valid
374    /// for MinCut computation
375    template<typename _CutMap>
376    void actMinCut(_CutMap& M) const {
377      NodeIt v;
378      switch (status) {
379      case AFTER_PRE_FLOW_PHASE_1:
380        for(g->first(v); g->valid(v); g->next(v)) {
381          if (level[v] < n) {
382            M.set(v, false);
383          } else {
384            M.set(v, true);
385          }
386        }
387        break;
388      case AFTER_PRE_FLOW_PHASE_2:
389      case AFTER_NOTHING:
390      case AFTER_AUGMENTING:
391      case AFTER_FAST_AUGMENTING:
392        minMinCut(M);
393        break;
394      }
395    }
396
397    ///Returns the inclusionwise minimum of the minimum value cuts.
398
399    ///Sets \c M to the characteristic vector of the minimum value cut
400    ///which is inclusionwise minimum. It is computed by processing
401    ///a bfs from the source node \c s in the residual graph.
402    ///\pre M should be a node map of bools initialized to false.
403    ///\pre \c flow must be a maximum flow.
404    template<typename _CutMap>
405    void minMinCut(_CutMap& M) const {
406      std::queue<Node> queue;
407
408      M.set(s,true);
409      queue.push(s);
410
411      while (!queue.empty()) {
412        Node w=queue.front();
413        queue.pop();
414
415        OutEdgeIt e;
416        for(g->first(e,w) ; g->valid(e); g->next(e)) {
417          Node v=g->head(e);
418          if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
419            queue.push(v);
420            M.set(v, true);
421          }
422        }
423
424        InEdgeIt f;
425        for(g->first(f,w) ; g->valid(f); g->next(f)) {
426          Node v=g->tail(f);
427          if (!M[v] && (*flow)[f] > 0 ) {
428            queue.push(v);
429            M.set(v, true);
430          }
431        }
432      }
433    }
434
435    ///Returns the inclusionwise maximum of the minimum value cuts.
436
437    ///Sets \c M to the characteristic vector of the minimum value cut
438    ///which is inclusionwise maximum. It is computed by processing a
439    ///backward bfs from the target node \c t in the residual graph.
440    ///\pre M should be a node map of bools initialized to false.
441    ///\pre \c flow must be a maximum flow.
442    template<typename _CutMap>
443    void maxMinCut(_CutMap& M) const {
444
445      NodeIt v;
446      for(g->first(v) ; g->valid(v); g->next(v)) {
447        M.set(v, true);
448      }
449
450      std::queue<Node> queue;
451
452      M.set(t,false);
453      queue.push(t);
454
455      while (!queue.empty()) {
456        Node w=queue.front();
457        queue.pop();
458
459        InEdgeIt e;
460        for(g->first(e,w) ; g->valid(e); g->next(e)) {
461          Node v=g->tail(e);
462          if (M[v] && (*flow)[e] < (*capacity)[e] ) {
463            queue.push(v);
464            M.set(v, false);
465          }
466        }
467
468        OutEdgeIt f;
469        for(g->first(f,w) ; g->valid(f); g->next(f)) {
470          Node v=g->head(f);
471          if (M[v] && (*flow)[f] > 0 ) {
472            queue.push(v);
473            M.set(v, false);
474          }
475        }
476      }
477    }
478
479    ///Returns a minimum value cut.
480
481    ///Sets \c M to the characteristic vector of a minimum value cut.
482    ///\pre M should be a node map of bools initialized to false.
483    ///\pre \c flow must be a maximum flow.   
484    template<typename CutMap>
485    void minCut(CutMap& M) const { minMinCut(M); }
486
487    ///Sets the source node to \c _s.
488
489    ///Sets the source node to \c _s.
490    ///
491    void setSource(Node _s) { s=_s; status=AFTER_NOTHING; }
492
493    ///Sets the target node to \c _t.
494
495    ///Sets the target node to \c _t.
496    ///
497    void setTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
498
499    /// Sets the edge map of the capacities to _cap.
500
501    /// Sets the edge map of the capacities to _cap.
502    ///
503    void setCap(const CapMap& _cap)
504    { capacity=&_cap; status=AFTER_NOTHING; }
505
506    /// Sets the edge map of the flows to _flow.
507
508    /// Sets the edge map of the flows to _flow.
509    ///
510    void setFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
511
512
513  private:
514
515    int push(Node w, NNMap& next, VecFirst& first) {
516
517      int lev=level[w];
518      Num exc=excess[w];
519      int newlevel=n;       //bound on the next level of w
520
521      OutEdgeIt e;
522      for(g->first(e,w); g->valid(e); g->next(e)) {
523
524        if ( (*flow)[e] >= (*capacity)[e] ) continue;
525        Node v=g->head(e);
526
527        if( lev > level[v] ) { //Push is allowed now
528
529          if ( excess[v]<=0 && v!=t && v!=s ) {
530            next.set(v,first[level[v]]);
531            first[level[v]]=v;
532          }
533
534          Num cap=(*capacity)[e];
535          Num flo=(*flow)[e];
536          Num remcap=cap-flo;
537
538          if ( remcap >= exc ) { //A nonsaturating push.
539
540            flow->set(e, flo+exc);
541            excess.set(v, excess[v]+exc);
542            exc=0;
543            break;
544
545          } else { //A saturating push.
546            flow->set(e, cap);
547            excess.set(v, excess[v]+remcap);
548            exc-=remcap;
549          }
550        } else if ( newlevel > level[v] ) newlevel = level[v];
551      } //for out edges wv
552
553      if ( exc > 0 ) {
554        InEdgeIt e;
555        for(g->first(e,w); g->valid(e); g->next(e)) {
556
557          if( (*flow)[e] <= 0 ) continue;
558          Node v=g->tail(e);
559
560          if( lev > level[v] ) { //Push is allowed now
561
562            if ( excess[v]<=0 && v!=t && v!=s ) {
563              next.set(v,first[level[v]]);
564              first[level[v]]=v;
565            }
566
567            Num flo=(*flow)[e];
568
569            if ( flo >= exc ) { //A nonsaturating push.
570
571              flow->set(e, flo-exc);
572              excess.set(v, excess[v]+exc);
573              exc=0;
574              break;
575            } else {  //A saturating push.
576
577              excess.set(v, excess[v]+flo);
578              exc-=flo;
579              flow->set(e,0);
580            }
581          } else if ( newlevel > level[v] ) newlevel = level[v];
582        } //for in edges vw
583
584      } // if w still has excess after the out edge for cycle
585
586      excess.set(w, exc);
587
588      return newlevel;
589    }
590
591
592
593    void preflowPreproc(FlowEnum fe, NNMap& next, VecFirst& first,
594                        VecNode& level_list, NNMap& left, NNMap& right)
595    {
596      switch (fe) { //setting excess
597        case NO_FLOW:
598        {
599          EdgeIt e;
600          for(g->first(e); g->valid(e); g->next(e)) flow->set(e,0);
601         
602          NodeIt v;
603          for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
604          break;
605        }
606        case ZERO_FLOW:
607        {
608          NodeIt v;
609          for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
610          break;
611        }
612        case GEN_FLOW:
613        {
614          NodeIt v;
615          for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
616
617          Num exc=0;
618          InEdgeIt e;
619          for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
620          OutEdgeIt f;
621          for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
622          excess.set(t,exc);
623          break;
624        }
625        default: break;
626      }
627
628      NodeIt v;
629      for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
630      //setting each node to level n
631     
632      std::queue<Node> bfs_queue;
633
634
635      switch (fe) {
636      case NO_FLOW:   //flow is already set to const zero
637      case ZERO_FLOW:
638        {
639          //Reverse_bfs from t, to find the starting level.
640          level.set(t,0);
641          bfs_queue.push(t);
642
643          while (!bfs_queue.empty()) {
644
645            Node v=bfs_queue.front();
646            bfs_queue.pop();
647            int l=level[v]+1;
648
649            InEdgeIt e;
650            for(g->first(e,v); g->valid(e); g->next(e)) {
651              Node w=g->tail(e);
652              if ( level[w] == n && w != s ) {
653                bfs_queue.push(w);
654                Node z=level_list[l];
655                if ( g->valid(z) ) left.set(z,w);
656                right.set(w,z);
657                level_list[l]=w;
658                level.set(w, l);
659              }
660            }
661          }
662
663          //the starting flow
664          OutEdgeIt e;
665          for(g->first(e,s); g->valid(e); g->next(e))
666            {
667              Num c=(*capacity)[e];
668              if ( c <= 0 ) continue;
669              Node w=g->head(e);
670              if ( level[w] < n ) {
671                if ( excess[w] <= 0 && w!=t ) //putting into the stack
672                  {
673                    next.set(w,first[level[w]]);
674                    first[level[w]]=w;
675                  }
676                flow->set(e, c);
677                excess.set(w, excess[w]+c);
678              }
679            }
680          break;
681        }
682
683      case GEN_FLOW:
684        {
685          //Reverse_bfs from t in the residual graph,
686          //to find the starting level.
687          level.set(t,0);
688          bfs_queue.push(t);
689
690          while (!bfs_queue.empty()) {
691
692            Node v=bfs_queue.front();
693            bfs_queue.pop();
694            int l=level[v]+1;
695
696            InEdgeIt e;
697            for(g->first(e,v); g->valid(e); g->next(e)) {
698              if ( (*capacity)[e] <= (*flow)[e] ) continue;
699              Node w=g->tail(e);
700              if ( level[w] == n && w != s ) {
701                bfs_queue.push(w);
702                Node z=level_list[l];
703                if ( g->valid(z) ) left.set(z,w);
704                right.set(w,z);
705                level_list[l]=w;
706                level.set(w, l);
707              }
708            }
709
710            OutEdgeIt f;
711            for(g->first(f,v); g->valid(f); g->next(f)) {
712              if ( 0 >= (*flow)[f] ) continue;
713              Node w=g->head(f);
714              if ( level[w] == n && w != s ) {
715                bfs_queue.push(w);
716                Node z=level_list[l];
717                if ( g->valid(z) ) left.set(z,w);
718                right.set(w,z);
719                level_list[l]=w;
720                level.set(w, l);
721              }
722            }
723          }
724
725          //the starting flow
726          OutEdgeIt e;
727          for(g->first(e,s); g->valid(e); g->next(e))
728            {
729              Num rem=(*capacity)[e]-(*flow)[e];
730              if ( rem <= 0 ) continue;
731              Node w=g->head(e);
732              if ( level[w] < n ) {
733                if ( excess[w] <= 0 && w!=t ) //putting into the stack
734                  {
735                    next.set(w,first[level[w]]);
736                    first[level[w]]=w;
737                  }   
738                flow->set(e, (*capacity)[e]);
739                excess.set(w, excess[w]+rem);
740              }
741            }
742
743          InEdgeIt f;
744          for(g->first(f,s); g->valid(f); g->next(f))
745            {
746              if ( (*flow)[f] <= 0 ) continue;
747              Node w=g->tail(f);
748              if ( level[w] < n ) {
749                if ( excess[w] <= 0 && w!=t )
750                  {
751                    next.set(w,first[level[w]]);
752                    first[level[w]]=w;
753                  } 
754                excess.set(w, excess[w]+(*flow)[f]);
755                flow->set(f, 0);
756              }
757            }
758          break;
759        } //case GEN_FLOW
760   
761      case PRE_FLOW:
762        {
763          //Reverse_bfs from t in the residual graph,
764          //to find the starting level.
765          level.set(t,0);
766          bfs_queue.push(t);
767
768          while (!bfs_queue.empty()) {
769
770            Node v=bfs_queue.front();
771            bfs_queue.pop();
772            int l=level[v]+1;
773
774            InEdgeIt e;
775            for(g->first(e,v); g->valid(e); g->next(e)) {
776              if ( (*capacity)[e] <= (*flow)[e] ) continue;
777              Node w=g->tail(e);
778              if ( level[w] == n && w != s ) {
779                bfs_queue.push(w);
780                Node z=level_list[l];
781                if ( g->valid(z) ) left.set(z,w);
782                right.set(w,z);
783                level_list[l]=w;
784                level.set(w, l);
785              }
786            }
787
788            OutEdgeIt f;
789            for(g->first(f,v); g->valid(f); g->next(f)) {
790              if ( 0 >= (*flow)[f] ) continue;
791              Node w=g->head(f);
792              if ( level[w] == n && w != s ) {
793                bfs_queue.push(w);
794                Node z=level_list[l];
795                if ( g->valid(z) ) left.set(z,w);
796                right.set(w,z);
797                level_list[l]=w;
798                level.set(w, l);
799              }
800            }
801          }
802
803
804          //the starting flow
805          OutEdgeIt e;
806          for(g->first(e,s); g->valid(e); g->next(e))
807            {
808              Num rem=(*capacity)[e]-(*flow)[e];
809              if ( rem <= 0 ) continue;
810              Node w=g->head(e);
811              if ( level[w] < n ) {
812                flow->set(e, (*capacity)[e]);
813                excess.set(w, excess[w]+rem);
814              }
815            }
816
817          InEdgeIt f;
818          for(g->first(f,s); g->valid(f); g->next(f))
819            {
820              if ( (*flow)[f] <= 0 ) continue;
821              Node w=g->tail(f);
822              if ( level[w] < n ) {
823                excess.set(w, excess[w]+(*flow)[f]);
824                flow->set(f, 0);
825              }
826            }
827         
828          NodeIt w; //computing the excess
829          for(g->first(w); g->valid(w); g->next(w)) {
830            Num exc=0;
831
832            InEdgeIt e;
833            for(g->first(e,w); g->valid(e); g->next(e)) exc+=(*flow)[e];
834            OutEdgeIt f;
835            for(g->first(f,w); g->valid(f); g->next(f)) exc-=(*flow)[f];
836
837            excess.set(w,exc);
838
839            //putting the active nodes into the stack
840            int lev=level[w];
841            if ( exc > 0 && lev < n && Node(w) != t )
842///\bug     if ( exc > 0 && lev < n && w != t ) tempararily for working with wrappers. in hugo 0.2 it will work. Amugy mukodik sage_graph-fal, de smart_graph-fal nem, azt hozzatennem.
843              {
844                next.set(w,first[lev]);
845                first[lev]=w;
846              }
847          }
848          break;
849        } //case PRE_FLOW
850      }
851    } //preflowPreproc
852
853
854    void relabel(Node w, int newlevel, NNMap& next, VecFirst& first,
855                 VecNode& level_list, NNMap& left,
856                 NNMap& right, int& b, int& k, bool what_heur )
857    {
858
859      int lev=level[w];
860
861      Node right_n=right[w];
862      Node left_n=left[w];
863
864      //unlacing starts
865      if ( g->valid(right_n) ) {
866        if ( g->valid(left_n) ) {
867          right.set(left_n, right_n);
868          left.set(right_n, left_n);
869        } else {
870          level_list[lev]=right_n;
871          left.set(right_n, INVALID);
872        }
873      } else {
874        if ( g->valid(left_n) ) {
875          right.set(left_n, INVALID);
876        } else {
877          level_list[lev]=INVALID;
878        }
879      }
880      //unlacing ends
881
882      if ( !g->valid(level_list[lev]) ) {
883
884        //gapping starts
885        for (int i=lev; i!=k ; ) {
886          Node v=level_list[++i];
887          while ( g->valid(v) ) {
888            level.set(v,n);
889            v=right[v];
890          }
891          level_list[i]=INVALID;
892          if ( !what_heur ) first[i]=INVALID;
893        }
894
895        level.set(w,n);
896        b=lev-1;
897        k=b;
898        //gapping ends
899
900      } else {
901
902        if ( newlevel == n ) level.set(w,n);
903        else {
904          level.set(w,++newlevel);
905          next.set(w,first[newlevel]);
906          first[newlevel]=w;
907          if ( what_heur ) b=newlevel;
908          if ( k < newlevel ) ++k;      //now k=newlevel
909          Node z=level_list[newlevel];
910          if ( g->valid(z) ) left.set(z,w);
911          right.set(w,z);
912          left.set(w,INVALID);
913          level_list[newlevel]=w;
914        }
915      }
916    } //relabel
917
918    void printexcess() {////
919      std::cout << "Excesses:" <<std::endl;
920
921      NodeIt v;
922      for(g->first(v); g->valid(v); g->next(v)) {
923        std::cout << 1+(g->id(v)) << ":" << excess[v]<<std::endl;
924      }
925    }
926
927 void printlevel() {////
928      std::cout << "Levels:" <<std::endl;
929
930      NodeIt v;
931      for(g->first(v); g->valid(v); g->next(v)) {
932        std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
933      }
934    }
935
936void printactive() {////
937      std::cout << "Levels:" <<std::endl;
938
939      NodeIt v;
940      for(g->first(v); g->valid(v); g->next(v)) {
941        std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
942      }
943    }
944
945
946  };  //class MaxFlow
947} //namespace hugo
948
949#endif //HUGO_MAX_FLOW_H
950
951
952
953
Note: See TracBrowser for help on using the repository browser.