3 * This file is a part of LEMON, a generic C++ optimization library
5 * Copyright (C) 2003-2007
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
19 #ifndef LEMON_PREFLOW_H
20 #define LEMON_PREFLOW_H
25 #include <lemon/error.h>
26 #include <lemon/bits/invalid.h>
27 #include <lemon/tolerance.h>
28 #include <lemon/maps.h>
29 #include <lemon/graph_utils.h>
33 /// \brief Implementation of the preflow algorithm.
38 ///\brief %Preflow algorithms class.
40 ///This class provides an implementation of the \e preflow \e
41 ///algorithm producing a flow of maximum value in a directed
42 ///graph. The preflow algorithms are the fastest known max flow algorithms.
43 ///The \e source node, the \e target node, the \e
44 ///capacity of the edges and the \e starting \e flow value of the
45 ///edges should be passed to the algorithm through the
46 ///constructor. It is possible to change these quantities using the
47 ///functions \ref source, \ref target, \ref capacityMap and \ref
50 ///After running \ref lemon::Preflow::phase1() "phase1()"
51 ///or \ref lemon::Preflow::run() "run()", the maximal flow
52 ///value can be obtained by calling \ref flowValue(). The minimum
53 ///value cut can be written into a <tt>bool</tt> node map by
54 ///calling \ref minCut(). (\ref minMinCut() and \ref maxMinCut() writes
55 ///the inclusionwise minimum and maximum of the minimum value cuts,
58 ///\param Graph The directed graph type the algorithm runs on.
59 ///\param Num The number type of the capacities and the flow values.
60 ///\param CapacityMap The capacity map type.
61 ///\param FlowMap The flow map type.
62 ///\param Tol The tolerance type.
64 ///\author Jacint Szabo
65 ///\todo Second template parameter is superfluous
66 template <typename Graph, typename Num,
67 typename CapacityMap=typename Graph::template EdgeMap<Num>,
68 typename FlowMap=typename Graph::template EdgeMap<Num>,
69 typename Tol=Tolerance<Num> >
72 typedef typename Graph::Node Node;
73 typedef typename Graph::NodeIt NodeIt;
74 typedef typename Graph::EdgeIt EdgeIt;
75 typedef typename Graph::OutEdgeIt OutEdgeIt;
76 typedef typename Graph::InEdgeIt InEdgeIt;
78 typedef typename Graph::template NodeMap<Node> NNMap;
79 typedef typename std::vector<Node> VecNode;
84 const CapacityMap* _capacity;
89 int _node_num; //the number of nodes of G
91 typename Graph::template NodeMap<int> level;
92 typename Graph::template NodeMap<Num> excess;
94 // constants used for heuristics
95 static const int H0=20;
96 static const int H1=1;
100 ///\ref Exception for the case when s=t.
102 ///\ref Exception for the case when the source equals the target.
103 class InvalidArgument : public lemon::LogicError {
105 virtual const char* what() const throw() {
106 return "lemon::Preflow::InvalidArgument";
111 ///Indicates the property of the starting flow map.
113 ///Indicates the property of the starting flow map.
116 ///indicates an unspecified edge map. \c flow will be
117 ///set to the constant zero flow in the beginning of
118 ///the algorithm in this case.
120 ///constant zero flow
122 ///any flow, i.e. the sum of the in-flows equals to
123 ///the sum of the out-flows in every node except the \c source and
126 ///any preflow, i.e. the sum of the in-flows is at
127 ///least the sum of the out-flows in every node except the \c source.
131 ///Indicates the state of the preflow algorithm.
133 ///Indicates the state of the preflow algorithm.
136 ///before running the algorithm or
137 ///at an unspecified state.
139 ///right after running \ref phase1()
140 AFTER_PREFLOW_PHASE_1,
141 ///after running \ref phase2()
142 AFTER_PREFLOW_PHASE_2
147 StatusEnum status; // Do not needle this flag only if necessary.
150 ///The constructor of the class.
152 ///The constructor of the class.
153 ///\param _gr The directed graph the algorithm runs on.
154 ///\param _s The source node.
155 ///\param _t The target node.
156 ///\param _cap The capacity of the edges.
157 ///\param _f The flow of the edges.
158 ///\param _sr Tol class.
159 ///Except the graph, all of these parameters can be reset by
160 ///calling \ref source, \ref target, \ref capacityMap and \ref
162 Preflow(const Graph& _gr, Node _s, Node _t,
163 const CapacityMap& _cap, FlowMap& _f,
164 const Tol &_sr=Tol()) :
165 _g(&_gr), _source(_s), _target(_t), _capacity(&_cap),
166 _flow(&_f), _surely(_sr),
167 _node_num(countNodes(_gr)), level(_gr), excess(_gr,0),
168 flow_prop(NO_FLOW), status(AFTER_NOTHING) {
169 if ( _source==_target )
170 throw InvalidArgument();
173 ///Give a reference to the tolerance handler class
175 ///Give a reference to the tolerance handler class
177 Tol &tolerance() { return _surely; }
179 ///Runs the preflow algorithm.
181 ///Runs the preflow algorithm.
188 ///Runs the preflow algorithm.
190 ///Runs the preflow algorithm.
191 ///\pre The starting flow map must be
192 /// - a constant zero flow if \c fp is \c ZERO_FLOW,
193 /// - an arbitrary flow if \c fp is \c GEN_FLOW,
194 /// - an arbitrary preflow if \c fp is \c PRE_FLOW,
195 /// - any map if \c fp is NO_FLOW.
196 ///If the starting flow map is a flow or a preflow then
197 ///the algorithm terminates faster.
198 void run(FlowEnum fp) {
203 ///Runs the first phase of the preflow algorithm.
205 ///The preflow algorithm consists of two phases, this method runs
206 ///the first phase. After the first phase the maximum flow value
207 ///and a minimum value cut can already be computed, although a
208 ///maximum flow is not yet obtained. So after calling this method
209 ///\ref flowValue returns the value of a maximum flow and \ref
210 ///minCut returns a minimum cut.
211 ///\warning \ref minMinCut and \ref maxMinCut do not give minimum
212 ///value cuts unless calling \ref phase2.
213 ///\warning A real flow map (i.e. not \ref lemon::NullMap "NullMap")
214 ///is needed for this phase.
215 ///\pre The starting flow must be
216 ///- a constant zero flow if \c fp is \c ZERO_FLOW,
217 ///- an arbitary flow if \c fp is \c GEN_FLOW,
218 ///- an arbitary preflow if \c fp is \c PRE_FLOW,
219 ///- any map if \c fp is NO_FLOW.
220 void phase1(FlowEnum fp)
227 ///Runs the first phase of the preflow algorithm.
229 ///The preflow algorithm consists of two phases, this method runs
230 ///the first phase. After the first phase the maximum flow value
231 ///and a minimum value cut can already be computed, although a
232 ///maximum flow is not yet obtained. So after calling this method
233 ///\ref flowValue returns the value of a maximum flow and \ref
234 ///minCut returns a minimum cut.
235 ///\warning \ref minMinCut() and \ref maxMinCut() do not
236 ///give minimum value cuts unless calling \ref phase2().
237 ///\warning A real flow map (i.e. not \ref lemon::NullMap "NullMap")
238 ///is needed for this phase.
241 int heur0=int(H0*_node_num); //time while running 'bound decrease'
242 int heur1=int(H1*_node_num); //time while running 'highest label'
243 int heur=heur1; //starting time interval (#of relabels)
247 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
250 //Needed for 'bound decrease', true means no active
251 //nodes are above bound b.
253 int k=_node_num-2; //bound on the highest level under n containing a node
254 int b=k; //bound on the highest level under n containing an active node
256 VecNode first(_node_num, INVALID);
257 NNMap next(*_g, INVALID);
259 NNMap left(*_g, INVALID);
260 NNMap right(*_g, INVALID);
261 VecNode level_list(_node_num,INVALID);
262 //List of the nodes in level i<n, set to n.
264 preflowPreproc(first, next, level_list, left, right);
266 //Push/relabel on the highest level active nodes.
269 if ( !what_heur && !end && k > 0 ) {
275 if ( first[b]==INVALID ) --b;
280 int newlevel=push(w, next, first);
281 if ( excess[w] != 0 ) {
282 relabel(w, newlevel, first, next, level_list,
283 left, right, b, k, what_heur);
287 if ( numrelabel >= heur ) {
302 status=AFTER_PREFLOW_PHASE_1;
307 // list 'level_list' on the nodes on level i implemented by hand
308 // stack 'active' on the active nodes on level i
309 // runs heuristic 'highest label' for H1*n relabels
310 // runs heuristic 'bound decrease' for H0*n relabels,
311 // starts with 'highest label'
312 // Parameters H0 and H1 are initialized to 20 and 1.
315 ///Runs the second phase of the preflow algorithm.
317 ///The preflow algorithm consists of two phases, this method runs
318 ///the second phase. After calling \ref phase1() and then
320 /// \ref flowMap() return a maximum flow, \ref flowValue
321 ///returns the value of a maximum flow, \ref minCut returns a
322 ///minimum cut, while the methods \ref minMinCut and \ref
323 ///maxMinCut return the inclusionwise minimum and maximum cuts of
324 ///minimum value, resp. \pre \ref phase1 must be called before.
326 /// \todo The inexact computation can cause positive excess on a set of
327 /// unpushable nodes. We may have to watch the empty level in this case
328 /// due to avoid the terrible long running time.
332 int k=_node_num-2; //bound on the highest level under n containing a node
333 int b=k; //bound on the highest level under n of an active node
336 VecNode first(_node_num, INVALID);
337 NNMap next(*_g, INVALID);
338 level.set(_source,0);
339 std::queue<Node> bfs_queue;
340 bfs_queue.push(_source);
342 while ( !bfs_queue.empty() ) {
344 Node v=bfs_queue.front();
348 for(InEdgeIt e(*_g,v); e!=INVALID; ++e) {
349 if ( !_surely.positive((*_capacity)[e] - (*_flow)[e])) continue;
350 Node u=_g->source(e);
351 if ( level[u] >= _node_num ) {
354 if ( excess[u] != 0 ) {
355 next.set(u,first[l]);
361 for(OutEdgeIt e(*_g,v); e!=INVALID; ++e) {
362 if ( !_surely.positive((*_flow)[e]) ) continue;
363 Node u=_g->target(e);
364 if ( level[u] >= _node_num ) {
367 if ( excess[u] != 0 ) {
368 next.set(u,first[l]);
379 if ( first[b]==INVALID ) --b;
383 int newlevel=push(w,next, first);
385 if ( newlevel == _node_num) {
387 level.set(w,_node_num);
390 if ( excess[w] != 0 ) {
391 level.set(w,++newlevel);
392 next.set(w,first[newlevel]);
399 status=AFTER_PREFLOW_PHASE_2;
402 /// Returns the value of the maximum flow.
404 /// Returns the value of the maximum flow by returning the excess
405 /// of the target node \c t. This value equals to the value of
406 /// the maximum flow already after running \ref phase1.
407 Num flowValue() const {
408 return excess[_target];
412 ///Returns a minimum value cut.
414 ///Sets \c M to the characteristic vector of a minimum value
415 ///cut. This method can be called both after running \ref
416 ///phase1 and \ref phase2. It is much faster after
417 ///\ref phase1. \pre M should be a bool-valued node-map. \pre
418 ///If \ref minCut() is called after \ref phase2() then M should
419 ///be initialized to false.
420 template<typename _CutMap>
421 void minCut(_CutMap& M) const {
423 case AFTER_PREFLOW_PHASE_1:
424 for(NodeIt v(*_g); v!=INVALID; ++v) {
425 if (level[v] < _node_num) {
432 case AFTER_PREFLOW_PHASE_2:
440 ///Returns the inclusionwise minimum of the minimum value cuts.
442 ///Sets \c M to the characteristic vector of the minimum value cut
443 ///which is inclusionwise minimum. It is computed by processing a
444 ///bfs from the source node \c s in the residual graph. \pre M
445 ///should be a node map of bools initialized to false. \pre \ref
446 ///phase2 should already be run.
447 template<typename _CutMap>
448 void minMinCut(_CutMap& M) const {
450 std::queue<Node> queue;
454 while (!queue.empty()) {
455 Node w=queue.front();
458 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
459 Node v=_g->target(e);
460 if (!M[v] && _surely.positive((*_capacity)[e] -(*_flow)[e]) ) {
466 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
467 Node v=_g->source(e);
468 if (!M[v] && _surely.positive((*_flow)[e]) ) {
476 ///Returns the inclusionwise maximum of the minimum value cuts.
478 ///Sets \c M to the characteristic vector of the minimum value cut
479 ///which is inclusionwise maximum. It is computed by processing a
480 ///backward bfs from the target node \c t in the residual graph.
481 ///\pre \ref phase2() or run() should already be run.
482 template<typename _CutMap>
483 void maxMinCut(_CutMap& M) const {
485 for(NodeIt v(*_g) ; v!=INVALID; ++v) M.set(v, true);
487 std::queue<Node> queue;
489 M.set(_target,false);
492 while (!queue.empty()) {
493 Node w=queue.front();
496 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
497 Node v=_g->source(e);
498 if (M[v] && _surely.positive((*_capacity)[e] - (*_flow)[e]) ) {
504 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
505 Node v=_g->target(e);
506 if (M[v] && _surely.positive((*_flow)[e]) ) {
514 ///Sets the source node to \c _s.
516 ///Sets the source node to \c _s.
518 void source(Node _s) {
520 if ( flow_prop != ZERO_FLOW ) flow_prop=NO_FLOW;
521 status=AFTER_NOTHING;
524 ///Returns the source node.
526 ///Returns the source node.
528 Node source() const {
532 ///Sets the target node to \c _t.
534 ///Sets the target node to \c _t.
536 void target(Node _t) {
538 if ( flow_prop == GEN_FLOW ) flow_prop=PRE_FLOW;
539 status=AFTER_NOTHING;
542 ///Returns the target node.
544 ///Returns the target node.
546 Node target() const {
550 /// Sets the edge map of the capacities to _cap.
552 /// Sets the edge map of the capacities to _cap.
554 void capacityMap(const CapacityMap& _cap) {
556 status=AFTER_NOTHING;
558 /// Returns a reference to capacity map.
560 /// Returns a reference to capacity map.
562 const CapacityMap &capacityMap() const {
566 /// Sets the edge map of the flows to _flow.
568 /// Sets the edge map of the flows to _flow.
570 void flowMap(FlowMap& _f) {
573 status=AFTER_NOTHING;
576 /// Returns a reference to flow map.
578 /// Returns a reference to flow map.
580 const FlowMap &flowMap() const {
586 int push(Node w, NNMap& next, VecNode& first) {
590 int newlevel=_node_num; //bound on the next level of w
592 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
593 if ( !_surely.positive((*_capacity)[e] - (*_flow)[e])) continue;
594 Node v=_g->target(e);
596 if( lev > level[v] ) { //Push is allowed now
598 if ( excess[v] == 0 && v!=_target && v!=_source ) {
599 next.set(v,first[level[v]]);
603 Num cap=(*_capacity)[e];
607 if ( ! _surely.less(remcap, exc) ) { //A nonsaturating push.
609 _flow->set(e, flo+exc);
610 excess.set(v, excess[v]+exc);
614 } else { //A saturating push.
616 excess.set(v, excess[v]+remcap);
619 } else if ( newlevel > level[v] ) newlevel = level[v];
623 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
625 if ( !_surely.positive((*_flow)[e]) ) continue;
626 Node v=_g->source(e);
628 if( lev > level[v] ) { //Push is allowed now
630 if ( excess[v] == 0 && v!=_target && v!=_source ) {
631 next.set(v,first[level[v]]);
637 if ( !_surely.less(flo, exc) ) { //A nonsaturating push.
639 _flow->set(e, flo-exc);
640 excess.set(v, excess[v]+exc);
643 } else { //A saturating push.
645 excess.set(v, excess[v]+flo);
649 } else if ( newlevel > level[v] ) newlevel = level[v];
652 } // if w still has excess after the out edge for cycle
661 void preflowPreproc(VecNode& first, NNMap& next,
662 VecNode& level_list, NNMap& left, NNMap& right)
664 for(NodeIt v(*_g); v!=INVALID; ++v) level.set(v,_node_num);
665 std::queue<Node> bfs_queue;
667 if ( flow_prop == GEN_FLOW || flow_prop == PRE_FLOW ) {
668 //Reverse_bfs from t in the residual graph,
669 //to find the starting level.
670 level.set(_target,0);
671 bfs_queue.push(_target);
673 while ( !bfs_queue.empty() ) {
675 Node v=bfs_queue.front();
679 for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
680 if ( !_surely.positive((*_capacity)[e] - (*_flow)[e] )) continue;
681 Node w=_g->source(e);
682 if ( level[w] == _node_num && w != _source ) {
684 Node z=level_list[l];
685 if ( z!=INVALID ) left.set(z,w);
692 for(OutEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
693 if ( !_surely.positive((*_flow)[e]) ) continue;
694 Node w=_g->target(e);
695 if ( level[w] == _node_num && w != _source ) {
697 Node z=level_list[l];
698 if ( z!=INVALID ) left.set(z,w);
710 for(EdgeIt e(*_g); e!=INVALID; ++e) _flow->set(e,0);
712 for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
714 //Reverse_bfs from t, to find the starting level.
715 level.set(_target,0);
716 bfs_queue.push(_target);
718 while ( !bfs_queue.empty() ) {
720 Node v=bfs_queue.front();
724 for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
725 Node w=_g->source(e);
726 if ( level[w] == _node_num && w != _source ) {
728 Node z=level_list[l];
729 if ( z!=INVALID ) left.set(z,w);
738 for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
739 Num c=(*_capacity)[e];
740 if ( !_surely.positive(c) ) continue;
741 Node w=_g->target(e);
742 if ( level[w] < _node_num ) {
743 if ( excess[w] == 0 && w!=_target ) { //putting into the stack
744 next.set(w,first[level[w]]);
748 excess.set(w, excess[w]+c);
754 for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
757 for(InEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc+=(*_flow)[e];
758 for(OutEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc-=(*_flow)[e];
759 if (!_surely.positive(exc)) {
762 excess.set(_target,exc);
766 for(OutEdgeIt e(*_g,_source); e!=INVALID; ++e) {
767 Num rem=(*_capacity)[e]-(*_flow)[e];
768 if ( !_surely.positive(rem) ) continue;
769 Node w=_g->target(e);
770 if ( level[w] < _node_num ) {
771 if ( excess[w] == 0 && w!=_target ) { //putting into the stack
772 next.set(w,first[level[w]]);
775 _flow->set(e, (*_capacity)[e]);
776 excess.set(w, excess[w]+rem);
780 for(InEdgeIt e(*_g,_source); e!=INVALID; ++e) {
781 if ( !_surely.positive((*_flow)[e]) ) continue;
782 Node w=_g->source(e);
783 if ( level[w] < _node_num ) {
784 if ( excess[w] == 0 && w!=_target ) {
785 next.set(w,first[level[w]]);
788 excess.set(w, excess[w]+(*_flow)[e]);
796 for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
797 Num rem=(*_capacity)[e]-(*_flow)[e];
798 if ( !_surely.positive(rem) ) continue;
799 Node w=_g->target(e);
800 if ( level[w] < _node_num ) _flow->set(e, (*_capacity)[e]);
803 for(InEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
804 if ( !_surely.positive((*_flow)[e]) ) continue;
805 Node w=_g->source(e);
806 if ( level[w] < _node_num ) _flow->set(e, 0);
809 //computing the excess
810 for(NodeIt w(*_g); w!=INVALID; ++w) {
812 for(InEdgeIt e(*_g,w); e!=INVALID; ++e) exc+=(*_flow)[e];
813 for(OutEdgeIt e(*_g,w); e!=INVALID; ++e) exc-=(*_flow)[e];
814 if (!_surely.positive(exc)) {
819 //putting the active nodes into the stack
821 if ( exc != 0 && lev < _node_num && Node(w) != _target ) {
822 next.set(w,first[lev]);
831 void relabel(Node w, int newlevel, VecNode& first, NNMap& next,
832 VecNode& level_list, NNMap& left,
833 NNMap& right, int& b, int& k, bool what_heur )
838 Node right_n=right[w];
842 if ( right_n!=INVALID ) {
843 if ( left_n!=INVALID ) {
844 right.set(left_n, right_n);
845 left.set(right_n, left_n);
847 level_list[lev]=right_n;
848 left.set(right_n, INVALID);
851 if ( left_n!=INVALID ) {
852 right.set(left_n, INVALID);
854 level_list[lev]=INVALID;
859 if ( level_list[lev]==INVALID ) {
862 for (int i=lev; i!=k ; ) {
863 Node v=level_list[++i];
864 while ( v!=INVALID ) {
865 level.set(v,_node_num);
868 level_list[i]=INVALID;
869 if ( !what_heur ) first[i]=INVALID;
872 level.set(w,_node_num);
879 if ( newlevel == _node_num ) level.set(w,_node_num);
881 level.set(w,++newlevel);
882 next.set(w,first[newlevel]);
884 if ( what_heur ) b=newlevel;
885 if ( k < newlevel ) ++k; //now k=newlevel
886 Node z=level_list[newlevel];
887 if ( z!=INVALID ) left.set(z,w);
890 level_list[newlevel]=w;
898 ///\brief Function type interface for Preflow algorithm.
900 ///Function type interface for Preflow algorithm.
902 template<class GR, class CM, class FM>
903 Preflow<GR,typename CM::Value,CM,FM> preflow(const GR &g,
904 typename GR::Node source,
905 typename GR::Node target,
910 return Preflow<GR,typename CM::Value,CM,FM>(g,source,target,cap,flow);
915 #endif //LEMON_PREFLOW_H