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 ( first[b]==INVALID ) --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();
292 for(InEdgeIt e(*g,v); e!=INVALID; ++e) {
293 if ( (*capacity)[e] <= (*flow)[e] ) continue;
295 if ( level[u] >= n ) {
298 if ( excess[u] > 0 ) {
299 next.set(u,first[l]);
305 for(OutEdgeIt e(*g,v); e!=INVALID; ++e) {
306 if ( 0 >= (*flow)[e] ) continue;
308 if ( level[u] >= n ) {
311 if ( excess[u] > 0 ) {
312 next.set(u,first[l]);
324 if ( first[b]==INVALID ) --b;
329 int newlevel=push(w,next, first/*active*/);
332 if ( excess[w] > 0 ) {
333 level.set(w,++newlevel);
334 next.set(w,first[newlevel]);
341 status=AFTER_PRE_FLOW_PHASE_2;
345 /// Returns the value of the maximum flow.
347 /// Returns the excess of the target node \ref t.
348 /// After running \ref preflowPhase1, this is the value of
349 /// the maximum flow.
350 /// It can be called already after running \ref preflowPhase1.
351 Num flowValue() const {
353 // for(InEdgeIt e(*g,t);g->valid(e);g->next(e)) a+=(*flow)[e];
354 // 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 {
376 case AFTER_PRE_FLOW_PHASE_1:
377 for(NodeIt v(*g); v!=INVALID; ++v) {
385 case AFTER_PRE_FLOW_PHASE_2:
387 case AFTER_AUGMENTING:
388 case AFTER_FAST_AUGMENTING:
394 ///Returns the inclusionwise minimum of the minimum value cuts.
396 ///Sets \c M to the characteristic vector of the minimum value cut
397 ///which is inclusionwise minimum. It is computed by processing
398 ///a bfs from the source node \c s in the residual graph.
399 ///\pre M should be a node map of bools initialized to false.
400 ///\pre \c flow must be a maximum flow.
401 template<typename _CutMap>
402 void minMinCut(_CutMap& M) const {
403 std::queue<Node> queue;
408 while (!queue.empty()) {
409 Node w=queue.front();
412 for(OutEdgeIt e(*g,w) ; e!=INVALID; ++e) {
414 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
420 for(InEdgeIt e(*g,w) ; e!=INVALID; ++e) {
422 if (!M[v] && (*flow)[e] > 0 ) {
430 ///Returns the inclusionwise maximum of the minimum value cuts.
432 ///Sets \c M to the characteristic vector of the minimum value cut
433 ///which is inclusionwise maximum. It is computed by processing a
434 ///backward bfs from the target node \c t in the residual graph.
435 ///\pre M should be a node map of bools initialized to false.
436 ///\pre \c flow must be a maximum flow.
437 template<typename _CutMap>
438 void maxMinCut(_CutMap& M) const {
440 for(NodeIt v(*g) ; v!=INVALID; ++v) M.set(v, true);
442 std::queue<Node> queue;
447 while (!queue.empty()) {
448 Node w=queue.front();
451 for(InEdgeIt e(*g,w) ; e!=INVALID; ++e) {
453 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
459 for(OutEdgeIt e(*g,w) ; e!=INVALID; ++e) {
461 if (M[v] && (*flow)[e] > 0 ) {
469 ///Returns a minimum value cut.
471 ///Sets \c M to the characteristic vector of a minimum value cut.
472 ///\pre M should be a node map of bools initialized to false.
473 ///\pre \c flow must be a maximum flow.
474 template<typename CutMap>
475 void minCut(CutMap& M) const { minMinCut(M); }
477 ///Sets the source node to \c _s.
479 ///Sets the source node to \c _s.
481 void setSource(Node _s) { s=_s; status=AFTER_NOTHING; }
483 ///Sets the target node to \c _t.
485 ///Sets the target node to \c _t.
487 void setTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
489 /// Sets the edge map of the capacities to _cap.
491 /// Sets the edge map of the capacities to _cap.
493 void setCap(const CapMap& _cap)
494 { capacity=&_cap; status=AFTER_NOTHING; }
496 /// Sets the edge map of the flows to _flow.
498 /// Sets the edge map of the flows to _flow.
500 void setFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
505 int push(Node w, NNMap& next, VecFirst& first) {
509 int newlevel=n; //bound on the next level of w
511 for(OutEdgeIt e(*g,w) ; e!=INVALID; ++e) {
512 if ( (*flow)[e] >= (*capacity)[e] ) continue;
515 if( lev > level[v] ) { //Push is allowed now
517 if ( excess[v]<=0 && v!=t && v!=s ) {
518 next.set(v,first[level[v]]);
522 Num cap=(*capacity)[e];
526 if ( remcap >= exc ) { //A nonsaturating push.
528 flow->set(e, flo+exc);
529 excess.set(v, excess[v]+exc);
533 } else { //A saturating push.
535 excess.set(v, excess[v]+remcap);
538 } else if ( newlevel > level[v] ) newlevel = level[v];
542 for(InEdgeIt e(*g,w) ; e!=INVALID; ++e) {
544 if( (*flow)[e] <= 0 ) continue;
547 if( lev > level[v] ) { //Push is allowed now
549 if ( excess[v]<=0 && v!=t && v!=s ) {
550 next.set(v,first[level[v]]);
556 if ( flo >= exc ) { //A nonsaturating push.
558 flow->set(e, flo-exc);
559 excess.set(v, excess[v]+exc);
562 } else { //A saturating push.
564 excess.set(v, excess[v]+flo);
568 } else if ( newlevel > level[v] ) newlevel = level[v];
571 } // if w still has excess after the out edge for cycle
580 void preflowPreproc(FlowEnum fe, NNMap& next, VecFirst& first,
581 VecNode& level_list, NNMap& left, NNMap& right)
583 switch (fe) { //setting excess
585 for(EdgeIt e(*g); e!=INVALID; ++e) flow->set(e,0);
586 for(NodeIt v(*g); v!=INVALID; ++v) excess.set(v,0);
589 for(NodeIt v(*g); v!=INVALID; ++v) excess.set(v,0);
592 for(NodeIt v(*g); v!=INVALID; ++v) excess.set(v,0);
595 for(InEdgeIt e(*g,t) ; e!=INVALID; ++e) exc+=(*flow)[e];
596 for(OutEdgeIt e(*g,t) ; e!=INVALID; ++e) exc-=(*flow)[e];
604 for(NodeIt v(*g); v!=INVALID; ++v) level.set(v,n);
605 //setting each node to level n
607 std::queue<Node> bfs_queue;
611 case NO_FLOW: //flow is already set to const zero
613 //Reverse_bfs from t, to find the starting level.
617 while (!bfs_queue.empty()) {
619 Node v=bfs_queue.front();
623 for(InEdgeIt e(*g,v) ; e!=INVALID; ++e) {
625 if ( level[w] == n && w != s ) {
627 Node z=level_list[l];
628 if ( z!=INVALID ) left.set(z,w);
637 for(OutEdgeIt e(*g,s) ; e!=INVALID; ++e)
639 Num c=(*capacity)[e];
640 if ( c <= 0 ) continue;
642 if ( level[w] < n ) {
643 if ( excess[w] <= 0 && w!=t ) //putting into the stack
645 next.set(w,first[level[w]]);
649 excess.set(w, excess[w]+c);
654 //Reverse_bfs from t in the residual graph,
655 //to find the starting level.
659 while (!bfs_queue.empty()) {
661 Node v=bfs_queue.front();
665 for(InEdgeIt e(*g,v) ; e!=INVALID; ++e) {
666 if ( (*capacity)[e] <= (*flow)[e] ) continue;
668 if ( level[w] == n && w != s ) {
670 Node z=level_list[l];
671 if ( z!=INVALID ) left.set(z,w);
678 for(OutEdgeIt e(*g,v) ; e!=INVALID; ++e) {
679 if ( 0 >= (*flow)[e] ) continue;
681 if ( level[w] == n && w != s ) {
683 Node z=level_list[l];
684 if ( z!=INVALID ) left.set(z,w);
693 for(OutEdgeIt e(*g,s); e!=INVALID; ++e)
695 Num rem=(*capacity)[e]-(*flow)[e];
696 if ( rem <= 0 ) continue;
698 if ( level[w] < n ) {
699 if ( excess[w] <= 0 && w!=t ) //putting into the stack
701 next.set(w,first[level[w]]);
704 flow->set(e, (*capacity)[e]);
705 excess.set(w, excess[w]+rem);
709 for(InEdgeIt e(*g,s); e!=INVALID; ++e)
711 if ( (*flow)[e] <= 0 ) continue;
713 if ( level[w] < n ) {
714 if ( excess[w] <= 0 && w!=t )
716 next.set(w,first[level[w]]);
719 excess.set(w, excess[w]+(*flow)[e]);
725 //Reverse_bfs from t in the residual graph,
726 //to find the starting level.
730 while (!bfs_queue.empty()) {
732 Node v=bfs_queue.front();
736 for(InEdgeIt e(*g,v) ; e!=INVALID; ++e) {
737 if ( (*capacity)[e] <= (*flow)[e] ) continue;
739 if ( level[w] == n && w != s ) {
741 Node z=level_list[l];
742 if ( z!=INVALID ) left.set(z,w);
749 for(OutEdgeIt e(*g,v) ; e!=INVALID; ++e) {
750 if ( 0 >= (*flow)[e] ) continue;
752 if ( level[w] == n && w != s ) {
754 Node z=level_list[l];
755 if ( z!=INVALID ) left.set(z,w);
765 for(OutEdgeIt e(*g,s) ; e!=INVALID; ++e) {
766 Num rem=(*capacity)[e]-(*flow)[e];
767 if ( rem <= 0 ) continue;
769 if ( level[w] < n ) {
770 flow->set(e, (*capacity)[e]);
771 excess.set(w, excess[w]+rem);
775 for(InEdgeIt e(*g,s) ; e!=INVALID; ++e) {
776 if ( (*flow)[e] <= 0 ) continue;
778 if ( level[w] < n ) {
779 excess.set(w, excess[w]+(*flow)[e]);
784 //computing the excess
785 for(NodeIt w(*g); w!=INVALID; ++w) {
788 for(InEdgeIt e(*g,w) ; e!=INVALID; ++e) exc+=(*flow)[e];
789 for(OutEdgeIt e(*g,w) ; e!=INVALID; ++e) exc-=(*flow)[e];
793 //putting the active nodes into the stack
795 if ( exc > 0 && lev < n && Node(w) != t )
796 ///\bug if ( exc > 0 && lev < n && w != t ) temporarily for working with wrappers.
798 next.set(w,first[lev]);
807 void relabel(Node w, int newlevel, NNMap& next, VecFirst& first,
808 VecNode& level_list, NNMap& left,
809 NNMap& right, int& b, int& k, bool what_heur )
814 Node right_n=right[w];
818 if ( right_n!=INVALID ) {
819 if ( left_n!=INVALID ) {
820 right.set(left_n, right_n);
821 left.set(right_n, left_n);
823 level_list[lev]=right_n;
824 left.set(right_n, INVALID);
827 if ( left_n!=INVALID ) {
828 right.set(left_n, INVALID);
830 level_list[lev]=INVALID;
835 if ( level_list[lev]==INVALID ) {
838 for (int i=lev; i!=k ; ) {
839 Node v=level_list[++i];
840 while ( v!=INVALID ) {
844 level_list[i]=INVALID;
845 if ( !what_heur ) first[i]=INVALID;
855 if ( newlevel == n ) level.set(w,n);
857 level.set(w,++newlevel);
858 next.set(w,first[newlevel]);
860 if ( what_heur ) b=newlevel;
861 if ( k < newlevel ) ++k; //now k=newlevel
862 Node z=level_list[newlevel];
863 if ( z!=INVALID ) left.set(z,w);
866 level_list[newlevel]=w;
871 void printexcess() {////
872 std::cout << "Excesses:" <<std::endl;
874 for(NodeIt v(*g); v!=INVALID ; ++v) {
875 std::cout << 1+(g->id(v)) << ":" << excess[v]<<std::endl;
879 void printlevel() {////
880 std::cout << "Levels:" <<std::endl;
882 for(NodeIt v(*g); v!=INVALID ; ++v) {
883 std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
887 void printactive() {////
888 std::cout << "Levels:" <<std::endl;
890 for(NodeIt v(*g); v!=INVALID ; ++v) {
891 std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
899 #endif //HUGO_MAX_FLOW_H