doc change - one more todo.
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>
19 ///Maximum flow algorithms class.
21 ///This class provides various algorithms for finding a flow of
22 ///maximum value in a directed graph. The \e source node, the \e
23 ///target node, the \e capacity of the edges and the \e starting \e
24 ///flow value of the edges should be passed to the algorithm through the
25 ///constructor. It is possible to change these quantities using the
26 ///functions \ref resetSource, \ref resetTarget, \ref resetCap and
27 ///\ref resetFlow. Before any subsequent runs of any algorithm of
28 ///the class \ref resetFlow should be called.
30 ///After running an algorithm of the class, the actual flow value
31 ///can be obtained by calling \ref flowValue(). The minimum
32 ///value cut can be written into a \c node map of \c bools by
33 ///calling \ref minCut. (\ref minMinCut and \ref maxMinCut writes
34 ///the inclusionwise minimum and maximum of the minimum value
36 ///\param Graph The directed graph type the algorithm runs on.
37 ///\param Num The number type of the capacities and the flow values.
38 ///\param CapMap The capacity map type.
39 ///\param FlowMap The flow map type.
40 ///\author Marton Makai, Jacint Szabo
41 template <typename Graph, typename Num,
42 typename CapMap=typename Graph::template EdgeMap<Num>,
43 typename FlowMap=typename Graph::template EdgeMap<Num> >
46 typedef typename Graph::Node Node;
47 typedef typename Graph::NodeIt NodeIt;
48 typedef typename Graph::EdgeIt EdgeIt;
49 typedef typename Graph::OutEdgeIt OutEdgeIt;
50 typedef typename Graph::InEdgeIt InEdgeIt;
52 typedef typename std::vector<Node> VecFirst;
53 typedef typename Graph::template NodeMap<Node> NNMap;
54 typedef typename std::vector<Node> VecNode;
59 const CapMap* capacity;
61 int n; //the number of nodes of G
62 typedef ResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
63 //typedef ExpResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
64 typedef typename ResGW::OutEdgeIt ResGWOutEdgeIt;
65 typedef typename ResGW::Edge ResGWEdge;
66 typedef typename Graph::template NodeMap<int> ReachedMap;
69 //level works as a bool map in augmenting path algorithms and is
70 //used by bfs for storing reached information. In preflow, it
71 //shows the levels of nodes.
74 //excess is needed only in preflow
75 typename Graph::template NodeMap<Num> excess;
77 // constants used for heuristics
78 static const int H0=20;
79 static const int H1=1;
83 ///Indicates the property of the starting flow.
85 ///Indicates the property of the starting flow. The meanings are as follows:
86 ///- \c ZERO_FLOW: constant zero flow
87 ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
88 ///the sum of the out-flows in every node except the \e source and
90 ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at
91 ///least the sum of the out-flows in every node except the \e source.
92 ///- \c NO_FLOW: indicates an unspecified edge map. \ref flow will be
93 ///set to the constant zero flow in the beginning of the algorithm in this case.
104 AFTER_FAST_AUGMENTING,
105 AFTER_PRE_FLOW_PHASE_1,
106 AFTER_PRE_FLOW_PHASE_2
109 /// Do not needle this flag only if necessary.
112 // int number_of_augmentations;
115 // template<typename IntMap>
116 // class TrickyReachedMap {
119 // int* number_of_augmentations;
121 // TrickyReachedMap(IntMap& _map, int& _number_of_augmentations) :
122 // map(&_map), number_of_augmentations(&_number_of_augmentations) { }
123 // void set(const Node& n, bool b) {
125 // map->set(n, *number_of_augmentations);
127 // map->set(n, *number_of_augmentations-1);
129 // bool operator[](const Node& n) const {
130 // return (*map)[n]==*number_of_augmentations;
136 ///\todo Document, please.
138 MaxFlow(const Graph& _G, Node _s, Node _t,
139 const CapMap& _capacity, FlowMap& _flow) :
140 g(&_G), s(_s), t(_t), capacity(&_capacity),
141 flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0),
142 status(AFTER_NOTHING) { }
144 ///Runs a maximum flow algorithm.
146 ///Runs a preflow algorithm, which is the fastest maximum flow
147 ///algorithm up-to-date. The default for \c fe is ZERO_FLOW.
148 ///\pre The starting flow must be
149 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
150 /// - an arbitary flow if \c fe is \c GEN_FLOW,
151 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
152 /// - any map if \c fe is NO_FLOW.
153 void run(FlowEnum fe=ZERO_FLOW) {
158 ///Runs a preflow algorithm.
160 ///Runs a preflow algorithm. The preflow algorithms provide the
161 ///fastest way to compute a maximum flow in a directed graph.
162 ///\pre The starting flow must be
163 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
164 /// - an arbitary flow if \c fe is \c GEN_FLOW,
165 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
166 /// - any map if \c fe is NO_FLOW.
168 ///\todo NO_FLOW should be the default flow.
169 void preflow(FlowEnum fe) {
176 // list 'level_list' on the nodes on level i implemented by hand
177 // stack 'active' on the active nodes on level i
178 // runs heuristic 'highest label' for H1*n relabels
179 // runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
180 // Parameters H0 and H1 are initialized to 20 and 1.
182 ///Runs the first phase of the preflow algorithm.
184 ///The preflow algorithm consists of two phases, this method runs the
185 ///first phase. After the first phase the maximum flow value and a
186 ///minimum value cut can already be computed, though a maximum flow
187 ///is not yet obtained. So after calling this method \ref flowValue
188 ///and \ref actMinCut gives proper results.
189 ///\warning: \ref minCut, \ref minMinCut and \ref maxMinCut do not
190 ///give minimum value cuts unless calling \ref preflowPhase2.
191 ///\pre The starting flow must be
192 /// - a constant zero flow if \c fe is \c ZERO_FLOW,
193 /// - an arbitary flow if \c fe is \c GEN_FLOW,
194 /// - an arbitary preflow if \c fe is \c PRE_FLOW,
195 /// - any map if \c fe is NO_FLOW.
196 void preflowPhase1(FlowEnum fe)
199 int heur0=(int)(H0*n); //time while running 'bound decrease'
200 int heur1=(int)(H1*n); //time while running 'highest label'
201 int heur=heur1; //starting time interval (#of relabels)
205 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
208 //Needed for 'bound decrease', true means no active nodes are above bound
211 int k=n-2; //bound on the highest level under n containing a node
212 int b=k; //bound on the highest level under n of an active node
214 VecFirst first(n, INVALID);
215 NNMap next(*g, INVALID); //maybe INVALID is not needed
217 NNMap left(*g, INVALID);
218 NNMap right(*g, INVALID);
219 VecNode level_list(n,INVALID);
220 //List of the nodes in level i<n, set to n.
222 preflowPreproc(fe, next, first, level_list, left, right);
223 //End of preprocessing
225 //Push/relabel on the highest level active nodes.
228 if ( !what_heur && !end && k > 0 ) {
234 if ( !g->valid(first[b]) ) --b;
239 int newlevel=push(w, next, first);
240 if ( excess[w] > 0 ) relabel(w, newlevel, next, first, level_list,
241 left, right, b, k, what_heur);
244 if ( numrelabel >= heur ) {
259 status=AFTER_PRE_FLOW_PHASE_1;
263 ///Runs the second phase of the preflow algorithm.
265 ///The preflow algorithm consists of two phases, this method runs
266 ///the second phase. After calling \ref preflowPhase1 and then
267 ///\ref preflowPhase2 the methods \ref flowValue, \ref minCut,
268 ///\ref minMinCut and \ref maxMinCut give proper results.
269 ///\pre \ref preflowPhase1 must be called before.
273 int k=n-2; //bound on the highest level under n containing a node
274 int b=k; //bound on the highest level under n of an active node
277 VecFirst first(n, INVALID);
278 NNMap next(*g, INVALID); //maybe INVALID is not needed
280 std::queue<Node> bfs_queue;
283 while (!bfs_queue.empty()) {
285 Node v=bfs_queue.front();
290 for(g->first(e,v); g->valid(e); g->next(e)) {
291 if ( (*capacity)[e] <= (*flow)[e] ) continue;
293 if ( level[u] >= n ) {
296 if ( excess[u] > 0 ) {
297 next.set(u,first[l]);
304 for(g->first(f,v); g->valid(f); g->next(f)) {
305 if ( 0 >= (*flow)[f] ) continue;
307 if ( level[u] >= n ) {
310 if ( excess[u] > 0 ) {
311 next.set(u,first[l]);
323 if ( !g->valid(first[b]) ) --b;
328 int newlevel=push(w,next, first/*active*/);
331 if ( excess[w] > 0 ) {
332 level.set(w,++newlevel);
333 next.set(w,first[newlevel]);
340 status=AFTER_PRE_FLOW_PHASE_2;
344 /// Returns the maximum value of a flow.
346 /// Returns the maximum value of a flow, by counting the
347 /// over-flow of the target node \ref t.
348 /// It can be called already after running \ref preflowPhase1.
349 Num flowValue() const {
351 for(InEdgeIt e(*g,t);g->valid(e);g->next(e)) a+=(*flow)[e];
352 for(OutEdgeIt e(*g,t);g->valid(e);g->next(e)) a-=(*flow)[e];
354 //marci figyu: excess[t] epp ezt adja preflow 1. fazisa utan
358 ///Returns a minimum value cut after calling \ref preflowPhase1.
360 ///After the first phase of the preflow algorithm the maximum flow
361 ///value and a minimum value cut can already be computed. This
362 ///method can be called after running \ref preflowPhase1 for
363 ///obtaining a minimum value cut.
364 /// \warning Gives proper result only right after calling \ref
366 /// \todo We have to make some status variable which shows the
368 /// of the class. This enables us to determine which methods are valid
369 /// for MinCut computation
370 template<typename _CutMap>
371 void actMinCut(_CutMap& M) const {
374 case AFTER_PRE_FLOW_PHASE_1:
375 for(g->first(v); g->valid(v); g->next(v)) {
383 case AFTER_PRE_FLOW_PHASE_2:
385 case AFTER_AUGMENTING:
386 case AFTER_FAST_AUGMENTING:
392 ///Returns the inclusionwise minimum of the minimum value cuts.
394 ///Sets \c M to the characteristic vector of the minimum value cut
395 ///which is inclusionwise minimum. It is computed by processing
396 ///a bfs from the source node \c s in the residual graph.
397 ///\pre M should be a node map of bools initialized to false.
398 ///\pre \c flow must be a maximum flow.
399 template<typename _CutMap>
400 void minMinCut(_CutMap& M) const {
401 std::queue<Node> queue;
406 while (!queue.empty()) {
407 Node w=queue.front();
411 for(g->first(e,w) ; g->valid(e); g->next(e)) {
413 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
420 for(g->first(f,w) ; g->valid(f); g->next(f)) {
422 if (!M[v] && (*flow)[f] > 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 {
441 for(g->first(v) ; g->valid(v); g->next(v)) {
445 std::queue<Node> queue;
450 while (!queue.empty()) {
451 Node w=queue.front();
455 for(g->first(e,w) ; g->valid(e); g->next(e)) {
457 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
464 for(g->first(f,w) ; g->valid(f); g->next(f)) {
466 if (M[v] && (*flow)[f] > 0 ) {
474 ///Returns a minimum value cut.
476 ///Sets \c M to the characteristic vector of a minimum value cut.
477 ///\pre M should be a node map of bools initialized to false.
478 ///\pre \c flow must be a maximum flow.
479 template<typename CutMap>
480 void minCut(CutMap& M) const { minMinCut(M); }
482 ///Resets the source node to \c _s.
484 ///Resets the source node to \c _s.
486 void resetSource(Node _s) { s=_s; status=AFTER_NOTHING; }
488 ///Resets the target node to \c _t.
490 ///Resets the target node to \c _t.
492 void resetTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
494 /// Resets the edge map of the capacities to _cap.
496 /// Resets the edge map of the capacities to _cap.
498 void resetCap(const CapMap& _cap)
499 { capacity=&_cap; status=AFTER_NOTHING; }
501 /// Resets the edge map of the flows to _flow.
503 /// Resets the edge map of the flows to _flow.
505 void resetFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
510 int push(Node w, NNMap& next, VecFirst& first) {
514 int newlevel=n; //bound on the next level of w
517 for(g->first(e,w); g->valid(e); g->next(e)) {
519 if ( (*flow)[e] >= (*capacity)[e] ) continue;
522 if( lev > level[v] ) { //Push is allowed now
524 if ( excess[v]<=0 && v!=t && v!=s ) {
525 next.set(v,first[level[v]]);
529 Num cap=(*capacity)[e];
533 if ( remcap >= exc ) { //A nonsaturating push.
535 flow->set(e, flo+exc);
536 excess.set(v, excess[v]+exc);
540 } else { //A saturating push.
542 excess.set(v, excess[v]+remcap);
545 } else if ( newlevel > level[v] ) newlevel = level[v];
550 for(g->first(e,w); g->valid(e); g->next(e)) {
552 if( (*flow)[e] <= 0 ) continue;
555 if( lev > level[v] ) { //Push is allowed now
557 if ( excess[v]<=0 && v!=t && v!=s ) {
558 next.set(v,first[level[v]]);
564 if ( flo >= exc ) { //A nonsaturating push.
566 flow->set(e, flo-exc);
567 excess.set(v, excess[v]+exc);
570 } else { //A saturating push.
572 excess.set(v, excess[v]+flo);
576 } else if ( newlevel > level[v] ) newlevel = level[v];
579 } // if w still has excess after the out edge for cycle
588 void preflowPreproc(FlowEnum fe, NNMap& next, VecFirst& first,
589 VecNode& level_list, NNMap& left, NNMap& right)
591 switch (fe) { //setting excess
595 for(g->first(e); g->valid(e); g->next(e)) flow->set(e,0);
598 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
604 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
610 for(g->first(v); g->valid(v); g->next(v)) excess.set(v,0);
614 for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
616 for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
624 for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
625 //setting each node to level n
627 std::queue<Node> bfs_queue;
631 case NO_FLOW: //flow is already set to const zero
634 //Reverse_bfs from t, to find the starting level.
638 while (!bfs_queue.empty()) {
640 Node v=bfs_queue.front();
645 for(g->first(e,v); g->valid(e); g->next(e)) {
647 if ( level[w] == n && w != s ) {
649 Node z=level_list[l];
650 if ( g->valid(z) ) left.set(z,w);
660 for(g->first(e,s); g->valid(e); g->next(e))
662 Num c=(*capacity)[e];
663 if ( c <= 0 ) continue;
665 if ( level[w] < n ) {
666 if ( excess[w] <= 0 && w!=t ) //putting into the stack
668 next.set(w,first[level[w]]);
672 excess.set(w, excess[w]+c);
680 //Reverse_bfs from t in the residual graph,
681 //to find the starting level.
685 while (!bfs_queue.empty()) {
687 Node v=bfs_queue.front();
692 for(g->first(e,v); g->valid(e); g->next(e)) {
693 if ( (*capacity)[e] <= (*flow)[e] ) continue;
695 if ( level[w] == n && w != s ) {
697 Node z=level_list[l];
698 if ( g->valid(z) ) left.set(z,w);
706 for(g->first(f,v); g->valid(f); g->next(f)) {
707 if ( 0 >= (*flow)[f] ) continue;
709 if ( level[w] == n && w != s ) {
711 Node z=level_list[l];
712 if ( g->valid(z) ) left.set(z,w);
722 for(g->first(e,s); g->valid(e); g->next(e))
724 Num rem=(*capacity)[e]-(*flow)[e];
725 if ( rem <= 0 ) continue;
727 if ( level[w] < n ) {
728 if ( excess[w] <= 0 && w!=t ) //putting into the stack
730 next.set(w,first[level[w]]);
733 flow->set(e, (*capacity)[e]);
734 excess.set(w, excess[w]+rem);
739 for(g->first(f,s); g->valid(f); g->next(f))
741 if ( (*flow)[f] <= 0 ) continue;
743 if ( level[w] < n ) {
744 if ( excess[w] <= 0 && w!=t )
746 next.set(w,first[level[w]]);
749 excess.set(w, excess[w]+(*flow)[f]);
758 //Reverse_bfs from t in the residual graph,
759 //to find the starting level.
763 while (!bfs_queue.empty()) {
765 Node v=bfs_queue.front();
770 for(g->first(e,v); g->valid(e); g->next(e)) {
771 if ( (*capacity)[e] <= (*flow)[e] ) continue;
773 if ( level[w] == n && w != s ) {
775 Node z=level_list[l];
776 if ( g->valid(z) ) left.set(z,w);
784 for(g->first(f,v); g->valid(f); g->next(f)) {
785 if ( 0 >= (*flow)[f] ) continue;
787 if ( level[w] == n && w != s ) {
789 Node z=level_list[l];
790 if ( g->valid(z) ) left.set(z,w);
801 for(g->first(e,s); g->valid(e); g->next(e))
803 Num rem=(*capacity)[e]-(*flow)[e];
804 if ( rem <= 0 ) continue;
806 if ( level[w] < n ) {
807 flow->set(e, (*capacity)[e]);
808 excess.set(w, excess[w]+rem);
813 for(g->first(f,s); g->valid(f); g->next(f))
815 if ( (*flow)[f] <= 0 ) continue;
817 if ( level[w] < n ) {
818 excess.set(w, excess[w]+(*flow)[f]);
823 NodeIt w; //computing the excess
824 for(g->first(w); g->valid(w); g->next(w)) {
828 for(g->first(e,w); g->valid(e); g->next(e)) exc+=(*flow)[e];
830 for(g->first(f,w); g->valid(f); g->next(f)) exc-=(*flow)[f];
834 //putting the active nodes into the stack
836 if ( exc > 0 && lev < n && w != t )
838 next.set(w,first[lev]);
848 void relabel(Node w, int newlevel, NNMap& next, VecFirst& first,
849 VecNode& level_list, NNMap& left,
850 NNMap& right, int& b, int& k, bool what_heur )
855 Node right_n=right[w];
859 if ( g->valid(right_n) ) {
860 if ( g->valid(left_n) ) {
861 right.set(left_n, right_n);
862 left.set(right_n, left_n);
864 level_list[lev]=right_n;
865 left.set(right_n, INVALID);
868 if ( g->valid(left_n) ) {
869 right.set(left_n, INVALID);
871 level_list[lev]=INVALID;
876 if ( !g->valid(level_list[lev]) ) {
879 for (int i=lev; i!=k ; ) {
880 Node v=level_list[++i];
881 while ( g->valid(v) ) {
885 level_list[i]=INVALID;
886 if ( !what_heur ) first[i]=INVALID;
896 if ( newlevel == n ) level.set(w,n);
898 level.set(w,++newlevel);
899 next.set(w,first[newlevel]);
901 if ( what_heur ) b=newlevel;
902 if ( k < newlevel ) ++k; //now k=newlevel
903 Node z=level_list[newlevel];
904 if ( g->valid(z) ) left.set(z,w);
907 level_list[newlevel]=w;
912 void printexcess() {////
913 std::cout << "Excesses:" <<std::endl;
916 for(g->first(v); g->valid(v); g->next(v)) {
917 std::cout << 1+(g->id(v)) << ":" << excess[v]<<std::endl;
921 void printlevel() {////
922 std::cout << "Levels:" <<std::endl;
925 for(g->first(v); g->valid(v); g->next(v)) {
926 std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
930 void printactive() {////
931 std::cout << "Levels:" <<std::endl;
934 for(g->first(v); g->valid(v); g->next(v)) {
935 std::cout << 1+(g->id(v)) << ":" << level[v]<<std::endl;
943 #endif //HUGO_MAX_FLOW_H