A very flexible bfs function using named parameters and impicit map types.
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:
459 ///Returns the inclusionwise minimum of the minimum value cuts.
461 ///Sets \c M to the characteristic vector of the minimum value cut
462 ///which is inclusionwise minimum. It is computed by processing
463 ///a bfs from the source node \c s in the residual graph.
464 ///\pre M should be a node map of bools initialized to false.
465 ///\pre \c flow must be a maximum flow.
466 template<typename _CutMap>
467 void minMinCut(_CutMap& M) const {
468 std::queue<Node> queue;
473 while (!queue.empty()) {
474 Node w=queue.front();
478 for(g->first(e,w) ; g->valid(e); g->next(e)) {
480 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
487 for(g->first(f,w) ; g->valid(f); g->next(f)) {
489 if (!M[v] && (*flow)[f] > 0 ) {
497 ///Returns the inclusionwise maximum of the minimum value cuts.
499 ///Sets \c M to the characteristic vector of the minimum value cut
500 ///which is inclusionwise maximum. It is computed by processing a
501 ///backward bfs from the target node \c t in the residual graph.
502 ///\pre M should be a node map of bools initialized to false.
503 ///\pre \c flow must be a maximum flow.
504 template<typename _CutMap>
505 void maxMinCut(_CutMap& M) const {
508 for(g->first(v) ; g->valid(v); g->next(v)) {
512 std::queue<Node> queue;
517 while (!queue.empty()) {
518 Node w=queue.front();
522 for(g->first(e,w) ; g->valid(e); g->next(e)) {
524 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
531 for(g->first(f,w) ; g->valid(f); g->next(f)) {
533 if (M[v] && (*flow)[f] > 0 ) {
541 ///Returns a minimum value cut.
543 ///Sets \c M to the characteristic vector of a minimum value cut.
544 ///\pre M should be a node map of bools initialized to false.
545 ///\pre \c flow must be a maximum flow.
546 template<typename CutMap>
547 void minCut(CutMap& M) const { minMinCut(M); }
549 ///Resets the source node to \c _s.
551 ///Resets the source node to \c _s.
553 void resetSource(Node _s) { s=_s; status=AFTER_NOTHING; }
555 ///Resets the target node to \c _t.
557 ///Resets the target node to \c _t.
559 void resetTarget(Node _t) { t=_t; status=AFTER_NOTHING; }
561 /// Resets the edge map of the capacities to _cap.
563 /// Resets the edge map of the capacities to _cap.
565 void resetCap(const CapMap& _cap)
566 { capacity=&_cap; status=AFTER_NOTHING; }
568 /// Resets the edge map of the flows to _flow.
570 /// Resets the edge map of the flows to _flow.
572 void resetFlow(FlowMap& _flow) { flow=&_flow; status=AFTER_NOTHING; }
577 int push(Node w, NNMap& next, VecFirst& first) {
581 int newlevel=n; //bound on the next level of w
584 for(g->first(e,w); g->valid(e); g->next(e)) {
586 if ( (*flow)[e] >= (*capacity)[e] ) continue;
589 if( lev > level[v] ) { //Push is allowed now
591 if ( excess[v]<=0 && v!=t && v!=s ) {
592 next.set(v,first[level[v]]);
594 // int lev_v=level[v];
595 //active[lev_v].push(v);
598 Num cap=(*capacity)[e];
602 if ( remcap >= exc ) { //A nonsaturating push.
604 flow->set(e, flo+exc);
605 excess.set(v, excess[v]+exc);
609 } else { //A saturating push.
611 excess.set(v, excess[v]+remcap);
614 } else if ( newlevel > level[v] ) newlevel = level[v];
619 for(g->first(e,w); g->valid(e); g->next(e)) {
621 if( (*flow)[e] <= 0 ) continue;
624 if( lev > level[v] ) { //Push is allowed now
626 if ( excess[v]<=0 && v!=t && v!=s ) {
627 next.set(v,first[level[v]]);
629 //int lev_v=level[v];
630 //active[lev_v].push(v);
635 if ( flo >= exc ) { //A nonsaturating push.
637 flow->set(e, flo-exc);
638 excess.set(v, excess[v]+exc);
641 } else { //A saturating push.
643 excess.set(v, excess[v]+flo);
647 } else if ( newlevel > level[v] ) newlevel = level[v];
650 } // if w still has excess after the out edge for cycle
658 void preflowPreproc(FlowEnum fe, NNMap& next, VecFirst& first,
659 VecNode& level_list, NNMap& left, NNMap& right)
661 std::queue<Node> bfs_queue;
664 case NO_FLOW: //flow is already set to const zero in this case
667 //Reverse_bfs from t, to find the starting level.
671 while (!bfs_queue.empty()) {
673 Node v=bfs_queue.front();
678 for(g->first(e,v); g->valid(e); g->next(e)) {
680 if ( level[w] == n && w != s ) {
682 Node z=level_list[l];
683 if ( g->valid(z) ) left.set(z,w);
693 for(g->first(e,s); g->valid(e); g->next(e))
695 Num c=(*capacity)[e];
696 if ( c <= 0 ) continue;
698 if ( level[w] < n ) {
699 if ( excess[w] <= 0 && w!=t )
701 next.set(w,first[level[w]]);
703 //active[level[w]].push(w);
706 excess.set(w, excess[w]+c);
715 //Reverse_bfs from t in the residual graph,
716 //to find the starting level.
720 while (!bfs_queue.empty()) {
722 Node v=bfs_queue.front();
727 for(g->first(e,v); g->valid(e); g->next(e)) {
728 if ( (*capacity)[e] <= (*flow)[e] ) continue;
730 if ( level[w] == n && w != s ) {
732 Node z=level_list[l];
733 if ( g->valid(z) ) left.set(z,w);
741 for(g->first(f,v); g->valid(f); g->next(f)) {
742 if ( 0 >= (*flow)[f] ) continue;
744 if ( level[w] == n && w != s ) {
746 Node z=level_list[l];
747 if ( g->valid(z) ) left.set(z,w);
758 for(g->first(e,s); g->valid(e); g->next(e))
760 Num rem=(*capacity)[e]-(*flow)[e];
761 if ( rem <= 0 ) continue;
763 if ( level[w] < n ) {
764 if ( excess[w] <= 0 && w!=t )
766 next.set(w,first[level[w]]);
768 //active[level[w]].push(w);
770 flow->set(e, (*capacity)[e]);
771 excess.set(w, excess[w]+rem);
776 for(g->first(f,s); g->valid(f); g->next(f))
778 if ( (*flow)[f] <= 0 ) continue;
780 if ( level[w] < n ) {
781 if ( excess[w] <= 0 && w!=t )
783 next.set(w,first[level[w]]);
785 //active[level[w]].push(w);
787 excess.set(w, excess[w]+(*flow)[f]);
798 void relabel(Node w, int newlevel, NNMap& next, VecFirst& first,
799 VecNode& level_list, NNMap& left,
800 NNMap& right, int& b, int& k, bool what_heur )
805 Node right_n=right[w];
809 if ( g->valid(right_n) ) {
810 if ( g->valid(left_n) ) {
811 right.set(left_n, right_n);
812 left.set(right_n, left_n);
814 level_list[lev]=right_n;
815 left.set(right_n, INVALID);
818 if ( g->valid(left_n) ) {
819 right.set(left_n, INVALID);
821 level_list[lev]=INVALID;
826 if ( !g->valid(level_list[lev]) ) {
829 for (int i=lev; i!=k ; ) {
830 Node v=level_list[++i];
831 while ( g->valid(v) ) {
835 level_list[i]=INVALID;
836 if ( !what_heur ) first[i]=INVALID;
838 while ( !active[i].empty() ) {
839 active[i].pop(); //FIXME: ezt szebben kene
851 if ( newlevel == n ) level.set(w,n);
853 level.set(w,++newlevel);
854 next.set(w,first[newlevel]);
856 // active[newlevel].push(w);
857 if ( what_heur ) b=newlevel;
858 if ( k < newlevel ) ++k; //now k=newlevel
859 Node z=level_list[newlevel];
860 if ( g->valid(z) ) left.set(z,w);
863 level_list[newlevel]=w;
870 #endif //HUGO_MAX_FLOW_H