Minor change.
2 * lemon/preflow.h - Part of LEMON, a generic C++ optimization library
4 * Copyright (C) 2006 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Research Group on Combinatorial Optimization, 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/error.h>
24 #include <lemon/invalid.h>
25 #include <lemon/tolerance.h>
26 #include <lemon/maps.h>
27 #include <lemon/graph_utils.h>
31 /// \brief Implementation of the preflow algorithm.
36 ///\brief %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 capacityMap 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 ///\todo Second template parameter is superfluous
63 template <typename Graph, typename Num,
64 typename CapacityMap=typename Graph::template EdgeMap<Num>,
65 typename FlowMap=typename Graph::template EdgeMap<Num>,
66 typename TOL=Tolerance<Num> >
69 typedef typename Graph::Node Node;
70 typedef typename Graph::NodeIt NodeIt;
71 typedef typename Graph::EdgeIt EdgeIt;
72 typedef typename Graph::OutEdgeIt OutEdgeIt;
73 typedef typename Graph::InEdgeIt InEdgeIt;
75 typedef typename Graph::template NodeMap<Node> NNMap;
76 typedef typename std::vector<Node> VecNode;
81 const CapacityMap* _capacity;
86 int _node_num; //the number of nodes of G
88 typename Graph::template NodeMap<int> level;
89 typename Graph::template NodeMap<Num> excess;
91 // constants used for heuristics
92 static const int H0=20;
93 static const int H1=1;
97 ///\ref Exception for the case when s=t.
99 ///\ref Exception for the case when the source equals the target.
100 class InvalidArgument : public lemon::LogicError {
102 virtual const char* exceptionName() const {
103 return "lemon::Preflow::InvalidArgument";
108 ///Indicates the property of the starting flow map.
110 ///Indicates the property of the starting flow map.
113 ///indicates an unspecified edge map. \c flow will be
114 ///set to the constant zero flow in the beginning of
115 ///the algorithm in this case.
117 ///constant zero flow
119 ///any flow, i.e. the sum of the in-flows equals to
120 ///the sum of the out-flows in every node except the \c source and
123 ///any preflow, i.e. the sum of the in-flows is at
124 ///least the sum of the out-flows in every node except the \c source.
128 ///Indicates the state of the preflow algorithm.
130 ///Indicates the state of the preflow algorithm.
133 ///before running the algorithm or
134 ///at an unspecified state.
136 ///right after running \ref phase1()
137 AFTER_PREFLOW_PHASE_1,
138 ///after running \ref phase2()
139 AFTER_PREFLOW_PHASE_2
144 StatusEnum status; // Do not needle this flag only if necessary.
147 ///The constructor of the class.
149 ///The constructor of the class.
150 ///\param _gr The directed graph the algorithm runs on.
151 ///\param _s The source node.
152 ///\param _t The target node.
153 ///\param _cap The capacity of the edges.
154 ///\param _f The flow of the edges.
155 ///\param tol Tolerance class.
156 ///Except the graph, all of these parameters can be reset by
157 ///calling \ref source, \ref target, \ref capacityMap and \ref
159 Preflow(const Graph& _gr, Node _s, Node _t,
160 const CapacityMap& _cap, FlowMap& _f,
161 const TOL &tol=TOL()) :
162 _g(&_gr), _source(_s), _target(_t), _capacity(&_cap),
163 _flow(&_f), surely(tol),
164 _node_num(countNodes(_gr)), level(_gr), excess(_gr,0),
165 flow_prop(NO_FLOW), status(AFTER_NOTHING) {
166 if ( _source==_target )
167 throw InvalidArgument();
170 ///Give a reference to the tolerance handler class
172 ///Give a reference to the tolerance handler class
174 TOL &tolerance() { return surely; }
176 ///Runs the preflow algorithm.
178 ///Runs the preflow algorithm.
185 ///Runs the preflow algorithm.
187 ///Runs the preflow algorithm.
188 ///\pre The starting flow map must be
189 /// - a constant zero flow if \c fp is \c ZERO_FLOW,
190 /// - an arbitrary flow if \c fp is \c GEN_FLOW,
191 /// - an arbitrary preflow if \c fp is \c PRE_FLOW,
192 /// - any map if \c fp is NO_FLOW.
193 ///If the starting flow map is a flow or a preflow then
194 ///the algorithm terminates faster.
195 void run(FlowEnum fp) {
200 ///Runs the first phase of the preflow algorithm.
202 ///The preflow algorithm consists of two phases, this method runs
203 ///the first phase. After the first phase the maximum flow value
204 ///and a minimum value cut can already be computed, although a
205 ///maximum flow is not yet obtained. So after calling this method
206 ///\ref flowValue returns the value of a maximum flow and \ref
207 ///minCut returns a minimum cut.
208 ///\warning \ref minMinCut and \ref maxMinCut do not give minimum
209 ///value cuts unless calling \ref phase2.
210 ///\pre The starting flow must be
211 ///- a constant zero flow if \c fp is \c ZERO_FLOW,
212 ///- an arbitary flow if \c fp is \c GEN_FLOW,
213 ///- an arbitary preflow if \c fp is \c PRE_FLOW,
214 ///- any map if \c fp is NO_FLOW.
215 void phase1(FlowEnum fp)
222 ///Runs the first phase of the preflow algorithm.
224 ///The preflow algorithm consists of two phases, this method runs
225 ///the first phase. After the first phase the maximum flow value
226 ///and a minimum value cut can already be computed, although a
227 ///maximum flow is not yet obtained. So after calling this method
228 ///\ref flowValue returns the value of a maximum flow and \ref
229 ///minCut returns a minimum cut.
230 ///\warning \ref minMinCut() and \ref maxMinCut() do not
231 ///give minimum value cuts unless calling \ref phase2().
234 int heur0=(int)(H0*_node_num); //time while running 'bound decrease'
235 int heur1=(int)(H1*_node_num); //time while running 'highest label'
236 int heur=heur1; //starting time interval (#of relabels)
240 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
243 //Needed for 'bound decrease', true means no active
244 //nodes are above bound b.
246 int k=_node_num-2; //bound on the highest level under n containing a node
247 int b=k; //bound on the highest level under n of an active node
249 VecNode first(_node_num, INVALID);
250 NNMap next(*_g, INVALID);
252 NNMap left(*_g, INVALID);
253 NNMap right(*_g, INVALID);
254 VecNode level_list(_node_num,INVALID);
255 //List of the nodes in level i<n, set to n.
257 preflowPreproc(first, next, level_list, left, right);
259 //Push/relabel on the highest level active nodes.
262 if ( !what_heur && !end && k > 0 ) {
268 if ( first[b]==INVALID ) --b;
273 int newlevel=push(w, next, first);
274 if ( excess[w] > 0 ) relabel(w, newlevel, first, next, level_list,
275 left, right, b, k, what_heur);
278 if ( numrelabel >= heur ) {
293 status=AFTER_PREFLOW_PHASE_1;
298 // list 'level_list' on the nodes on level i implemented by hand
299 // stack 'active' on the active nodes on level i
300 // runs heuristic 'highest label' for H1*n relabels
301 // runs heuristic 'bound decrease' for H0*n relabels,
302 // starts with 'highest label'
303 // Parameters H0 and H1 are initialized to 20 and 1.
306 ///Runs the second phase of the preflow algorithm.
308 ///The preflow algorithm consists of two phases, this method runs
309 ///the second phase. After calling \ref phase1() and then
311 /// \ref flowMap() return a maximum flow, \ref flowValue
312 ///returns the value of a maximum flow, \ref minCut returns a
313 ///minimum cut, while the methods \ref minMinCut and \ref
314 ///maxMinCut return the inclusionwise minimum and maximum cuts of
315 ///minimum value, resp. \pre \ref phase1 must be called before.
319 int k=_node_num-2; //bound on the highest level under n containing a node
320 int b=k; //bound on the highest level under n of an active node
323 VecNode first(_node_num, INVALID);
324 NNMap next(*_g, INVALID);
325 level.set(_source,0);
326 std::queue<Node> bfs_queue;
327 bfs_queue.push(_source);
329 while ( !bfs_queue.empty() ) {
331 Node v=bfs_queue.front();
335 for(InEdgeIt e(*_g,v); e!=INVALID; ++e) {
336 if ( (*_capacity)[e] <= (*_flow)[e] ) continue;
337 Node u=_g->source(e);
338 if ( level[u] >= _node_num ) {
341 if ( excess[u] > 0 ) {
342 next.set(u,first[l]);
348 for(OutEdgeIt e(*_g,v); e!=INVALID; ++e) {
349 if ( 0 >= (*_flow)[e] ) continue;
350 Node u=_g->target(e);
351 if ( level[u] >= _node_num ) {
354 if ( excess[u] > 0 ) {
355 next.set(u,first[l]);
366 if ( first[b]==INVALID ) --b;
370 int newlevel=push(w,next, first);
373 if ( excess[w] > 0 ) {
374 level.set(w,++newlevel);
375 next.set(w,first[newlevel]);
382 status=AFTER_PREFLOW_PHASE_2;
385 /// Returns the value of the maximum flow.
387 /// Returns the value of the maximum flow by returning the excess
388 /// of the target node \c t. This value equals to the value of
389 /// the maximum flow already after running \ref phase1.
390 Num flowValue() const {
391 return excess[_target];
395 ///Returns a minimum value cut.
397 ///Sets \c M to the characteristic vector of a minimum value
398 ///cut. This method can be called both after running \ref
399 ///phase1 and \ref phase2. It is much faster after
400 ///\ref phase1. \pre M should be a bool-valued node-map. \pre
401 ///If \ref minCut() is called after \ref phase2() then M should
402 ///be initialized to false.
403 template<typename _CutMap>
404 void minCut(_CutMap& M) const {
406 case AFTER_PREFLOW_PHASE_1:
407 for(NodeIt v(*_g); v!=INVALID; ++v) {
408 if (level[v] < _node_num) {
415 case AFTER_PREFLOW_PHASE_2:
423 ///Returns the inclusionwise minimum of the minimum value cuts.
425 ///Sets \c M to the characteristic vector of the minimum value cut
426 ///which is inclusionwise minimum. It is computed by processing a
427 ///bfs from the source node \c s in the residual graph. \pre M
428 ///should be a node map of bools initialized to false. \pre \ref
429 ///phase2 should already be run.
430 template<typename _CutMap>
431 void minMinCut(_CutMap& M) const {
433 std::queue<Node> queue;
437 while (!queue.empty()) {
438 Node w=queue.front();
441 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
442 Node v=_g->target(e);
443 if (!M[v] && (*_flow)[e] < (*_capacity)[e] ) {
449 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
450 Node v=_g->source(e);
451 if (!M[v] && (*_flow)[e] > 0 ) {
459 ///Returns the inclusionwise maximum of the minimum value cuts.
461 ///Sets \c M to the characteristic vector of the minimum value cut
462 ///which is inclusionwise maximum. It is computed by processing a
463 ///backward bfs from the target node \c t in the residual graph.
464 ///\pre \ref phase2() or run() should already be run.
465 template<typename _CutMap>
466 void maxMinCut(_CutMap& M) const {
468 for(NodeIt v(*_g) ; v!=INVALID; ++v) M.set(v, true);
470 std::queue<Node> queue;
472 M.set(_target,false);
475 while (!queue.empty()) {
476 Node w=queue.front();
479 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
480 Node v=_g->source(e);
481 if (M[v] && (*_flow)[e] < (*_capacity)[e] ) {
487 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
488 Node v=_g->target(e);
489 if (M[v] && (*_flow)[e] > 0 ) {
497 ///Sets the source node to \c _s.
499 ///Sets the source node to \c _s.
501 void source(Node _s) {
503 if ( flow_prop != ZERO_FLOW ) flow_prop=NO_FLOW;
504 status=AFTER_NOTHING;
507 ///Returns the source node.
509 ///Returns the source node.
511 Node source() const {
515 ///Sets the target node to \c _t.
517 ///Sets the target node to \c _t.
519 void target(Node _t) {
521 if ( flow_prop == GEN_FLOW ) flow_prop=PRE_FLOW;
522 status=AFTER_NOTHING;
525 ///Returns the target node.
527 ///Returns the target node.
529 Node target() const {
533 /// Sets the edge map of the capacities to _cap.
535 /// Sets the edge map of the capacities to _cap.
537 void capacityMap(const CapacityMap& _cap) {
539 status=AFTER_NOTHING;
541 /// Returns a reference to capacity map.
543 /// Returns a reference to capacity map.
545 const CapacityMap &capacityMap() const {
549 /// Sets the edge map of the flows to _flow.
551 /// Sets the edge map of the flows to _flow.
553 void flowMap(FlowMap& _f) {
556 status=AFTER_NOTHING;
559 /// Returns a reference to flow map.
561 /// Returns a reference to flow map.
563 const FlowMap &flowMap() const {
569 int push(Node w, NNMap& next, VecNode& first) {
573 int newlevel=_node_num; //bound on the next level of w
575 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
576 if ( (*_flow)[e] >= (*_capacity)[e] ) continue;
577 Node v=_g->target(e);
579 if( lev > level[v] ) { //Push is allowed now
581 if ( excess[v]<=0 && v!=_target && v!=_source ) {
582 next.set(v,first[level[v]]);
586 Num cap=(*_capacity)[e];
590 if ( remcap >= exc ) { //A nonsaturating push.
592 _flow->set(e, flo+exc);
593 excess.set(v, excess[v]+exc);
597 } else { //A saturating push.
599 excess.set(v, excess[v]+remcap);
602 } else if ( newlevel > level[v] ) newlevel = level[v];
606 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
608 if( (*_flow)[e] <= 0 ) continue;
609 Node v=_g->source(e);
611 if( lev > level[v] ) { //Push is allowed now
613 if ( excess[v]<=0 && v!=_target && v!=_source ) {
614 next.set(v,first[level[v]]);
620 if ( flo >= exc ) { //A nonsaturating push.
622 _flow->set(e, flo-exc);
623 excess.set(v, excess[v]+exc);
626 } else { //A saturating push.
628 excess.set(v, excess[v]+flo);
632 } else if ( newlevel > level[v] ) newlevel = level[v];
635 } // if w still has excess after the out edge for cycle
644 void preflowPreproc(VecNode& first, NNMap& next,
645 VecNode& level_list, NNMap& left, NNMap& right)
647 for(NodeIt v(*_g); v!=INVALID; ++v) level.set(v,_node_num);
648 std::queue<Node> bfs_queue;
650 if ( flow_prop == GEN_FLOW || flow_prop == PRE_FLOW ) {
651 //Reverse_bfs from t in the residual graph,
652 //to find the starting level.
653 level.set(_target,0);
654 bfs_queue.push(_target);
656 while ( !bfs_queue.empty() ) {
658 Node v=bfs_queue.front();
662 for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
663 if ( (*_capacity)[e] <= (*_flow)[e] ) continue;
664 Node w=_g->source(e);
665 if ( level[w] == _node_num && w != _source ) {
667 Node z=level_list[l];
668 if ( z!=INVALID ) left.set(z,w);
675 for(OutEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
676 if ( 0 >= (*_flow)[e] ) continue;
677 Node w=_g->target(e);
678 if ( level[w] == _node_num && w != _source ) {
680 Node z=level_list[l];
681 if ( z!=INVALID ) left.set(z,w);
693 for(EdgeIt e(*_g); e!=INVALID; ++e) _flow->set(e,0);
695 for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
697 //Reverse_bfs from t, to find the starting level.
698 level.set(_target,0);
699 bfs_queue.push(_target);
701 while ( !bfs_queue.empty() ) {
703 Node v=bfs_queue.front();
707 for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
708 Node w=_g->source(e);
709 if ( level[w] == _node_num && w != _source ) {
711 Node z=level_list[l];
712 if ( z!=INVALID ) left.set(z,w);
721 for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
722 Num c=(*_capacity)[e];
723 if ( c <= 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]]);
731 excess.set(w, excess[w]+c);
737 for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
740 for(InEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc+=(*_flow)[e];
741 for(OutEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc-=(*_flow)[e];
742 excess.set(_target,exc);
746 for(OutEdgeIt e(*_g,_source); e!=INVALID; ++e) {
747 Num rem=(*_capacity)[e]-(*_flow)[e];
748 if ( rem <= 0 ) continue;
749 Node w=_g->target(e);
750 if ( level[w] < _node_num ) {
751 if ( excess[w] <= 0 && w!=_target ) { //putting into the stack
752 next.set(w,first[level[w]]);
755 _flow->set(e, (*_capacity)[e]);
756 excess.set(w, excess[w]+rem);
760 for(InEdgeIt e(*_g,_source); e!=INVALID; ++e) {
761 if ( (*_flow)[e] <= 0 ) continue;
762 Node w=_g->source(e);
763 if ( level[w] < _node_num ) {
764 if ( excess[w] <= 0 && w!=_target ) {
765 next.set(w,first[level[w]]);
768 excess.set(w, excess[w]+(*_flow)[e]);
776 for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
777 Num rem=(*_capacity)[e]-(*_flow)[e];
778 if ( rem <= 0 ) continue;
779 Node w=_g->target(e);
780 if ( level[w] < _node_num ) _flow->set(e, (*_capacity)[e]);
783 for(InEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
784 if ( (*_flow)[e] <= 0 ) continue;
785 Node w=_g->source(e);
786 if ( level[w] < _node_num ) _flow->set(e, 0);
789 //computing the excess
790 for(NodeIt w(*_g); w!=INVALID; ++w) {
792 for(InEdgeIt e(*_g,w); e!=INVALID; ++e) exc+=(*_flow)[e];
793 for(OutEdgeIt e(*_g,w); e!=INVALID; ++e) exc-=(*_flow)[e];
796 //putting the active nodes into the stack
798 if ( exc > 0 && lev < _node_num && Node(w) != _target ) {
799 next.set(w,first[lev]);
808 void relabel(Node w, int newlevel, VecNode& first, NNMap& next,
809 VecNode& level_list, NNMap& left,
810 NNMap& right, int& b, int& k, bool what_heur )
815 Node right_n=right[w];
819 if ( right_n!=INVALID ) {
820 if ( left_n!=INVALID ) {
821 right.set(left_n, right_n);
822 left.set(right_n, left_n);
824 level_list[lev]=right_n;
825 left.set(right_n, INVALID);
828 if ( left_n!=INVALID ) {
829 right.set(left_n, INVALID);
831 level_list[lev]=INVALID;
836 if ( level_list[lev]==INVALID ) {
839 for (int i=lev; i!=k ; ) {
840 Node v=level_list[++i];
841 while ( v!=INVALID ) {
842 level.set(v,_node_num);
845 level_list[i]=INVALID;
846 if ( !what_heur ) first[i]=INVALID;
849 level.set(w,_node_num);
856 if ( newlevel == _node_num ) level.set(w,_node_num);
858 level.set(w,++newlevel);
859 next.set(w,first[newlevel]);
861 if ( what_heur ) b=newlevel;
862 if ( k < newlevel ) ++k; //now k=newlevel
863 Node z=level_list[newlevel];
864 if ( z!=INVALID ) left.set(z,w);
867 level_list[newlevel]=w;
875 ///\brief Function type interface for Preflow algorithm.
877 ///Function type interface for Preflow algorithm.
879 template<class GR, class CM, class FM>
880 Preflow<GR,typename CM::Value,CM,FM> preflow(const GR &g,
881 typename GR::Node source,
882 typename GR::Node target,
887 return Preflow<GR,typename CM::Value,CM,FM>(g,source,target,cap,flow);
892 #endif //LEMON_PREFLOW_H