Fight with Doxygen.
Victory hasn't been reached yet, but it's on the horizon.
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 ///Except the graph, all of these parameters can be reset by
156 ///calling \ref source, \ref target, \ref capacityMap and \ref
158 Preflow(const Graph& _gr, Node _s, Node _t,
159 const CapacityMap& _cap, FlowMap& _f,
160 const TOL &tol=TOL()) :
161 _g(&_gr), _source(_s), _target(_t), _capacity(&_cap),
162 _flow(&_f), surely(tol),
163 _node_num(countNodes(_gr)), level(_gr), excess(_gr,0),
164 flow_prop(NO_FLOW), status(AFTER_NOTHING) {
165 if ( _source==_target )
166 throw InvalidArgument();
169 ///Give a reference to the tolerance handler class
171 ///Give a reference to the tolerance handler class
173 TOL &tolerance() { return surely; }
175 ///Runs the preflow algorithm.
177 ///Runs the preflow algorithm.
184 ///Runs the preflow algorithm.
186 ///Runs the preflow algorithm.
187 ///\pre The starting flow map must be
188 /// - a constant zero flow if \c fp is \c ZERO_FLOW,
189 /// - an arbitrary flow if \c fp is \c GEN_FLOW,
190 /// - an arbitrary preflow if \c fp is \c PRE_FLOW,
191 /// - any map if \c fp is NO_FLOW.
192 ///If the starting flow map is a flow or a preflow then
193 ///the algorithm terminates faster.
194 void run(FlowEnum fp) {
199 ///Runs the first phase of the preflow algorithm.
201 ///The preflow algorithm consists of two phases, this method runs
202 ///the first phase. After the first phase the maximum flow value
203 ///and a minimum value cut can already be computed, although a
204 ///maximum flow is not yet obtained. So after calling this method
205 ///\ref flowValue returns the value of a maximum flow and \ref
206 ///minCut returns a minimum cut.
207 ///\warning \ref minMinCut and \ref maxMinCut do not give minimum
208 ///value cuts unless calling \ref phase2.
209 ///\pre The starting flow must be
210 ///- a constant zero flow if \c fp is \c ZERO_FLOW,
211 ///- an arbitary flow if \c fp is \c GEN_FLOW,
212 ///- an arbitary preflow if \c fp is \c PRE_FLOW,
213 ///- any map if \c fp is NO_FLOW.
214 void phase1(FlowEnum fp)
221 ///Runs the first phase of the preflow algorithm.
223 ///The preflow algorithm consists of two phases, this method runs
224 ///the first phase. After the first phase the maximum flow value
225 ///and a minimum value cut can already be computed, although a
226 ///maximum flow is not yet obtained. So after calling this method
227 ///\ref flowValue returns the value of a maximum flow and \ref
228 ///minCut returns a minimum cut.
229 ///\warning \ref minMinCut() and \ref maxMinCut() do not
230 ///give minimum value cuts unless calling \ref phase2().
233 int heur0=(int)(H0*_node_num); //time while running 'bound decrease'
234 int heur1=(int)(H1*_node_num); //time while running 'highest label'
235 int heur=heur1; //starting time interval (#of relabels)
239 //It is 0 in case 'bound decrease' and 1 in case 'highest label'
242 //Needed for 'bound decrease', true means no active
243 //nodes are above bound b.
245 int k=_node_num-2; //bound on the highest level under n containing a node
246 int b=k; //bound on the highest level under n of an active node
248 VecNode first(_node_num, INVALID);
249 NNMap next(*_g, INVALID);
251 NNMap left(*_g, INVALID);
252 NNMap right(*_g, INVALID);
253 VecNode level_list(_node_num,INVALID);
254 //List of the nodes in level i<n, set to n.
256 preflowPreproc(first, next, level_list, left, right);
258 //Push/relabel on the highest level active nodes.
261 if ( !what_heur && !end && k > 0 ) {
267 if ( first[b]==INVALID ) --b;
272 int newlevel=push(w, next, first);
273 if ( excess[w] > 0 ) relabel(w, newlevel, first, next, level_list,
274 left, right, b, k, what_heur);
277 if ( numrelabel >= heur ) {
292 status=AFTER_PREFLOW_PHASE_1;
297 // list 'level_list' on the nodes on level i implemented by hand
298 // stack 'active' on the active nodes on level i
299 // runs heuristic 'highest label' for H1*n relabels
300 // runs heuristic 'bound decrease' for H0*n relabels,
301 // starts with 'highest label'
302 // Parameters H0 and H1 are initialized to 20 and 1.
305 ///Runs the second phase of the preflow algorithm.
307 ///The preflow algorithm consists of two phases, this method runs
308 ///the second phase. After calling \ref phase1() and then
310 /// \ref flowMap() return a maximum flow, \ref flowValue
311 ///returns the value of a maximum flow, \ref minCut returns a
312 ///minimum cut, while the methods \ref minMinCut and \ref
313 ///maxMinCut return the inclusionwise minimum and maximum cuts of
314 ///minimum value, resp. \pre \ref phase1 must be called before.
318 int k=_node_num-2; //bound on the highest level under n containing a node
319 int b=k; //bound on the highest level under n of an active node
322 VecNode first(_node_num, INVALID);
323 NNMap next(*_g, INVALID);
324 level.set(_source,0);
325 std::queue<Node> bfs_queue;
326 bfs_queue.push(_source);
328 while ( !bfs_queue.empty() ) {
330 Node v=bfs_queue.front();
334 for(InEdgeIt e(*_g,v); e!=INVALID; ++e) {
335 if ( (*_capacity)[e] <= (*_flow)[e] ) continue;
336 Node u=_g->source(e);
337 if ( level[u] >= _node_num ) {
340 if ( excess[u] > 0 ) {
341 next.set(u,first[l]);
347 for(OutEdgeIt e(*_g,v); e!=INVALID; ++e) {
348 if ( 0 >= (*_flow)[e] ) continue;
349 Node u=_g->target(e);
350 if ( level[u] >= _node_num ) {
353 if ( excess[u] > 0 ) {
354 next.set(u,first[l]);
365 if ( first[b]==INVALID ) --b;
369 int newlevel=push(w,next, first);
372 if ( excess[w] > 0 ) {
373 level.set(w,++newlevel);
374 next.set(w,first[newlevel]);
381 status=AFTER_PREFLOW_PHASE_2;
384 /// Returns the value of the maximum flow.
386 /// Returns the value of the maximum flow by returning the excess
387 /// of the target node \c t. This value equals to the value of
388 /// the maximum flow already after running \ref phase1.
389 Num flowValue() const {
390 return excess[_target];
394 ///Returns a minimum value cut.
396 ///Sets \c M to the characteristic vector of a minimum value
397 ///cut. This method can be called both after running \ref
398 ///phase1 and \ref phase2. It is much faster after
399 ///\ref phase1. \pre M should be a bool-valued node-map. \pre
400 ///If \ref minCut() is called after \ref phase2() then M should
401 ///be initialized to false.
402 template<typename _CutMap>
403 void minCut(_CutMap& M) const {
405 case AFTER_PREFLOW_PHASE_1:
406 for(NodeIt v(*_g); v!=INVALID; ++v) {
407 if (level[v] < _node_num) {
414 case AFTER_PREFLOW_PHASE_2:
422 ///Returns the inclusionwise minimum of the minimum value cuts.
424 ///Sets \c M to the characteristic vector of the minimum value cut
425 ///which is inclusionwise minimum. It is computed by processing a
426 ///bfs from the source node \c s in the residual graph. \pre M
427 ///should be a node map of bools initialized to false. \pre \ref
428 ///phase2 should already be run.
429 template<typename _CutMap>
430 void minMinCut(_CutMap& M) const {
432 std::queue<Node> queue;
436 while (!queue.empty()) {
437 Node w=queue.front();
440 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
441 Node v=_g->target(e);
442 if (!M[v] && (*_flow)[e] < (*_capacity)[e] ) {
448 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
449 Node v=_g->source(e);
450 if (!M[v] && (*_flow)[e] > 0 ) {
458 ///Returns the inclusionwise maximum of the minimum value cuts.
460 ///Sets \c M to the characteristic vector of the minimum value cut
461 ///which is inclusionwise maximum. It is computed by processing a
462 ///backward bfs from the target node \c t in the residual graph.
463 ///\pre \ref phase2() or run() should already be run.
464 template<typename _CutMap>
465 void maxMinCut(_CutMap& M) const {
467 for(NodeIt v(*_g) ; v!=INVALID; ++v) M.set(v, true);
469 std::queue<Node> queue;
471 M.set(_target,false);
474 while (!queue.empty()) {
475 Node w=queue.front();
478 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
479 Node v=_g->source(e);
480 if (M[v] && (*_flow)[e] < (*_capacity)[e] ) {
486 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
487 Node v=_g->target(e);
488 if (M[v] && (*_flow)[e] > 0 ) {
496 ///Sets the source node to \c _s.
498 ///Sets the source node to \c _s.
500 void source(Node _s) {
502 if ( flow_prop != ZERO_FLOW ) flow_prop=NO_FLOW;
503 status=AFTER_NOTHING;
506 ///Returns the source node.
508 ///Returns the source node.
510 Node source() const {
514 ///Sets the target node to \c _t.
516 ///Sets the target node to \c _t.
518 void target(Node _t) {
520 if ( flow_prop == GEN_FLOW ) flow_prop=PRE_FLOW;
521 status=AFTER_NOTHING;
524 ///Returns the target node.
526 ///Returns the target node.
528 Node target() const {
532 /// Sets the edge map of the capacities to _cap.
534 /// Sets the edge map of the capacities to _cap.
536 void capacityMap(const CapacityMap& _cap) {
538 status=AFTER_NOTHING;
540 /// Returns a reference to capacity map.
542 /// Returns a reference to capacity map.
544 const CapacityMap &capacityMap() const {
548 /// Sets the edge map of the flows to _flow.
550 /// Sets the edge map of the flows to _flow.
552 void flowMap(FlowMap& _f) {
555 status=AFTER_NOTHING;
558 /// Returns a reference to flow map.
560 /// Returns a reference to flow map.
562 const FlowMap &flowMap() const {
568 int push(Node w, NNMap& next, VecNode& first) {
572 int newlevel=_node_num; //bound on the next level of w
574 for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
575 if ( (*_flow)[e] >= (*_capacity)[e] ) continue;
576 Node v=_g->target(e);
578 if( lev > level[v] ) { //Push is allowed now
580 if ( excess[v]<=0 && v!=_target && v!=_source ) {
581 next.set(v,first[level[v]]);
585 Num cap=(*_capacity)[e];
589 if ( remcap >= exc ) { //A nonsaturating push.
591 _flow->set(e, flo+exc);
592 excess.set(v, excess[v]+exc);
596 } else { //A saturating push.
598 excess.set(v, excess[v]+remcap);
601 } else if ( newlevel > level[v] ) newlevel = level[v];
605 for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
607 if( (*_flow)[e] <= 0 ) continue;
608 Node v=_g->source(e);
610 if( lev > level[v] ) { //Push is allowed now
612 if ( excess[v]<=0 && v!=_target && v!=_source ) {
613 next.set(v,first[level[v]]);
619 if ( flo >= exc ) { //A nonsaturating push.
621 _flow->set(e, flo-exc);
622 excess.set(v, excess[v]+exc);
625 } else { //A saturating push.
627 excess.set(v, excess[v]+flo);
631 } else if ( newlevel > level[v] ) newlevel = level[v];
634 } // if w still has excess after the out edge for cycle
643 void preflowPreproc(VecNode& first, NNMap& next,
644 VecNode& level_list, NNMap& left, NNMap& right)
646 for(NodeIt v(*_g); v!=INVALID; ++v) level.set(v,_node_num);
647 std::queue<Node> bfs_queue;
649 if ( flow_prop == GEN_FLOW || flow_prop == PRE_FLOW ) {
650 //Reverse_bfs from t in the residual graph,
651 //to find the starting level.
652 level.set(_target,0);
653 bfs_queue.push(_target);
655 while ( !bfs_queue.empty() ) {
657 Node v=bfs_queue.front();
661 for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
662 if ( (*_capacity)[e] <= (*_flow)[e] ) continue;
663 Node w=_g->source(e);
664 if ( level[w] == _node_num && w != _source ) {
666 Node z=level_list[l];
667 if ( z!=INVALID ) left.set(z,w);
674 for(OutEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
675 if ( 0 >= (*_flow)[e] ) continue;
676 Node w=_g->target(e);
677 if ( level[w] == _node_num && w != _source ) {
679 Node z=level_list[l];
680 if ( z!=INVALID ) left.set(z,w);
692 for(EdgeIt e(*_g); e!=INVALID; ++e) _flow->set(e,0);
694 for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
696 //Reverse_bfs from t, to find the starting level.
697 level.set(_target,0);
698 bfs_queue.push(_target);
700 while ( !bfs_queue.empty() ) {
702 Node v=bfs_queue.front();
706 for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
707 Node w=_g->source(e);
708 if ( level[w] == _node_num && w != _source ) {
710 Node z=level_list[l];
711 if ( z!=INVALID ) left.set(z,w);
720 for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
721 Num c=(*_capacity)[e];
722 if ( c <= 0 ) continue;
723 Node w=_g->target(e);
724 if ( level[w] < _node_num ) {
725 if ( excess[w] <= 0 && w!=_target ) { //putting into the stack
726 next.set(w,first[level[w]]);
730 excess.set(w, excess[w]+c);
736 for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
739 for(InEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc+=(*_flow)[e];
740 for(OutEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc-=(*_flow)[e];
741 excess.set(_target,exc);
745 for(OutEdgeIt e(*_g,_source); e!=INVALID; ++e) {
746 Num rem=(*_capacity)[e]-(*_flow)[e];
747 if ( rem <= 0 ) continue;
748 Node w=_g->target(e);
749 if ( level[w] < _node_num ) {
750 if ( excess[w] <= 0 && w!=_target ) { //putting into the stack
751 next.set(w,first[level[w]]);
754 _flow->set(e, (*_capacity)[e]);
755 excess.set(w, excess[w]+rem);
759 for(InEdgeIt e(*_g,_source); e!=INVALID; ++e) {
760 if ( (*_flow)[e] <= 0 ) continue;
761 Node w=_g->source(e);
762 if ( level[w] < _node_num ) {
763 if ( excess[w] <= 0 && w!=_target ) {
764 next.set(w,first[level[w]]);
767 excess.set(w, excess[w]+(*_flow)[e]);
775 for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
776 Num rem=(*_capacity)[e]-(*_flow)[e];
777 if ( rem <= 0 ) continue;
778 Node w=_g->target(e);
779 if ( level[w] < _node_num ) _flow->set(e, (*_capacity)[e]);
782 for(InEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
783 if ( (*_flow)[e] <= 0 ) continue;
784 Node w=_g->source(e);
785 if ( level[w] < _node_num ) _flow->set(e, 0);
788 //computing the excess
789 for(NodeIt w(*_g); w!=INVALID; ++w) {
791 for(InEdgeIt e(*_g,w); e!=INVALID; ++e) exc+=(*_flow)[e];
792 for(OutEdgeIt e(*_g,w); e!=INVALID; ++e) exc-=(*_flow)[e];
795 //putting the active nodes into the stack
797 if ( exc > 0 && lev < _node_num && Node(w) != _target ) {
798 next.set(w,first[lev]);
807 void relabel(Node w, int newlevel, VecNode& first, NNMap& next,
808 VecNode& level_list, NNMap& left,
809 NNMap& right, int& b, int& k, bool what_heur )
814 Node right_n=right[w];
818 if ( right_n!=INVALID ) {
819 if ( left_n!=INVALID ) {
820 right.set(left_n, right_n);
821 left.set(right_n, left_n);
823 level_list[lev]=right_n;
824 left.set(right_n, INVALID);
827 if ( left_n!=INVALID ) {
828 right.set(left_n, INVALID);
830 level_list[lev]=INVALID;
835 if ( level_list[lev]==INVALID ) {
838 for (int i=lev; i!=k ; ) {
839 Node v=level_list[++i];
840 while ( v!=INVALID ) {
841 level.set(v,_node_num);
844 level_list[i]=INVALID;
845 if ( !what_heur ) first[i]=INVALID;
848 level.set(w,_node_num);
855 if ( newlevel == _node_num ) level.set(w,_node_num);
857 level.set(w,++newlevel);
858 next.set(w,first[newlevel]);
860 if ( what_heur ) b=newlevel;
861 if ( k < newlevel ) ++k; //now k=newlevel
862 Node z=level_list[newlevel];
863 if ( z!=INVALID ) left.set(z,w);
866 level_list[newlevel]=w;
874 ///\brief Function type interface for Preflow algorithm.
876 ///Function type interface for Preflow algorithm.
878 template<class GR, class CM, class FM>
879 Preflow<GR,typename CM::Value,CM,FM> preflow(const GR &g,
880 typename GR::Node source,
881 typename GR::Node target,
886 return Preflow<GR,typename CM::Value,CM,FM>(g,source,target,cap,flow);
891 #endif //LEMON_PREFLOW_H