beginning of a modular, generic merge_graph_wrapper...
2 * src/hugo/preflow.h - Part of HUGOlib, a generic C++ optimization library
4 * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Combinatorial Optimization Research Group, EGRES).
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
17 #ifndef HUGO_PREFLOW_H
18 #define HUGO_PREFLOW_H
23 #include <hugo/invalid.h>
24 #include <hugo/maps.h>
28 /// Implementation of the preflow algorithm.
32 /// \addtogroup flowalgs
35 ///%Preflow algorithms class.
37 ///This class provides an implementation of the \e preflow \e
38 ///algorithm producing a flow of maximum value in a directed
39 ///graph. The preflow algorithms are the fastest max flow algorithms
40 ///up to now. The \e source node, the \e target node, the \e
41 ///capacity of the edges and the \e starting \e flow value of the
42 ///edges should be passed to the algorithm through the
43 ///constructor. It is possible to change these quantities using the
44 ///functions \ref setSource, \ref setTarget, \ref setCap and \ref
47 ///After running \ref hugo::Preflow::phase1() "phase1()"
48 ///or \ref hugo::Preflow::run() "run()", the actual flow
49 ///value can be obtained by calling \ref flowValue(). The minimum
50 ///value cut can be written into a <tt>bool</tt> node map by
51 ///calling \ref minCut(). (\ref minMinCut() and \ref maxMinCut() writes
52 ///the inclusionwise minimum and maximum of the minimum value cuts,
55 ///\param Graph The directed graph type the algorithm runs on.
56 ///\param Num The number type of the capacities and the flow values.
57 ///\param CapMap The capacity map type.
58 ///\param FlowMap The flow map type.
60 ///\author Jacint Szabo
61 template <typename Graph, typename Num,
62 typename CapMap=typename Graph::template EdgeMap<Num>,
63 typename FlowMap=typename Graph::template EdgeMap<Num> >
66 typedef typename Graph::Node Node;
67 typedef typename Graph::NodeIt NodeIt;
68 typedef typename Graph::EdgeIt EdgeIt;
69 typedef typename Graph::OutEdgeIt OutEdgeIt;
70 typedef typename Graph::InEdgeIt InEdgeIt;
72 typedef typename Graph::template NodeMap<Node> NNMap;
73 typedef typename std::vector<Node> VecNode;
78 const CapMap* capacity;
80 int n; //the number of nodes of G
82 typename Graph::template NodeMap<int> level;
83 typename Graph::template NodeMap<Num> excess;
85 // constants used for heuristics
86 static const int H0=20;
87 static const int H1=1;
91 ///Indicates the property of the starting flow map.
93 ///Indicates the property of the starting flow map. The meanings are as follows:
94 ///- \c ZERO_FLOW: constant zero flow
95 ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
96 ///the sum of the out-flows in every node except the \e source and
98 ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at
99 ///least the sum of the out-flows in every node except the \e source.
100 ///- \c NO_FLOW: indicates an unspecified edge map. \c flow will be
101 ///set to the constant zero flow in the beginning of
102 ///the algorithm in this case.
111 ///Indicates the state of the preflow algorithm.
113 ///Indicates the state of the preflow algorithm. The meanings are as follows:
114 ///- \c AFTER_NOTHING: before running the algorithm or at an unspecified state.
115 ///- \c AFTER_PREFLOW_PHASE_1: right after running \c phase1
116 ///- \c AFTER_PREFLOW_PHASE_2: after running \ref phase2()
120 AFTER_PREFLOW_PHASE_1,
121 AFTER_PREFLOW_PHASE_2
126 StatusEnum status; // Do not needle this flag only if necessary.
129 ///The constructor of the class.
131 ///The constructor of the class.
132 ///\param _G The directed graph the algorithm runs on.
133 ///\param _s The source node.
134 ///\param _t The target node.
135 ///\param _capacity The capacity of the edges.
136 ///\param _flow The flow of the edges.
137 ///Except the graph, all of these parameters can be reset by
138 ///calling \ref setSource, \ref setTarget, \ref setCap and \ref
140 Preflow(const Graph& _G, Node _s, Node _t,
141 const CapMap& _capacity, FlowMap& _flow) :
142 g(&_G), s(_s), t(_t), capacity(&_capacity),
143 flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0),
144 flow_prop(NO_FLOW), status(AFTER_NOTHING) { }
148 ///Runs the preflow algorithm.
150 ///Runs the preflow algorithm.
157 ///Runs the preflow algorithm.
159 ///Runs the preflow algorithm.
160 ///\pre The starting flow map must be
161 /// - a constant zero flow if \c fp is \c ZERO_FLOW,
162 /// - an arbitrary flow if \c fp is \c GEN_FLOW,
163 /// - an arbitrary preflow if \c fp is \c PRE_FLOW,
164 /// - any map if \c fp is NO_FLOW.
165 ///If the starting flow map is a flow or a preflow then
166 ///the algorithm terminates faster.
167 void run(FlowEnum fp) {
172 ///Runs the first phase of the preflow algorithm.
174 ///The preflow algorithm consists of two phases, this method runs the
175 ///first phase. After the first phase the maximum flow value and a
176 ///minimum value cut can already be computed, though a maximum flow
177 ///is not yet obtained. So after calling this method \ref flowValue
178 ///and \ref minCut gives proper results.
179 ///\warning \ref minMinCut and \ref maxMinCut do not
180 ///give minimum value cuts unless calling \ref phase2.
181 ///\pre The starting flow must be
182 /// - a constant zero flow if \c fp is \c ZERO_FLOW,
183 /// - an arbitary flow if \c fp is \c GEN_FLOW,
184 /// - an arbitary preflow if \c fp is \c PRE_FLOW,
185 /// - any map if \c fp is NO_FLOW.
186 void phase1(FlowEnum fp)
193 ///Runs the first phase of the preflow algorithm.
195 ///The preflow algorithm consists of two phases, this method runs the
196 ///first phase. After the first phase the maximum flow value and a
197 ///minimum value cut can already be computed, though a maximum flow
198 ///is not yet obtained. So after calling this method \ref flowValue
199 ///and \ref MinCut() gives proper results.
200 ///\warning \ref minCut(), \ref minMinCut() and \ref maxMinCut() do not
201 ///give minimum value cuts unless calling \ref phase2().
204 int heur0=(int)(H0*n); //time while running 'bound decrease'
205 int heur1=(int)(H1*n); //time while running 'highest label'
206 int heur=heur1; //starting time interval (#of relabels)
210 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
213 //Needed for 'bound decrease', true means no active
214 //nodes are above bound b.
216 int k=n-2; //bound on the highest level under n containing a node
217 int b=k; //bound on the highest level under n of an active node
219 VecNode first(n, INVALID);
220 NNMap next(*g, INVALID);
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.
227 preflowPreproc(first, next, level_list, left, right);
229 //Push/relabel on the highest level active nodes.
232 if ( !what_heur && !end && k > 0 ) {
238 if ( first[b]==INVALID ) --b;
243 int newlevel=push(w, next, first);
244 if ( excess[w] > 0 ) relabel(w, newlevel, first, next, level_list,
245 left, right, b, k, what_heur);
248 if ( numrelabel >= heur ) {
263 status=AFTER_PREFLOW_PHASE_1;
268 // list 'level_list' on the nodes on level i implemented by hand
269 // stack 'active' on the active nodes on level i
270 // runs heuristic 'highest label' for H1*n relabels
271 // runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
272 // Parameters H0 and H1 are initialized to 20 and 1.
275 ///Runs the second phase of the preflow algorithm.
277 ///The preflow algorithm consists of two phases, this method runs
278 ///the second phase. After calling \ref phase1 and then
279 ///\ref phase2 the methods \ref flowValue, \ref minCut,
280 ///\ref minMinCut and \ref maxMinCut give proper results.
281 ///\pre \ref phase1 must be called before.
285 int k=n-2; //bound on the highest level under n containing a node
286 int b=k; //bound on the highest level under n of an active node
289 VecNode first(n, INVALID);
290 NNMap next(*g, INVALID);
292 std::queue<Node> bfs_queue;
295 while ( !bfs_queue.empty() ) {
297 Node v=bfs_queue.front();
301 for(InEdgeIt e(*g,v); e!=INVALID; ++e) {
302 if ( (*capacity)[e] <= (*flow)[e] ) continue;
304 if ( level[u] >= n ) {
307 if ( excess[u] > 0 ) {
308 next.set(u,first[l]);
314 for(OutEdgeIt e(*g,v); e!=INVALID; ++e) {
315 if ( 0 >= (*flow)[e] ) continue;
317 if ( level[u] >= n ) {
320 if ( excess[u] > 0 ) {
321 next.set(u,first[l]);
332 if ( first[b]==INVALID ) --b;
336 int newlevel=push(w,next, first);
339 if ( excess[w] > 0 ) {
340 level.set(w,++newlevel);
341 next.set(w,first[newlevel]);
348 status=AFTER_PREFLOW_PHASE_2;
351 /// Returns the value of the maximum flow.
353 /// Returns the value of the maximum flow by returning the excess
354 /// of the target node \c t. This value equals to the value of
355 /// the maximum flow already after running \ref phase1.
356 Num flowValue() const {
361 ///Returns a minimum value cut.
363 ///Sets \c M to the characteristic vector of a minimum value
364 ///cut. This method can be called both after running \ref
365 ///phase1 and \ref phase2. It is much faster after
366 ///\ref phase1. \pre M should be a bool-valued node-map. \pre
367 ///If \ref minCut() is called after \ref phase2() then M should
368 ///be initialized to false.
369 template<typename _CutMap>
370 void minCut(_CutMap& M) const {
372 case AFTER_PREFLOW_PHASE_1:
373 for(NodeIt v(*g); v!=INVALID; ++v) {
381 case AFTER_PREFLOW_PHASE_2:
389 ///Returns the inclusionwise minimum of the minimum value cuts.
391 ///Sets \c M to the characteristic vector of the minimum value cut
392 ///which is inclusionwise minimum. It is computed by processing a
393 ///bfs from the source node \c s in the residual graph. \pre M
394 ///should be a node map of bools initialized to false. \pre \ref
395 ///phase2 should already be run.
396 template<typename _CutMap>
397 void minMinCut(_CutMap& M) const {
399 std::queue<Node> queue;
403 while (!queue.empty()) {
404 Node w=queue.front();
407 for(OutEdgeIt e(*g,w) ; e!=INVALID; ++e) {
409 if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
415 for(InEdgeIt e(*g,w) ; e!=INVALID; ++e) {
417 if (!M[v] && (*flow)[e] > 0 ) {
425 ///Returns the inclusionwise maximum of the minimum value cuts.
427 ///Sets \c M to the characteristic vector of the minimum value cut
428 ///which is inclusionwise maximum. It is computed by processing a
429 ///backward bfs from the target node \c t in the residual graph.
430 ///\pre \ref phase2() or run() should already be run.
431 template<typename _CutMap>
432 void maxMinCut(_CutMap& M) const {
434 for(NodeIt v(*g) ; v!=INVALID; ++v) M.set(v, true);
436 std::queue<Node> queue;
441 while (!queue.empty()) {
442 Node w=queue.front();
445 for(InEdgeIt e(*g,w) ; e!=INVALID; ++e) {
447 if (M[v] && (*flow)[e] < (*capacity)[e] ) {
453 for(OutEdgeIt e(*g,w) ; e!=INVALID; ++e) {
455 if (M[v] && (*flow)[e] > 0 ) {
463 ///Sets the source node to \c _s.
465 ///Sets the source node to \c _s.
467 void setSource(Node _s) {
469 if ( flow_prop != ZERO_FLOW ) flow_prop=NO_FLOW;
470 status=AFTER_NOTHING;
473 ///Sets the target node to \c _t.
475 ///Sets the target node to \c _t.
477 void setTarget(Node _t) {
479 if ( flow_prop == GEN_FLOW ) flow_prop=PRE_FLOW;
480 status=AFTER_NOTHING;
483 /// Sets the edge map of the capacities to _cap.
485 /// Sets the edge map of the capacities to _cap.
487 void setCap(const CapMap& _cap) {
489 status=AFTER_NOTHING;
492 /// Sets the edge map of the flows to _flow.
494 /// Sets the edge map of the flows to _flow.
496 void setFlow(FlowMap& _flow) {
499 status=AFTER_NOTHING;
505 int push(Node w, NNMap& next, VecNode& 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(VecNode& first, NNMap& next,
581 VecNode& level_list, NNMap& left, NNMap& right)
583 for(NodeIt v(*g); v!=INVALID; ++v) level.set(v,n);
584 std::queue<Node> bfs_queue;
586 if ( flow_prop == GEN_FLOW || flow_prop == PRE_FLOW ) {
587 //Reverse_bfs from t in the residual graph,
588 //to find the starting level.
592 while ( !bfs_queue.empty() ) {
594 Node v=bfs_queue.front();
598 for(InEdgeIt e(*g,v) ; e!=INVALID; ++e) {
599 if ( (*capacity)[e] <= (*flow)[e] ) continue;
601 if ( level[w] == n && w != s ) {
603 Node z=level_list[l];
604 if ( z!=INVALID ) left.set(z,w);
611 for(OutEdgeIt e(*g,v) ; e!=INVALID; ++e) {
612 if ( 0 >= (*flow)[e] ) continue;
614 if ( level[w] == n && w != s ) {
616 Node z=level_list[l];
617 if ( z!=INVALID ) left.set(z,w);
629 for(EdgeIt e(*g); e!=INVALID; ++e) flow->set(e,0);
631 for(NodeIt v(*g); v!=INVALID; ++v) excess.set(v,0);
633 //Reverse_bfs from t, to find the starting level.
637 while ( !bfs_queue.empty() ) {
639 Node v=bfs_queue.front();
643 for(InEdgeIt e(*g,v) ; e!=INVALID; ++e) {
645 if ( level[w] == n && w != s ) {
647 Node z=level_list[l];
648 if ( z!=INVALID ) left.set(z,w);
657 for(OutEdgeIt e(*g,s) ; e!=INVALID; ++e) {
658 Num c=(*capacity)[e];
659 if ( c <= 0 ) continue;
661 if ( level[w] < n ) {
662 if ( excess[w] <= 0 && w!=t ) { //putting into the stack
663 next.set(w,first[level[w]]);
667 excess.set(w, excess[w]+c);
673 for(NodeIt v(*g); v!=INVALID; ++v) excess.set(v,0);
676 for(InEdgeIt e(*g,t) ; e!=INVALID; ++e) exc+=(*flow)[e];
677 for(OutEdgeIt e(*g,t) ; e!=INVALID; ++e) exc-=(*flow)[e];
682 for(OutEdgeIt e(*g,s); e!=INVALID; ++e) {
683 Num rem=(*capacity)[e]-(*flow)[e];
684 if ( rem <= 0 ) continue;
686 if ( level[w] < n ) {
687 if ( excess[w] <= 0 && w!=t ) { //putting into the stack
688 next.set(w,first[level[w]]);
691 flow->set(e, (*capacity)[e]);
692 excess.set(w, excess[w]+rem);
696 for(InEdgeIt e(*g,s); e!=INVALID; ++e) {
697 if ( (*flow)[e] <= 0 ) continue;
699 if ( level[w] < n ) {
700 if ( excess[w] <= 0 && w!=t ) {
701 next.set(w,first[level[w]]);
704 excess.set(w, excess[w]+(*flow)[e]);
712 for(OutEdgeIt e(*g,s) ; e!=INVALID; ++e) {
713 Num rem=(*capacity)[e]-(*flow)[e];
714 if ( rem <= 0 ) continue;
716 if ( level[w] < n ) flow->set(e, (*capacity)[e]);
719 for(InEdgeIt e(*g,s) ; e!=INVALID; ++e) {
720 if ( (*flow)[e] <= 0 ) continue;
722 if ( level[w] < n ) flow->set(e, 0);
725 //computing the excess
726 for(NodeIt w(*g); w!=INVALID; ++w) {
728 for(InEdgeIt e(*g,w); e!=INVALID; ++e) exc+=(*flow)[e];
729 for(OutEdgeIt e(*g,w); e!=INVALID; ++e) exc-=(*flow)[e];
732 //putting the active nodes into the stack
734 if ( exc > 0 && lev < n && Node(w) != t ) {
735 next.set(w,first[lev]);
744 void relabel(Node w, int newlevel, VecNode& first, NNMap& next,
745 VecNode& level_list, NNMap& left,
746 NNMap& right, int& b, int& k, bool what_heur )
751 Node right_n=right[w];
755 if ( right_n!=INVALID ) {
756 if ( left_n!=INVALID ) {
757 right.set(left_n, right_n);
758 left.set(right_n, left_n);
760 level_list[lev]=right_n;
761 left.set(right_n, INVALID);
764 if ( left_n!=INVALID ) {
765 right.set(left_n, INVALID);
767 level_list[lev]=INVALID;
772 if ( level_list[lev]==INVALID ) {
775 for (int i=lev; i!=k ; ) {
776 Node v=level_list[++i];
777 while ( v!=INVALID ) {
781 level_list[i]=INVALID;
782 if ( !what_heur ) first[i]=INVALID;
792 if ( newlevel == n ) level.set(w,n);
794 level.set(w,++newlevel);
795 next.set(w,first[newlevel]);
797 if ( what_heur ) b=newlevel;
798 if ( k < newlevel ) ++k; //now k=newlevel
799 Node z=level_list[newlevel];
800 if ( z!=INVALID ) left.set(z,w);
803 level_list[newlevel]=w;
811 #endif //HUGO_PREFLOW_H