More documented file.
2 #ifndef HUGO_MAX_FLOW_NO_STACK_H
3 #define HUGO_MAX_FLOW_NO_STACK_H
9 #include <hugo/graph_wrapper.h>
10 #include <hugo/invalid.h>
11 #include <hugo/maps.h>
14 /// \brief The same as max_flow.h, but without using stl stack for the active nodes. Only for test.
21 ///Maximum flow algorithms class.
23 ///This class provides various algorithms for finding a flow of
24 ///maximum value in a directed graph. The \e source node, the \e
25 ///target node, the \e capacity of the edges and the \e starting \e
26 ///flow value of the edges should be passed to the algorithm through the
27 ///constructor. It is possible to change these quantities using the
28 ///functions \ref resetSource, \ref resetTarget, \ref resetCap and
29 ///\ref resetFlow. Before any subsequent runs of any algorithm of
30 ///the class \ref resetFlow should be called.
32 ///After running an algorithm of the class, the actual flow value
33 ///can be obtained by calling \ref flowValue(). The minimum
34 ///value cut can be written into a \c node map of \c bools by
35 ///calling \ref minCut. (\ref minMinCut and \ref maxMinCut writes
36 ///the inclusionwise minimum and maximum of the minimum value
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 ///\author Marton Makai, Jacint Szabo
43 template <typename Graph, typename Num,
44 typename CapMap=typename Graph::template EdgeMap<Num>,
45 typename FlowMap=typename Graph::template EdgeMap<Num> >
48 typedef typename Graph::Node Node;
49 typedef typename Graph::NodeIt NodeIt;
50 typedef typename Graph::EdgeIt EdgeIt;
51 typedef typename Graph::OutEdgeIt OutEdgeIt;
52 typedef typename Graph::InEdgeIt InEdgeIt;
54 // typedef typename std::vector<std::stack<Node> > VecStack;
55 typedef typename std::vector<Node> VecFirst;
56 typedef typename Graph::template NodeMap<Node> NNMap;
57 typedef typename std::vector<Node> VecNode;
62 const CapMap* capacity;
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 ResGW::template NodeMap<bool> ReachedMap;
70 typedef typename Graph::template NodeMap<int> ReachedMap;
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.
78 //excess is needed only in preflow
79 typename Graph::template NodeMap<Num> excess;
81 // constants used for heuristics
82 static const int H0=20;
83 static const int H1=1;
87 ///Indicates the property of the starting flow.
89 ///Indicates the property of the starting flow. The meanings are as follows:
90 ///- \c ZERO_FLOW: constant zero flow
91 ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
92 ///the sum of the out-flows in every node except the \e source and
94 ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at
95 ///least the sum of the out-flows in every node except the \e source.
96 ///- \c NO_FLOW: indicates an unspecified edge map. \ref flow will be
97 ///set to the constant zero flow in the beginning of the algorithm in this case.
108 AFTER_FAST_AUGMENTING,
109 AFTER_PRE_FLOW_PHASE_1,
110 AFTER_PRE_FLOW_PHASE_2
113 /// Don not needle this flag only if necessary.
116 // int number_of_augmentations;
119 // template<typename IntMap>
120 // class TrickyReachedMap {
123 // int* number_of_augmentations;
125 // TrickyReachedMap(IntMap& _map, int& _number_of_augmentations) :
126 // map(&_map), number_of_augmentations(&_number_of_augmentations) { }
127 // void set(const Node& n, bool b) {
129 // map->set(n, *number_of_augmentations);
131 // map->set(n, *number_of_augmentations-1);
133 // bool operator[](const Node& n) const {
134 // return (*map)[n]==*number_of_augmentations;
140 ///\todo Document, please.
142 MaxFlow(const Graph& _G, Node _s, Node _t,
143 const CapMap& _capacity, FlowMap& _flow) :
144 g(&_G), s(_s), t(_t), capacity(&_capacity),
145 flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0),
146 status(AFTER_NOTHING) { }
148 ///Runs a maximum flow algorithm.
150 ///Runs a preflow algorithm, which is the fastest maximum flow
151 ///algorithm up-to-date. The default for \c fe is ZERO_FLOW.
152 ///\pre The starting flow must be
153 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
154 /// - an arbitary flow if \c fe is \c GEN_FLOW,
155 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
156 /// - any map if \c fe is NO_FLOW.
157 void run(FlowEnum fe=ZERO_FLOW) {
162 ///Runs a preflow algorithm.
164 ///Runs a preflow algorithm. The preflow algorithms provide the
165 ///fastest way to compute a maximum flow in a directed graph.
166 ///\pre The starting flow must be
167 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
168 /// - an arbitary flow if \c fe is \c GEN_FLOW,
169 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
170 /// - any map if \c fe is NO_FLOW.
172 ///\todo NO_FLOW should be the default flow.
173 void preflow(FlowEnum fe) {
180 // list 'level_list' on the nodes on level i implemented by hand
181 // stack 'active' on the active nodes on level i
182 // runs heuristic 'highest label' for H1*n relabels
183 // runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
184 // Parameters H0 and H1 are initialized to 20 and 1.
186 ///Runs the first phase of the preflow algorithm.
188 ///The preflow algorithm consists of two phases, this method runs the
189 ///first phase. After the first phase the maximum flow value and a
190 ///minimum value cut can already be computed, though a maximum flow
191 ///is net yet obtained. So after calling this method \ref flowValue
192 ///and \ref actMinCut gives proper results.
193 ///\warning: \ref minCut, \ref minMinCut and \ref maxMinCut do not
194 ///give minimum value cuts unless calling \ref preflowPhase2.
195 ///\pre The starting flow must be
196 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
197 /// - an arbitary flow if \c fe is \c GEN_FLOW,
198 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
199 /// - any map if \c fe is NO_FLOW.
200 void preflowPhase1(FlowEnum fe)
203 int heur0=(int)(H0*n); //time while running 'bound decrease'
204 int heur1=(int)(H1*n); //time while running 'highest label'
205 int heur=heur1; //starting time interval (#of relabels)
209 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
212 //Needed for 'bound decrease', true means no active nodes are above bound
215 int k=n-2; //bound on the highest level under n containing a node
216 int b=k; //bound on the highest level under n of an active node
218 VecFirst first(n, INVALID);
219 NNMap next(*g, INVALID); //maybe INVALID is not needed
220 // VecStack active(n);
222 NNMap left(*g, INVALID);
223 NNMap right(*g, INVALID);
224 VecNode level_list(n,INVALID);
225 //List of the nodes in level i<n, set to n.
228 for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
229 //setting each node to level n
231 if ( fe == NO_FLOW ) {
233 for(g->first(e); g->valid(e); g->next(e)) flow->set(e,0);
236 switch (fe) { //computing the excess
240 for(g->first(v); g->valid(v); g->next(v)) {
244 for(g->first(e,v); g->valid(e); g->next(e)) exc+=(*flow)[e];
246 for(g->first(f,v); g->valid(f); g->next(f)) exc-=(*flow)[f];
250 //putting the active nodes into the stack
252 if ( exc > 0 && lev < n && v != t )
254 next.set(v,first[lev]);
257 // active[lev].push(v);
264 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
268 for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
270 for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
278 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
283 preflowPreproc(fe, next, first,/*active*/ level_list, left, right);
284 //End of preprocessing
287 //Push/relabel on the highest level active nodes.
290 if ( !what_heur && !end && k > 0 ) {
296 if ( !g->valid(first[b])/*active[b].empty()*/ ) --b;
301 /* Node w=active[b].top();
303 int newlevel=push(w,/*active*/next, first);
304 if ( excess[w] > 0 ) relabel(w, newlevel, /*active*/next, first, level_list,
305 left, right, b, k, what_heur);
308 if ( numrelabel >= heur ) {
323 status=AFTER_PRE_FLOW_PHASE_1;
327 ///Runs the second phase of the preflow algorithm.
329 ///The preflow algorithm consists of two phases, this method runs
330 ///the second phase. After calling \ref preflowPhase1 and then
331 ///\ref preflowPhase2 the methods \ref flowValue, \ref minCut,
332 ///\ref minMinCut and \ref maxMinCut give proper results.
333 ///\pre \ref preflowPhase1 must be called before.
337 int k=n-2; //bound on the highest level under n containing a node
338 int b=k; //bound on the highest level under n of an active node
341 VecFirst first(n, INVALID);
342 NNMap next(*g, INVALID); //maybe INVALID is not needed
343 // VecStack active(n);
345 std::queue<Node> bfs_queue;
348 while (!bfs_queue.empty()) {
350 Node v=bfs_queue.front();
355 for(g->first(e,v); g->valid(e); g->next(e)) {
356 if ( (*capacity)[e] <= (*flow)[e] ) continue;
358 if ( level[u] >= n ) {
361 if ( excess[u] > 0 ) {
362 next.set(u,first[l]);
370 for(g->first(f,v); g->valid(f); g->next(f)) {
371 if ( 0 >= (*flow)[f] ) continue;
373 if ( level[u] >= n ) {
376 if ( excess[u] > 0 ) {
377 next.set(u,first[l]);
390 if ( !g->valid(first[b])/*active[b].empty()*/ ) --b;
395 /* Node w=active[b].top();
397 int newlevel=push(w,next, first/*active*/);
400 if ( excess[w] > 0 ) {
401 level.set(w,++newlevel);
402 next.set(w,first[newlevel]);
404 //active[newlevel].push(w);
407 } // if stack[b] is nonempty
410 status=AFTER_PRE_FLOW_PHASE_2;
414 /// Returns the maximum value of a flow.
416 /// Returns the maximum value of a flow, by counting the
417 /// over-flow of the target node \ref t.
418 /// It can be called already after running \ref preflowPhase1.
419 Num flowValue() const {
421 for(InEdgeIt e(*g,t);g->valid(e);G.next(e)) a+=(*flow)[e];
422 for(OutEdgeIt e(*g,t);g->valid(e);G.next(e)) a-=(*flow)[e];
424 //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan
427 ///Returns a minimum value cut after calling \ref preflowPhase1.
429 ///After the first phase of the preflow algorithm the maximum flow
430 ///value and a minimum value cut can already be computed. This
431 ///method can be called after running \ref preflowPhase1 for
432 ///obtaining a minimum value cut.
433 /// \warning Gives proper result only right after calling \ref
435 /// \todo We have to make some status variable which shows the
437 /// of the class. This enables us to determine which methods are valid
438 /// for MinCut computation
439 template<typename _CutMap>
440 void actMinCut(_CutMap& M) const {
443 case AFTER_PRE_FLOW_PHASE_1:
444 for(g->first(v); g->valid(v); g->next(v)) {
452 case AFTER_PRE_FLOW_PHASE_2:
456 case AFTER_AUGMENTING:
457 for(g->first(v); g->valid(v); g->next(v)) {
465 case AFTER_FAST_AUGMENTING:
466 for(g->first(v); g->valid(v); g->next(v)) {
467 if (level[v]==number_of_augmentations) {
477 ///Returns the inclusionwise minimum of the minimum value cuts.
479 ///Sets \c M to the characteristic vector of the minimum value cut
480 ///which is inclusionwise minimum. It is computed by processing
481 ///a bfs from the source node \c s in the residual graph.
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 minMinCut(_CutMap& M) const {
486 std::queue<Node> queue;
491 while (!queue.empty()) {
492 Node w=queue.front();
496 for(g->first(e,w) ; g->valid(e); g->next(e)) {
498 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
505 for(g->first(f,w) ; g->valid(f); g->next(f)) {
507 if (!M[v] && (*flow)[f] > 0 ) {
515 ///Returns the inclusionwise maximum of the minimum value cuts.
517 ///Sets \c M to the characteristic vector of the minimum value cut
518 ///which is inclusionwise maximum. It is computed by processing a
519 ///backward bfs from the target node \c t in the residual graph.
520 ///\pre M should be a node map of bools initialized to false.
521 ///\pre \c flow must be a maximum flow.
522 template<typename _CutMap>
523 void maxMinCut(_CutMap& M) const {
526 for(g->first(v) ; g->valid(v); g->next(v)) {
530 std::queue<Node> queue;
535 while (!queue.empty()) {
536 Node w=queue.front();
540 for(g->first(e,w) ; g->valid(e); g->next(e)) {
542 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
549 for(g->first(f,w) ; g->valid(f); g->next(f)) {
551 if (M[v] && (*flow)[f] > 0 ) {
559 ///Returns a minimum value cut.
561 ///Sets \c M to the characteristic vector of a minimum value cut.
562 ///\pre M should be a node map of bools initialized to false.
563 ///\pre \c flow must be a maximum flow.
564 template<typename CutMap>
565 void minCut(CutMap& M) const { minMinCut(M); }
567 ///Resets the source node to \c _s.
569 ///Resets the source node to \c _s.
571 void resetSource(Node _s) { s=_s; status=AFTER_NOTHING; }
573 ///Resets the target node to \c _t.
575 ///Resets the target node to \c _t.
577 void resetTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
579 /// Resets the edge map of the capacities to _cap.
581 /// Resets the edge map of the capacities to _cap.
583 void resetCap(const CapMap& _cap)
584 { capacity=&_cap; status=AFTER_NOTHING; }
586 /// Resets the edge map of the flows to _flow.
588 /// Resets the edge map of the flows to _flow.
590 void resetFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
595 int push(Node w, NNMap& next, VecFirst& first) {
599 int newlevel=n; //bound on the next level of w
602 for(g->first(e,w); g->valid(e); g->next(e)) {
604 if ( (*flow)[e] >= (*capacity)[e] ) continue;
607 if( lev > level[v] ) { //Push is allowed now
609 if ( excess[v]<=0 && v!=t && v!=s ) {
610 next.set(v,first[level[v]]);
612 // int lev_v=level[v];
613 //active[lev_v].push(v);
616 Num cap=(*capacity)[e];
620 if ( remcap >= exc ) { //A nonsaturating push.
622 flow->set(e, flo+exc);
623 excess.set(v, excess[v]+exc);
627 } else { //A saturating push.
629 excess.set(v, excess[v]+remcap);
632 } else if ( newlevel > level[v] ) newlevel = level[v];
637 for(g->first(e,w); g->valid(e); g->next(e)) {
639 if( (*flow)[e] <= 0 ) continue;
642 if( lev > level[v] ) { //Push is allowed now
644 if ( excess[v]<=0 && v!=t && v!=s ) {
645 next.set(v,first[level[v]]);
647 //int lev_v=level[v];
648 //active[lev_v].push(v);
653 if ( flo >= exc ) { //A nonsaturating push.
655 flow->set(e, flo-exc);
656 excess.set(v, excess[v]+exc);
659 } else { //A saturating push.
661 excess.set(v, excess[v]+flo);
665 } else if ( newlevel > level[v] ) newlevel = level[v];
668 } // if w still has excess after the out edge for cycle
676 void preflowPreproc(FlowEnum fe, NNMap& next, VecFirst& first,
677 VecNode& level_list, NNMap& left, NNMap& right)
679 std::queue<Node> bfs_queue;
682 case NO_FLOW: //flow is already set to const zero in this case
685 //Reverse_bfs from t, to find the starting level.
689 while (!bfs_queue.empty()) {
691 Node v=bfs_queue.front();
696 for(g->first(e,v); g->valid(e); g->next(e)) {
698 if ( level[w] == n && w != s ) {
700 Node z=level_list[l];
701 if ( g->valid(z) ) left.set(z,w);
711 for(g->first(e,s); g->valid(e); g->next(e))
713 Num c=(*capacity)[e];
714 if ( c <= 0 ) continue;
716 if ( level[w] < n ) {
717 if ( excess[w] <= 0 && w!=t )
719 next.set(w,first[level[w]]);
721 //active[level[w]].push(w);
724 excess.set(w, excess[w]+c);
733 //Reverse_bfs from t in the residual graph,
734 //to find the starting level.
738 while (!bfs_queue.empty()) {
740 Node v=bfs_queue.front();
745 for(g->first(e,v); g->valid(e); g->next(e)) {
746 if ( (*capacity)[e] <= (*flow)[e] ) continue;
748 if ( level[w] == n && w != s ) {
750 Node z=level_list[l];
751 if ( g->valid(z) ) left.set(z,w);
759 for(g->first(f,v); g->valid(f); g->next(f)) {
760 if ( 0 >= (*flow)[f] ) continue;
762 if ( level[w] == n && w != s ) {
764 Node z=level_list[l];
765 if ( g->valid(z) ) left.set(z,w);
776 for(g->first(e,s); g->valid(e); g->next(e))
778 Num rem=(*capacity)[e]-(*flow)[e];
779 if ( rem <= 0 ) continue;
781 if ( level[w] < n ) {
782 if ( excess[w] <= 0 && w!=t )
784 next.set(w,first[level[w]]);
786 //active[level[w]].push(w);
788 flow->set(e, (*capacity)[e]);
789 excess.set(w, excess[w]+rem);
794 for(g->first(f,s); g->valid(f); g->next(f))
796 if ( (*flow)[f] <= 0 ) continue;
798 if ( level[w] < n ) {
799 if ( excess[w] <= 0 && w!=t )
801 next.set(w,first[level[w]]);
803 //active[level[w]].push(w);
805 excess.set(w, excess[w]+(*flow)[f]);
816 void relabel(Node w, int newlevel, NNMap& next, VecFirst& first,
817 VecNode& level_list, NNMap& left,
818 NNMap& right, int& b, int& k, bool what_heur )
823 Node right_n=right[w];
827 if ( g->valid(right_n) ) {
828 if ( g->valid(left_n) ) {
829 right.set(left_n, right_n);
830 left.set(right_n, left_n);
832 level_list[lev]=right_n;
833 left.set(right_n, INVALID);
836 if ( g->valid(left_n) ) {
837 right.set(left_n, INVALID);
839 level_list[lev]=INVALID;
844 if ( !g->valid(level_list[lev]) ) {
847 for (int i=lev; i!=k ; ) {
848 Node v=level_list[++i];
849 while ( g->valid(v) ) {
853 level_list[i]=INVALID;
854 if ( !what_heur ) first[i]=INVALID;
856 while ( !active[i].empty() ) {
857 active[i].pop(); //FIXME: ezt szebben kene
869 if ( newlevel == n ) level.set(w,n);
871 level.set(w,++newlevel);
872 next.set(w,first[newlevel]);
874 // active[newlevel].push(w);
875 if ( what_heur ) b=newlevel;
876 if ( k < newlevel ) ++k; //now k=newlevel
877 Node z=level_list[newlevel];
878 if ( g->valid(z) ) left.set(z,w);
881 level_list[newlevel]=w;
888 #endif //HUGO_MAX_FLOW_H