New Doxygen module for path/flow algs.
2 #ifndef HUGO_MAX_FLOW_H
3 #define HUGO_MAX_FLOW_H
8 #include <hugo/graph_wrapper.h>
9 #include <hugo/invalid.h>
10 #include <hugo/maps.h>
17 /// \addtogroup flowalgs
20 ///Maximum flow algorithms class.
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.
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
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.
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> >
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;
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 Graph::template NodeMap<int> ReachedMap;
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.
77 //excess is needed only in preflow
78 typename Graph::template NodeMap<Num> excess;
80 // constants used for heuristics
81 static const int H0=20;
82 static const int H1=1;
86 ///Indicates the property of the starting flow.
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
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.
107 AFTER_FAST_AUGMENTING,
108 AFTER_PRE_FLOW_PHASE_1,
109 AFTER_PRE_FLOW_PHASE_2
112 /// Do not needle this flag only if necessary.
115 // int number_of_augmentations;
118 // template<typename IntMap>
119 // class TrickyReachedMap {
122 // int* number_of_augmentations;
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) {
128 // map->set(n, *number_of_augmentations);
130 // map->set(n, *number_of_augmentations-1);
132 // bool operator[](const Node& n) const {
133 // return (*map)[n]==*number_of_augmentations;
139 ///\todo Document, please.
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) { }
147 ///Runs a maximum flow algorithm.
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) {
161 ///Runs a preflow algorithm.
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.
171 ///\todo NO_FLOW should be the default flow.
172 void preflow(FlowEnum fe) {
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.
185 ///Runs the first phase of the preflow algorithm.
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)
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)
208 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
211 //Needed for 'bound decrease', true means no active nodes are above bound
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
217 VecFirst first(n, INVALID);
218 NNMap next(*g, INVALID); //maybe INVALID is not needed
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.
225 preflowPreproc(fe, next, first, level_list, left, right);
226 //End of preprocessing
228 //Push/relabel on the highest level active nodes.
231 if ( !what_heur && !end && k > 0 ) {
237 if ( !g->valid(first[b]) ) --b;
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);
247 if ( numrelabel >= heur ) {
262 status=AFTER_PRE_FLOW_PHASE_1;
266 ///Runs the second phase of the preflow algorithm.
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.
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
280 VecFirst first(n, INVALID);
281 NNMap next(*g, INVALID); //maybe INVALID is not needed
283 std::queue<Node> bfs_queue;
286 while (!bfs_queue.empty()) {
288 Node v=bfs_queue.front();
293 for(g->first(e,v); g->valid(e); g->next(e)) {
294 if ( (*capacity)[e] <= (*flow)[e] ) continue;
296 if ( level[u] >= n ) {
299 if ( excess[u] > 0 ) {
300 next.set(u,first[l]);
307 for(g->first(f,v); g->valid(f); g->next(f)) {
308 if ( 0 >= (*flow)[f] ) continue;
310 if ( level[u] >= n ) {
313 if ( excess[u] > 0 ) {
314 next.set(u,first[l]);
326 if ( !g->valid(first[b]) ) --b;
331 int newlevel=push(w,next, first/*active*/);
334 if ( excess[w] > 0 ) {
335 level.set(w,++newlevel);
336 next.set(w,first[newlevel]);
343 status=AFTER_PRE_FLOW_PHASE_2;
347 /// Returns the maximum value of a flow.
349 /// Returns the maximum value of a flow, by counting the
350 /// over-flow of the target node \ref t.
351 /// It can be called already after running \ref preflowPhase1.
352 Num flowValue() const {
354 for(InEdgeIt e(*g,t);g->valid(e);g->next(e)) a+=(*flow)[e];
355 for(OutEdgeIt e(*g,t);g->valid(e);g->next(e)) a-=(*flow)[e];
357 //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan
361 ///Returns a minimum value cut after calling \ref preflowPhase1.
363 ///After the first phase of the preflow algorithm the maximum flow
364 ///value and a minimum value cut can already be computed. This
365 ///method can be called after running \ref preflowPhase1 for
366 ///obtaining a minimum value cut.
367 /// \warning Gives proper result only right after calling \ref
369 /// \todo We have to make some status variable which shows the
371 /// of the class. This enables us to determine which methods are valid
372 /// for MinCut computation
373 template<typename _CutMap>
374 void actMinCut(_CutMap& M) const {
377 case AFTER_PRE_FLOW_PHASE_1:
378 for(g->first(v); g->valid(v); g->next(v)) {
386 case AFTER_PRE_FLOW_PHASE_2:
388 case AFTER_AUGMENTING:
389 case AFTER_FAST_AUGMENTING:
395 ///Returns the inclusionwise minimum of the minimum value cuts.
397 ///Sets \c M to the characteristic vector of the minimum value cut
398 ///which is inclusionwise minimum. It is computed by processing
399 ///a bfs from the source node \c s in the residual graph.
400 ///\pre M should be a node map of bools initialized to false.
401 ///\pre \c flow must be a maximum flow.
402 template<typename _CutMap>
403 void minMinCut(_CutMap& M) const {
404 std::queue<Node> queue;
409 while (!queue.empty()) {
410 Node w=queue.front();
414 for(g->first(e,w) ; g->valid(e); g->next(e)) {
416 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
423 for(g->first(f,w) ; g->valid(f); g->next(f)) {
425 if (!M[v] && (*flow)[f] > 0 ) {
433 ///Returns the inclusionwise maximum of the minimum value cuts.
435 ///Sets \c M to the characteristic vector of the minimum value cut
436 ///which is inclusionwise maximum. It is computed by processing a
437 ///backward bfs from the target node \c t in the residual graph.
438 ///\pre M should be a node map of bools initialized to false.
439 ///\pre \c flow must be a maximum flow.
440 template<typename _CutMap>
441 void maxMinCut(_CutMap& M) const {
444 for(g->first(v) ; g->valid(v); g->next(v)) {
448 std::queue<Node> queue;
453 while (!queue.empty()) {
454 Node w=queue.front();
458 for(g->first(e,w) ; g->valid(e); g->next(e)) {
460 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
467 for(g->first(f,w) ; g->valid(f); g->next(f)) {
469 if (M[v] && (*flow)[f] > 0 ) {
477 ///Returns a minimum value cut.
479 ///Sets \c M to the characteristic vector of a minimum value cut.
480 ///\pre M should be a node map of bools initialized to false.
481 ///\pre \c flow must be a maximum flow.
482 template<typename CutMap>
483 void minCut(CutMap& M) const { minMinCut(M); }
485 ///Sets the source node to \c _s.
487 ///Sets the source node to \c _s.
489 void setSource(Node _s) { s=_s; status=AFTER_NOTHING; }
491 ///Sets the target node to \c _t.
493 ///Sets the target node to \c _t.
495 void setTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
497 /// Sets the edge map of the capacities to _cap.
499 /// Sets the edge map of the capacities to _cap.
501 void setCap(const CapMap& _cap)
502 { capacity=&_cap; status=AFTER_NOTHING; }
504 /// Sets the edge map of the flows to _flow.
506 /// Sets the edge map of the flows to _flow.
508 void setFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
513 int push(Node w, NNMap& next, VecFirst& first) {
517 int newlevel=n; //bound on the next level of w
520 for(g->first(e,w); g->valid(e); g->next(e)) {
522 if ( (*flow)[e] >= (*capacity)[e] ) continue;
525 if( lev > level[v] ) { //Push is allowed now
527 if ( excess[v]<=0 && v!=t && v!=s ) {
528 next.set(v,first[level[v]]);
532 Num cap=(*capacity)[e];
536 if ( remcap >= exc ) { //A nonsaturating push.
538 flow->set(e, flo+exc);
539 excess.set(v, excess[v]+exc);
543 } else { //A saturating push.
545 excess.set(v, excess[v]+remcap);
548 } else if ( newlevel > level[v] ) newlevel = level[v];
553 for(g->first(e,w); g->valid(e); g->next(e)) {
555 if( (*flow)[e] <= 0 ) continue;
558 if( lev > level[v] ) { //Push is allowed now
560 if ( excess[v]<=0 && v!=t && v!=s ) {
561 next.set(v,first[level[v]]);
567 if ( flo >= exc ) { //A nonsaturating push.
569 flow->set(e, flo-exc);
570 excess.set(v, excess[v]+exc);
573 } else { //A saturating push.
575 excess.set(v, excess[v]+flo);
579 } else if ( newlevel > level[v] ) newlevel = level[v];
582 } // if w still has excess after the out edge for cycle
591 void preflowPreproc(FlowEnum fe, NNMap& next, VecFirst& first,
592 VecNode& level_list, NNMap& left, NNMap& right)
594 switch (fe) { //setting excess
598 for(g->first(e); g->valid(e); g->next(e)) flow->set(e,0);
601 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
607 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
613 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
617 for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
619 for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
627 for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
628 //setting each node to level n
630 std::queue<Node> bfs_queue;
634 case NO_FLOW: //flow is already set to const zero
637 //Reverse_bfs from t, to find the starting level.
641 while (!bfs_queue.empty()) {
643 Node v=bfs_queue.front();
648 for(g->first(e,v); g->valid(e); g->next(e)) {
650 if ( level[w] == n && w != s ) {
652 Node z=level_list[l];
653 if ( g->valid(z) ) left.set(z,w);
663 for(g->first(e,s); g->valid(e); g->next(e))
665 Num c=(*capacity)[e];
666 if ( c <= 0 ) continue;
668 if ( level[w] < n ) {
669 if ( excess[w] <= 0 && w!=t ) //putting into the stack
671 next.set(w,first[level[w]]);
675 excess.set(w, excess[w]+c);
683 //Reverse_bfs from t in the residual graph,
684 //to find the starting level.
688 while (!bfs_queue.empty()) {
690 Node v=bfs_queue.front();
695 for(g->first(e,v); g->valid(e); g->next(e)) {
696 if ( (*capacity)[e] <= (*flow)[e] ) continue;
698 if ( level[w] == n && w != s ) {
700 Node z=level_list[l];
701 if ( g->valid(z) ) left.set(z,w);
709 for(g->first(f,v); g->valid(f); g->next(f)) {
710 if ( 0 >= (*flow)[f] ) continue;
712 if ( level[w] == n && w != s ) {
714 Node z=level_list[l];
715 if ( g->valid(z) ) left.set(z,w);
725 for(g->first(e,s); g->valid(e); g->next(e))
727 Num rem=(*capacity)[e]-(*flow)[e];
728 if ( rem <= 0 ) continue;
730 if ( level[w] < n ) {
731 if ( excess[w] <= 0 && w!=t ) //putting into the stack
733 next.set(w,first[level[w]]);
736 flow->set(e, (*capacity)[e]);
737 excess.set(w, excess[w]+rem);
742 for(g->first(f,s); g->valid(f); g->next(f))
744 if ( (*flow)[f] <= 0 ) continue;
746 if ( level[w] < n ) {
747 if ( excess[w] <= 0 && w!=t )
749 next.set(w,first[level[w]]);
752 excess.set(w, excess[w]+(*flow)[f]);
761 //Reverse_bfs from t in the residual graph,
762 //to find the starting level.
766 while (!bfs_queue.empty()) {
768 Node v=bfs_queue.front();
773 for(g->first(e,v); g->valid(e); g->next(e)) {
774 if ( (*capacity)[e] <= (*flow)[e] ) continue;
776 if ( level[w] == n && w != s ) {
778 Node z=level_list[l];
779 if ( g->valid(z) ) left.set(z,w);
787 for(g->first(f,v); g->valid(f); g->next(f)) {
788 if ( 0 >= (*flow)[f] ) continue;
790 if ( level[w] == n && w != s ) {
792 Node z=level_list[l];
793 if ( g->valid(z) ) left.set(z,w);
804 for(g->first(e,s); g->valid(e); g->next(e))
806 Num rem=(*capacity)[e]-(*flow)[e];
807 if ( rem <= 0 ) continue;
809 if ( level[w] < n ) {
810 flow->set(e, (*capacity)[e]);
811 excess.set(w, excess[w]+rem);
816 for(g->first(f,s); g->valid(f); g->next(f))
818 if ( (*flow)[f] <= 0 ) continue;
820 if ( level[w] < n ) {
821 excess.set(w, excess[w]+(*flow)[f]);
826 NodeIt w; //computing the excess
827 for(g->first(w); g->valid(w); g->next(w)) {
831 for(g->first(e,w); g->valid(e); g->next(e)) exc+=(*flow)[e];
833 for(g->first(f,w); g->valid(f); g->next(f)) exc-=(*flow)[f];
837 //putting the active nodes into the stack
839 if ( exc > 0 && lev < n && w != t )
841 next.set(w,first[lev]);
851 void relabel(Node w, int newlevel, NNMap& next, VecFirst& first,
852 VecNode& level_list, NNMap& left,
853 NNMap& right, int& b, int& k, bool what_heur )
858 Node right_n=right[w];
862 if ( g->valid(right_n) ) {
863 if ( g->valid(left_n) ) {
864 right.set(left_n, right_n);
865 left.set(right_n, left_n);
867 level_list[lev]=right_n;
868 left.set(right_n, INVALID);
871 if ( g->valid(left_n) ) {
872 right.set(left_n, INVALID);
874 level_list[lev]=INVALID;
879 if ( !g->valid(level_list[lev]) ) {
882 for (int i=lev; i!=k ; ) {
883 Node v=level_list[++i];
884 while ( g->valid(v) ) {
888 level_list[i]=INVALID;
889 if ( !what_heur ) first[i]=INVALID;
899 if ( newlevel == n ) level.set(w,n);
901 level.set(w,++newlevel);
902 next.set(w,first[newlevel]);
904 if ( what_heur ) b=newlevel;
905 if ( k < newlevel ) ++k; //now k=newlevel
906 Node z=level_list[newlevel];
907 if ( g->valid(z) ) left.set(z,w);
910 level_list[newlevel]=w;
915 void printexcess() {////
916 std::cout << "Excesses:" <<std::endl;
919 for(g->first(v); g->valid(v); g->next(v)) {
920 std::cout << 1+(g->id(v)) << ":" << excess[v]<<std::endl;
924 void printlevel() {////
925 std::cout << "Levels:" <<std::endl;
928 for(g->first(v); g->valid(v); g->next(v)) {
929 std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
933 void printactive() {////
934 std::cout << "Levels:" <<std::endl;
937 for(g->first(v); g->valid(v); g->next(v)) {
938 std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
946 #endif //HUGO_MAX_FLOW_H