2 * src/lemon/preflow.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2005 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 LEMON_PREFLOW_H
18 #define LEMON_PREFLOW_H
23 #include <lemon/invalid.h>
24 #include <lemon/maps.h>
25 #include <lemon/graph_utils.h>
29 /// Implementation of the preflow algorithm.
33 /// \addtogroup flowalgs
36 ///%Preflow algorithms class.
38 ///This class provides an implementation of the \e preflow \e
39 ///algorithm producing a flow of maximum value in a directed
40 ///graph. The preflow algorithms are the fastest known max flow algorithms
41 ///up to now. The \e source node, the \e target node, the \e
42 ///capacity of the edges and the \e starting \e flow value of the
43 ///edges should be passed to the algorithm through the
44 ///constructor. It is possible to change these quantities using the
45 ///functions \ref source, \ref target, \ref setCap and \ref
48 ///After running \ref lemon::Preflow::phase1() "phase1()"
49 ///or \ref lemon::Preflow::run() "run()", the maximal flow
50 ///value can be obtained by calling \ref flowValue(). The minimum
51 ///value cut can be written into a <tt>bool</tt> node map by
52 ///calling \ref minCut(). (\ref minMinCut() and \ref maxMinCut() writes
53 ///the inclusionwise minimum and maximum of the minimum value cuts,
56 ///\param Graph The directed graph type the algorithm runs on.
57 ///\param Num The number type of the capacities and the flow values.
58 ///\param CapacityMap The capacity map type.
59 ///\param FlowMap The flow map type.
61 ///\author Jacint Szabo
62 template <typename Graph, typename Num,
63 typename CapacityMap=typename Graph::template EdgeMap<Num>,
64 typename FlowMap=typename Graph::template EdgeMap<Num> >
67 typedef typename Graph::Node Node;
68 typedef typename Graph::NodeIt NodeIt;
69 typedef typename Graph::EdgeIt EdgeIt;
70 typedef typename Graph::OutEdgeIt OutEdgeIt;
71 typedef typename Graph::InEdgeIt InEdgeIt;
73 typedef typename Graph::template NodeMap<Node> NNMap;
74 typedef typename std::vector<Node> VecNode;
79 const CapacityMap* _capacity;
81 int _node_num; //the number of nodes of G
83 typename Graph::template NodeMap<int> level;
84 typename Graph::template NodeMap<Num> excess;
86 // constants used for heuristics
87 static const int H0=20;
88 static const int H1=1;
92 ///Indicates the property of the starting flow map.
94 ///Indicates the property of the starting flow map.
95 ///The meanings are as follows:
96 ///- \c ZERO_FLOW: constant zero flow
97 ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
98 ///the sum of the out-flows in every node except the \e source and
100 ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at
101 ///least the sum of the out-flows in every node except the \e source.
102 ///- \c NO_FLOW: indicates an unspecified edge map. \c flow will be
103 ///set to the constant zero flow in the beginning of
104 ///the algorithm in this case.
113 ///Indicates the state of the preflow algorithm.
115 ///Indicates the state of the preflow algorithm.
116 ///The meanings are as follows:
117 ///- \c AFTER_NOTHING: before running the algorithm or
118 /// at an unspecified state.
119 ///- \c AFTER_PREFLOW_PHASE_1: right after running \c phase1
120 ///- \c AFTER_PREFLOW_PHASE_2: after running \ref phase2()
124 AFTER_PREFLOW_PHASE_1,
125 AFTER_PREFLOW_PHASE_2
130 StatusEnum status; // Do not needle this flag only if necessary.
133 ///The constructor of the class.
135 ///The constructor of the class.
136 ///\param _G The directed graph the algorithm runs on.
137 ///\param _s The source node.
138 ///\param _t The target node.
139 ///\param _cap The capacity of the edges.
140 ///\param _f The flow of the edges.
141 ///Except the graph, all of these parameters can be reset by
142 ///calling \ref source, \ref target, \ref setCap and \ref
144 Preflow(const Graph& _gr, Node _s, Node _t,
145 const CapacityMap& _cap, FlowMap& _f) :
146 _g(&_gr), _source(_s), _target(_t), _capacity(&_cap),
147 _flow(&_f), _node_num(countNodes(_gr)), level(_gr), excess(_gr,0),
148 flow_prop(NO_FLOW), status(AFTER_NOTHING) { }
152 ///Runs the preflow algorithm.
154 ///Runs the preflow algorithm.
161 ///Runs the preflow algorithm.
163 ///Runs the preflow algorithm.
164 ///\pre The starting flow map must be
165 /// - a constant zero flow if \c fp is \c ZERO_FLOW,
166 /// - an arbitrary flow if \c fp is \c GEN_FLOW,
167 /// - an arbitrary preflow if \c fp is \c PRE_FLOW,
168 /// - any map if \c fp is NO_FLOW.
169 ///If the starting flow map is a flow or a preflow then
170 ///the algorithm terminates faster.
171 void run(FlowEnum fp) {
176 ///Runs the first phase of the preflow algorithm.
178 ///The preflow algorithm consists of two phases, this method runs
179 ///the first phase. After the first phase the maximum flow value
180 ///and a minimum value cut can already be computed, though a
181 ///maximum flow is not yet obtained. So after calling this method
182 ///\ref flowValue returns the value of a maximum flow and \ref
183 ///minCut returns a minimum cut.
184 ///\warning \ref minMinCut and \ref maxMinCut do not give minimum
185 ///value cuts unless calling \ref phase2.
186 ///\pre The starting flow must be
187 ///- a constant zero flow if \c fp is \c ZERO_FLOW,
188 ///- an arbitary flow if \c fp is \c GEN_FLOW,
189 ///- an arbitary preflow if \c fp is \c PRE_FLOW,
190 ///- any map if \c fp is NO_FLOW.
191 void phase1(FlowEnum fp)
198 ///Runs the first phase of the preflow algorithm.
200 ///The preflow algorithm consists of two phases, this method runs
201 ///the first phase. After the first phase the maximum flow value
202 ///and a minimum value cut can already be computed, though a
203 ///maximum flow is not yet obtained. So after calling this method
204 ///\ref flowValue returns the value of a maximum flow and \ref
205 ///minCut returns a minimum cut.
206 ///\warning \ref minCut(), \ref minMinCut() and \ref maxMinCut() do not
207 ///give minimum value cuts unless calling \ref phase2().
210 int heur0=(int)(H0*_node_num); //time while running 'bound decrease'
211 int heur1=(int)(H1*_node_num); //time while running 'highest label'
212 int heur=heur1; //starting time interval (#of relabels)
216 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
219 //Needed for 'bound decrease', true means no active
220 //nodes are above bound b.
222 int k=_node_num-2; //bound on the highest level under n containing a node
223 int b=k; //bound on the highest level under n of an active node
225 VecNode first(_node_num, INVALID);
226 NNMap next(*_g, INVALID);
228 NNMap left(*_g, INVALID);
229 NNMap right(*_g, INVALID);
230 VecNode level_list(_node_num,INVALID);
231 //List of the nodes in level i<n, set to n.
233 preflowPreproc(first, next, level_list, left, right);
235 //Push/relabel on the highest level active nodes.
238 if ( !what_heur && !end && k > 0 ) {
244 if ( first[b]==INVALID ) --b;
249 int newlevel=push(w, next, first);
250 if ( excess[w] > 0 ) relabel(w, newlevel, first, next, level_list,
251 left, right, b, k, what_heur);
254 if ( numrelabel >= heur ) {
269 status=AFTER_PREFLOW_PHASE_1;
274 // list 'level_list' on the nodes on level i implemented by hand
275 // stack 'active' on the active nodes on level i
276 // runs heuristic 'highest label' for H1*n relabels
277 // runs heuristic 'bound decrease' for H0*n relabels,
278 // starts with 'highest label'
279 // Parameters H0 and H1 are initialized to 20 and 1.
282 ///Runs the second phase of the preflow algorithm.
284 ///The preflow algorithm consists of two phases, this method runs
285 ///the second phase. After calling \ref phase1 and then \ref
286 ///phase2, \ref flow contains a maximum flow, \ref flowValue
287 ///returns the value of a maximum flow, \ref minCut returns a
288 ///minimum cut, while the methods \ref minMinCut and \ref
289 ///maxMinCut return the inclusionwise minimum and maximum cuts of
290 ///minimum value, resp. \pre \ref phase1 must be called before.
294 int k=_node_num-2; //bound on the highest level under n containing a node
295 int b=k; //bound on the highest level under n of an active node
298 VecNode first(_node_num, INVALID);
299 NNMap next(*_g, INVALID);
300 level.set(_source,0);
301 std::queue<Node> bfs_queue;
302 bfs_queue.push(_source);
304 while ( !bfs_queue.empty() ) {
306 Node v=bfs_queue.front();
310 for(InEdgeIt e(*_g,v); e!=INVALID; ++e) {
311 if ( (*_capacity)[e] <= (*_flow)[e] ) continue;
312 Node u=_g->source(e);
313 if ( level[u] >= _node_num ) {
316 if ( excess[u] > 0 ) {
317 next.set(u,first[l]);
323 for(OutEdgeIt e(*_g,v); e!=INVALID; ++e) {
324 if ( 0 >= (*_flow)[e] ) continue;
325 Node u=_g->target(e);
326 if ( level[u] >= _node_num ) {
329 if ( excess[u] > 0 ) {
330 next.set(u,first[l]);
341 if ( first[b]==INVALID ) --b;
345 int newlevel=push(w,next, first);
348 if ( excess[w] > 0 ) {
349 level.set(w,++newlevel);
350 next.set(w,first[newlevel]);
357 status=AFTER_PREFLOW_PHASE_2;
360 /// Returns the value of the maximum flow.
362 /// Returns the value of the maximum flow by returning the excess
363 /// of the target node \c t. This value equals to the value of
364 /// the maximum flow already after running \ref phase1.
365 Num flowValue() const {
366 return excess[_target];
370 ///Returns a minimum value cut.
372 ///Sets \c M to the characteristic vector of a minimum value
373 ///cut. This method can be called both after running \ref
374 ///phase1 and \ref phase2. It is much faster after
375 ///\ref phase1. \pre M should be a bool-valued node-map. \pre
376 ///If \ref minCut() is called after \ref phase2() then M should
377 ///be initialized to false.
378 template<typename _CutMap>
379 void minCut(_CutMap& M) const {
381 case AFTER_PREFLOW_PHASE_1:
382 for(NodeIt v(*_g); v!=INVALID; ++v) {
383 if (level[v] < _node_num) {
390 case AFTER_PREFLOW_PHASE_2:
398 ///Returns the inclusionwise minimum of the minimum value cuts.
400 ///Sets \c M to the characteristic vector of the minimum value cut
401 ///which is inclusionwise minimum. It is computed by processing a
402 ///bfs from the source node \c s in the residual graph. \pre M
403 ///should be a node map of bools initialized to false. \pre \ref
404 ///phase2 should already be run.
405 template<typename _CutMap>
406 void minMinCut(_CutMap& M) const {
408 std::queue<Node> queue;
412 while (!queue.empty()) {
413 Node w=queue.front();
416 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
417 Node v=_g->target(e);
418 if (!M[v] && (*_flow)[e] < (*_capacity)[e] ) {
424 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
425 Node v=_g->source(e);
426 if (!M[v] && (*_flow)[e] > 0 ) {
434 ///Returns the inclusionwise maximum of the minimum value cuts.
436 ///Sets \c M to the characteristic vector of the minimum value cut
437 ///which is inclusionwise maximum. It is computed by processing a
438 ///backward bfs from the target node \c t in the residual graph.
439 ///\pre \ref phase2() or run() should already be run.
440 template<typename _CutMap>
441 void maxMinCut(_CutMap& M) const {
443 for(NodeIt v(*_g) ; v!=INVALID; ++v) M.set(v, true);
445 std::queue<Node> queue;
447 M.set(_target,false);
450 while (!queue.empty()) {
451 Node w=queue.front();
454 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
455 Node v=_g->source(e);
456 if (M[v] && (*_flow)[e] < (*_capacity)[e] ) {
462 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
463 Node v=_g->target(e);
464 if (M[v] && (*_flow)[e] > 0 ) {
472 ///Sets the source node to \c _s.
474 ///Sets the source node to \c _s.
476 void source(Node _s) {
478 if ( flow_prop != ZERO_FLOW ) flow_prop=NO_FLOW;
479 status=AFTER_NOTHING;
482 ///Returns the source node.
484 ///Returns the source node.
486 Node source() const {
490 ///Sets the target node to \c _t.
492 ///Sets the target node to \c _t.
494 void target(Node _t) {
496 if ( flow_prop == GEN_FLOW ) flow_prop=PRE_FLOW;
497 status=AFTER_NOTHING;
500 ///Returns the target node.
502 ///Returns the target node.
504 Node target() const {
508 /// Sets the edge map of the capacities to _cap.
510 /// Sets the edge map of the capacities to _cap.
512 void capacityMap(const CapacityMap& _cap) {
514 status=AFTER_NOTHING;
516 /// Returns a reference to to capacity map.
518 /// Returns a reference to to capacity map.
520 const CapacityMap &capacityMap() const {
524 /// Sets the edge map of the flows to _flow.
526 /// Sets the edge map of the flows to _flow.
528 void flowMap(FlowMap& _f) {
531 status=AFTER_NOTHING;
534 /// Returns a reference to to flow map.
536 /// Returns a reference to to flow map.
538 const FlowMap &flowMap() const {
544 int push(Node w, NNMap& next, VecNode& first) {
548 int newlevel=_node_num; //bound on the next level of w
550 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
551 if ( (*_flow)[e] >= (*_capacity)[e] ) continue;
552 Node v=_g->target(e);
554 if( lev > level[v] ) { //Push is allowed now
556 if ( excess[v]<=0 && v!=_target && v!=_source ) {
557 next.set(v,first[level[v]]);
561 Num cap=(*_capacity)[e];
565 if ( remcap >= exc ) { //A nonsaturating push.
567 _flow->set(e, flo+exc);
568 excess.set(v, excess[v]+exc);
572 } else { //A saturating push.
574 excess.set(v, excess[v]+remcap);
577 } else if ( newlevel > level[v] ) newlevel = level[v];
581 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
583 if( (*_flow)[e] <= 0 ) continue;
584 Node v=_g->source(e);
586 if( lev > level[v] ) { //Push is allowed now
588 if ( excess[v]<=0 && v!=_target && v!=_source ) {
589 next.set(v,first[level[v]]);
595 if ( flo >= exc ) { //A nonsaturating push.
597 _flow->set(e, flo-exc);
598 excess.set(v, excess[v]+exc);
601 } else { //A saturating push.
603 excess.set(v, excess[v]+flo);
607 } else if ( newlevel > level[v] ) newlevel = level[v];
610 } // if w still has excess after the out edge for cycle
619 void preflowPreproc(VecNode& first, NNMap& next,
620 VecNode& level_list, NNMap& left, NNMap& right)
622 for(NodeIt v(*_g); v!=INVALID; ++v) level.set(v,_node_num);
623 std::queue<Node> bfs_queue;
625 if ( flow_prop == GEN_FLOW || flow_prop == PRE_FLOW ) {
626 //Reverse_bfs from t in the residual graph,
627 //to find the starting level.
628 level.set(_target,0);
629 bfs_queue.push(_target);
631 while ( !bfs_queue.empty() ) {
633 Node v=bfs_queue.front();
637 for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
638 if ( (*_capacity)[e] <= (*_flow)[e] ) continue;
639 Node w=_g->source(e);
640 if ( level[w] == _node_num && w != _source ) {
642 Node z=level_list[l];
643 if ( z!=INVALID ) left.set(z,w);
650 for(OutEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
651 if ( 0 >= (*_flow)[e] ) continue;
652 Node w=_g->target(e);
653 if ( level[w] == _node_num && w != _source ) {
655 Node z=level_list[l];
656 if ( z!=INVALID ) left.set(z,w);
668 for(EdgeIt e(*_g); e!=INVALID; ++e) _flow->set(e,0);
670 for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
672 //Reverse_bfs from t, to find the starting level.
673 level.set(_target,0);
674 bfs_queue.push(_target);
676 while ( !bfs_queue.empty() ) {
678 Node v=bfs_queue.front();
682 for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
683 Node w=_g->source(e);
684 if ( level[w] == _node_num && w != _source ) {
686 Node z=level_list[l];
687 if ( z!=INVALID ) left.set(z,w);
696 for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
697 Num c=(*_capacity)[e];
698 if ( c <= 0 ) continue;
699 Node w=_g->target(e);
700 if ( level[w] < _node_num ) {
701 if ( excess[w] <= 0 && w!=_target ) { //putting into the stack
702 next.set(w,first[level[w]]);
706 excess.set(w, excess[w]+c);
712 for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
715 for(InEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc+=(*_flow)[e];
716 for(OutEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc-=(*_flow)[e];
717 excess.set(_target,exc);
721 for(OutEdgeIt e(*_g,_source); e!=INVALID; ++e) {
722 Num rem=(*_capacity)[e]-(*_flow)[e];
723 if ( rem <= 0 ) continue;
724 Node w=_g->target(e);
725 if ( level[w] < _node_num ) {
726 if ( excess[w] <= 0 && w!=_target ) { //putting into the stack
727 next.set(w,first[level[w]]);
730 _flow->set(e, (*_capacity)[e]);
731 excess.set(w, excess[w]+rem);
735 for(InEdgeIt e(*_g,_source); e!=INVALID; ++e) {
736 if ( (*_flow)[e] <= 0 ) continue;
737 Node w=_g->source(e);
738 if ( level[w] < _node_num ) {
739 if ( excess[w] <= 0 && w!=_target ) {
740 next.set(w,first[level[w]]);
743 excess.set(w, excess[w]+(*_flow)[e]);
751 for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
752 Num rem=(*_capacity)[e]-(*_flow)[e];
753 if ( rem <= 0 ) continue;
754 Node w=_g->target(e);
755 if ( level[w] < _node_num ) _flow->set(e, (*_capacity)[e]);
758 for(InEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
759 if ( (*_flow)[e] <= 0 ) continue;
760 Node w=_g->source(e);
761 if ( level[w] < _node_num ) _flow->set(e, 0);
764 //computing the excess
765 for(NodeIt w(*_g); w!=INVALID; ++w) {
767 for(InEdgeIt e(*_g,w); e!=INVALID; ++e) exc+=(*_flow)[e];
768 for(OutEdgeIt e(*_g,w); e!=INVALID; ++e) exc-=(*_flow)[e];
771 //putting the active nodes into the stack
773 if ( exc > 0 && lev < _node_num && Node(w) != _target ) {
774 next.set(w,first[lev]);
783 void relabel(Node w, int newlevel, VecNode& first, NNMap& next,
784 VecNode& level_list, NNMap& left,
785 NNMap& right, int& b, int& k, bool what_heur )
790 Node right_n=right[w];
794 if ( right_n!=INVALID ) {
795 if ( left_n!=INVALID ) {
796 right.set(left_n, right_n);
797 left.set(right_n, left_n);
799 level_list[lev]=right_n;
800 left.set(right_n, INVALID);
803 if ( left_n!=INVALID ) {
804 right.set(left_n, INVALID);
806 level_list[lev]=INVALID;
811 if ( level_list[lev]==INVALID ) {
814 for (int i=lev; i!=k ; ) {
815 Node v=level_list[++i];
816 while ( v!=INVALID ) {
817 level.set(v,_node_num);
820 level_list[i]=INVALID;
821 if ( !what_heur ) first[i]=INVALID;
824 level.set(w,_node_num);
831 if ( newlevel == _node_num ) level.set(w,_node_num);
833 level.set(w,++newlevel);
834 next.set(w,first[newlevel]);
836 if ( what_heur ) b=newlevel;
837 if ( k < newlevel ) ++k; //now k=newlevel
838 Node z=level_list[newlevel];
839 if ( z!=INVALID ) left.set(z,w);
842 level_list[newlevel]=w;
850 #endif //LEMON_PREFLOW_H