lemon/preflow.h
author alpar
Fri, 03 Feb 2006 15:58:24 +0000
changeset 1953 d4f411003580
parent 1898 f030c01e6173
child 1956 a055123339d5
permissions -rw-r--r--
Polish the doc.
     1 /* -*- C++ -*-
     2  * lemon/preflow.h - Part of LEMON, a generic C++ optimization library
     3  *
     4  * Copyright (C) 2006 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     5  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     6  *
     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.
    10  *
    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
    13  * purpose.
    14  *
    15  */
    16 
    17 #ifndef LEMON_PREFLOW_H
    18 #define LEMON_PREFLOW_H
    19 
    20 #include <vector>
    21 #include <queue>
    22 
    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>
    28 
    29 /// \file
    30 /// \ingroup flowalgs
    31 /// \brief Implementation of the preflow algorithm.
    32 
    33 namespace lemon {
    34 
    35   ///\ingroup flowalgs
    36   ///\brief %Preflow algorithms class.
    37   ///
    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
    46   ///flowMap.
    47   ///
    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,
    54   ///resp.)
    55   ///
    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.
    60   ///
    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> >
    67   class Preflow {
    68   protected:
    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;
    74 
    75     typedef typename Graph::template NodeMap<Node> NNMap;
    76     typedef typename std::vector<Node> VecNode;
    77 
    78     const Graph* _g;
    79     Node _source;
    80     Node _target;
    81     const CapacityMap* _capacity;
    82     FlowMap* _flow;
    83 
    84     TOL surely;
    85     
    86     int _node_num;      //the number of nodes of G
    87     
    88     typename Graph::template NodeMap<int> level;  
    89     typename Graph::template NodeMap<Num> excess;
    90 
    91     // constants used for heuristics
    92     static const int H0=20;
    93     static const int H1=1;
    94 
    95   public:
    96 
    97     ///\ref Exception for the case when s=t.
    98 
    99     ///\ref Exception for the case when the source equals the target.
   100     class InvalidArgument : public lemon::LogicError {
   101     public:
   102       virtual const char* exceptionName() const {
   103 	return "lemon::Preflow::InvalidArgument";
   104       }
   105     };
   106     
   107     
   108     ///Indicates the property of the starting flow map.
   109     
   110     ///Indicates the property of the starting flow map.
   111     ///
   112     enum FlowEnum{
   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.
   116       NO_FLOW,
   117       ///constant zero flow
   118       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
   121       ///the \c target.
   122       GEN_FLOW,
   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.
   125       PRE_FLOW
   126     };
   127 
   128     ///Indicates the state of the preflow algorithm.
   129 
   130     ///Indicates the state of the preflow algorithm.
   131     ///
   132     enum StatusEnum {
   133       ///before running the algorithm or
   134       ///at an unspecified state.
   135       AFTER_NOTHING,
   136       ///right after running \ref phase1()
   137       AFTER_PREFLOW_PHASE_1,      
   138       ///after running \ref phase2()
   139       AFTER_PREFLOW_PHASE_2
   140     };
   141     
   142   protected: 
   143     FlowEnum flow_prop;
   144     StatusEnum status; // Do not needle this flag only if necessary.
   145     
   146   public: 
   147     ///The constructor of the class.
   148 
   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
   158     ///flowMap, resp.
   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();
   168       }
   169     
   170     ///Give a reference to the tolerance handler class
   171 
   172     ///Give a reference to the tolerance handler class
   173     ///\sa Tolerance
   174     TOL &tolerance() { return surely; }
   175 
   176     ///Runs the preflow algorithm.  
   177 
   178     ///Runs the preflow algorithm.
   179     ///
   180     void run() {
   181       phase1(flow_prop);
   182       phase2();
   183     }
   184     
   185     ///Runs the preflow algorithm.  
   186     
   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) {
   196       flow_prop=fp;
   197       run();
   198     }
   199       
   200     ///Runs the first phase of the preflow algorithm.
   201 
   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)
   216     {
   217       flow_prop=fp;
   218       phase1();
   219     }
   220 
   221     
   222     ///Runs the first phase of the preflow algorithm.
   223 
   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().
   232     void phase1()
   233     {
   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)
   237       int numrelabel=0;
   238 
   239       bool what_heur=1;
   240       //It is 0 in case 'bound decrease' and 1 in case 'highest label'
   241 
   242       bool end=false;
   243       //Needed for 'bound decrease', true means no active 
   244       //nodes are above bound b.
   245 
   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
   248 
   249       VecNode first(_node_num, INVALID);
   250       NNMap next(*_g, INVALID);
   251 
   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.
   256 
   257       preflowPreproc(first, next, level_list, left, right);
   258 
   259       //Push/relabel on the highest level active nodes.
   260       while ( true ) {
   261 	if ( b == 0 ) {
   262 	  if ( !what_heur && !end && k > 0 ) {
   263 	    b=k;
   264 	    end=true;
   265 	  } else break;
   266 	}
   267 
   268 	if ( first[b]==INVALID ) --b;
   269 	else {
   270 	  end=false;
   271 	  Node w=first[b];
   272 	  first[b]=next[w];
   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);
   276 
   277 	  ++numrelabel;
   278 	  if ( numrelabel >= heur ) {
   279 	    numrelabel=0;
   280 	    if ( what_heur ) {
   281 	      what_heur=0;
   282 	      heur=heur0;
   283 	      end=false;
   284 	    } else {
   285 	      what_heur=1;
   286 	      heur=heur1;
   287 	      b=k;
   288 	    }
   289 	  }
   290 	}
   291       }
   292       flow_prop=PRE_FLOW;
   293       status=AFTER_PREFLOW_PHASE_1;
   294     }
   295     // Heuristics:
   296     //   2 phase
   297     //   gap
   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.
   304 
   305 
   306     ///Runs the second phase of the preflow algorithm.
   307 
   308     ///The preflow algorithm consists of two phases, this method runs
   309     ///the second phase. After calling \ref phase1() and then
   310     ///\ref phase2(),
   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.
   316     void phase2()
   317     {
   318 
   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
   321 
   322     
   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);
   328 
   329       while ( !bfs_queue.empty() ) {
   330 
   331 	Node v=bfs_queue.front();
   332 	bfs_queue.pop();
   333 	int l=level[v]+1;
   334 
   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 ) {
   339 	    bfs_queue.push(u);
   340 	    level.set(u, l);
   341 	    if ( excess[u] > 0 ) {
   342 	      next.set(u,first[l]);
   343 	      first[l]=u;
   344 	    }
   345 	  }
   346 	}
   347 
   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 ) {
   352 	    bfs_queue.push(u);
   353 	    level.set(u, l);
   354 	    if ( excess[u] > 0 ) {
   355 	      next.set(u,first[l]);
   356 	      first[l]=u;
   357 	    }
   358 	  }
   359 	}
   360       }
   361       b=_node_num-2;
   362 
   363       while ( true ) {
   364 
   365 	if ( b == 0 ) break;
   366 	if ( first[b]==INVALID ) --b;
   367 	else {
   368 	  Node w=first[b];
   369 	  first[b]=next[w];
   370 	  int newlevel=push(w,next, first);
   371 	  
   372 	  //relabel
   373 	  if ( excess[w] > 0 ) {
   374 	    level.set(w,++newlevel);
   375 	    next.set(w,first[newlevel]);
   376 	    first[newlevel]=w;
   377 	    b=newlevel;
   378 	  }
   379 	} 
   380       } // while(true)
   381       flow_prop=GEN_FLOW;
   382       status=AFTER_PREFLOW_PHASE_2;
   383     }
   384 
   385     /// Returns the value of the maximum flow.
   386 
   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];
   392     }
   393 
   394 
   395     ///Returns a minimum value cut.
   396 
   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 {
   405       switch ( status ) {
   406 	case AFTER_PREFLOW_PHASE_1:
   407 	for(NodeIt v(*_g); v!=INVALID; ++v) {
   408 	  if (level[v] < _node_num) {
   409 	    M.set(v, false);
   410 	  } else {
   411 	    M.set(v, true);
   412 	  }
   413 	}
   414 	break;
   415 	case AFTER_PREFLOW_PHASE_2:
   416 	minMinCut(M);
   417 	break;
   418 	case AFTER_NOTHING:
   419 	break;
   420       }
   421     }
   422 
   423     ///Returns the inclusionwise minimum of the minimum value cuts.
   424 
   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 {
   432 
   433       std::queue<Node> queue;
   434       M.set(_source,true);
   435       queue.push(_source);
   436       
   437       while (!queue.empty()) {
   438 	Node w=queue.front();
   439 	queue.pop();
   440 	
   441 	for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   442 	  Node v=_g->target(e);
   443 	  if (!M[v] && (*_flow)[e] < (*_capacity)[e] ) {
   444 	    queue.push(v);
   445 	    M.set(v, true);
   446 	  }
   447 	}
   448 	
   449 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   450 	  Node v=_g->source(e);
   451 	  if (!M[v] && (*_flow)[e] > 0 ) {
   452 	    queue.push(v);
   453 	    M.set(v, true);
   454 	  }
   455 	}
   456       }
   457     }
   458     
   459     ///Returns the inclusionwise maximum of the minimum value cuts.
   460 
   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 {
   467 
   468       for(NodeIt v(*_g) ; v!=INVALID; ++v) M.set(v, true);
   469 
   470       std::queue<Node> queue;
   471 
   472       M.set(_target,false);
   473       queue.push(_target);
   474 
   475       while (!queue.empty()) {
   476         Node w=queue.front();
   477 	queue.pop();
   478 
   479 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   480 	  Node v=_g->source(e);
   481 	  if (M[v] && (*_flow)[e] < (*_capacity)[e] ) {
   482 	    queue.push(v);
   483 	    M.set(v, false);
   484 	  }
   485 	}
   486 
   487 	for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   488 	  Node v=_g->target(e);
   489 	  if (M[v] && (*_flow)[e] > 0 ) {
   490 	    queue.push(v);
   491 	    M.set(v, false);
   492 	  }
   493 	}
   494       }
   495     }
   496 
   497     ///Sets the source node to \c _s.
   498 
   499     ///Sets the source node to \c _s.
   500     /// 
   501     void source(Node _s) { 
   502       _source=_s; 
   503       if ( flow_prop != ZERO_FLOW ) flow_prop=NO_FLOW;
   504       status=AFTER_NOTHING; 
   505     }
   506 
   507     ///Returns the source node.
   508 
   509     ///Returns the source node.
   510     /// 
   511     Node source() const { 
   512       return _source;
   513     }
   514 
   515     ///Sets the target node to \c _t.
   516 
   517     ///Sets the target node to \c _t.
   518     ///
   519     void target(Node _t) { 
   520       _target=_t; 
   521       if ( flow_prop == GEN_FLOW ) flow_prop=PRE_FLOW;
   522       status=AFTER_NOTHING; 
   523     }
   524 
   525     ///Returns the target node.
   526 
   527     ///Returns the target node.
   528     /// 
   529     Node target() const { 
   530       return _target;
   531     }
   532 
   533     /// Sets the edge map of the capacities to _cap.
   534 
   535     /// Sets the edge map of the capacities to _cap.
   536     /// 
   537     void capacityMap(const CapacityMap& _cap) { 
   538       _capacity=&_cap; 
   539       status=AFTER_NOTHING; 
   540     }
   541     /// Returns a reference to capacity map.
   542 
   543     /// Returns a reference to capacity map.
   544     /// 
   545     const CapacityMap &capacityMap() const { 
   546       return *_capacity;
   547     }
   548 
   549     /// Sets the edge map of the flows to _flow.
   550 
   551     /// Sets the edge map of the flows to _flow.
   552     /// 
   553     void flowMap(FlowMap& _f) { 
   554       _flow=&_f; 
   555       flow_prop=NO_FLOW;
   556       status=AFTER_NOTHING; 
   557     }
   558      
   559     /// Returns a reference to flow map.
   560 
   561     /// Returns a reference to flow map.
   562     /// 
   563     const FlowMap &flowMap() const { 
   564       return *_flow;
   565     }
   566 
   567   private:
   568 
   569     int push(Node w, NNMap& next, VecNode& first) {
   570 
   571       int lev=level[w];
   572       Num exc=excess[w];
   573       int newlevel=_node_num;       //bound on the next level of w
   574 
   575       for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   576 	if ( (*_flow)[e] >= (*_capacity)[e] ) continue;
   577 	Node v=_g->target(e);
   578 
   579 	if( lev > level[v] ) { //Push is allowed now
   580 	  
   581 	  if ( excess[v]<=0 && v!=_target && v!=_source ) {
   582 	    next.set(v,first[level[v]]);
   583 	    first[level[v]]=v;
   584 	  }
   585 
   586 	  Num cap=(*_capacity)[e];
   587 	  Num flo=(*_flow)[e];
   588 	  Num remcap=cap-flo;
   589 	  
   590 	  if ( remcap >= exc ) { //A nonsaturating push.
   591 	    
   592 	    _flow->set(e, flo+exc);
   593 	    excess.set(v, excess[v]+exc);
   594 	    exc=0;
   595 	    break;
   596 
   597 	  } else { //A saturating push.
   598 	    _flow->set(e, cap);
   599 	    excess.set(v, excess[v]+remcap);
   600 	    exc-=remcap;
   601 	  }
   602 	} else if ( newlevel > level[v] ) newlevel = level[v];
   603       } //for out edges wv
   604 
   605       if ( exc > 0 ) {
   606 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   607 	  
   608 	  if( (*_flow)[e] <= 0 ) continue;
   609 	  Node v=_g->source(e);
   610 
   611 	  if( lev > level[v] ) { //Push is allowed now
   612 
   613 	    if ( excess[v]<=0 && v!=_target && v!=_source ) {
   614 	      next.set(v,first[level[v]]);
   615 	      first[level[v]]=v;
   616 	    }
   617 
   618 	    Num flo=(*_flow)[e];
   619 
   620 	    if ( flo >= exc ) { //A nonsaturating push.
   621 
   622 	      _flow->set(e, flo-exc);
   623 	      excess.set(v, excess[v]+exc);
   624 	      exc=0;
   625 	      break;
   626 	    } else {  //A saturating push.
   627 
   628 	      excess.set(v, excess[v]+flo);
   629 	      exc-=flo;
   630 	      _flow->set(e,0);
   631 	    }
   632 	  } else if ( newlevel > level[v] ) newlevel = level[v];
   633 	} //for in edges vw
   634 
   635       } // if w still has excess after the out edge for cycle
   636 
   637       excess.set(w, exc);
   638       
   639       return newlevel;
   640     }
   641     
   642     
   643     
   644     void preflowPreproc(VecNode& first, NNMap& next, 
   645 			VecNode& level_list, NNMap& left, NNMap& right)
   646     {
   647       for(NodeIt v(*_g); v!=INVALID; ++v) level.set(v,_node_num);
   648       std::queue<Node> bfs_queue;
   649       
   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);
   655 	
   656 	while ( !bfs_queue.empty() ) {
   657 	  
   658 	  Node v=bfs_queue.front();
   659 	  bfs_queue.pop();
   660 	  int l=level[v]+1;
   661 	  
   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 ) {
   666 	      bfs_queue.push(w);
   667 	      Node z=level_list[l];
   668 	      if ( z!=INVALID ) left.set(z,w);
   669 	      right.set(w,z);
   670 	      level_list[l]=w;
   671 	      level.set(w, l);
   672 	    }
   673 	  }
   674 	  
   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 ) {
   679 	      bfs_queue.push(w);
   680 	      Node z=level_list[l];
   681 	      if ( z!=INVALID ) left.set(z,w);
   682 	      right.set(w,z);
   683 	      level_list[l]=w;
   684 	      level.set(w, l);
   685 	    }
   686 	  }
   687 	} //while
   688       } //if
   689 
   690 
   691       switch (flow_prop) {
   692 	case NO_FLOW:  
   693 	for(EdgeIt e(*_g); e!=INVALID; ++e) _flow->set(e,0);
   694 	case ZERO_FLOW:
   695 	for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
   696 	
   697 	//Reverse_bfs from t, to find the starting level.
   698 	level.set(_target,0);
   699 	bfs_queue.push(_target);
   700 	
   701 	while ( !bfs_queue.empty() ) {
   702 	  
   703 	  Node v=bfs_queue.front();
   704 	  bfs_queue.pop();
   705 	  int l=level[v]+1;
   706 	  
   707 	  for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
   708 	    Node w=_g->source(e);
   709 	    if ( level[w] == _node_num && w != _source ) {
   710 	      bfs_queue.push(w);
   711 	      Node z=level_list[l];
   712 	      if ( z!=INVALID ) left.set(z,w);
   713 	      right.set(w,z);
   714 	      level_list[l]=w;
   715 	      level.set(w, l);
   716 	    }
   717 	  }
   718 	}
   719 	
   720 	//the starting flow
   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]]);
   728 	      first[level[w]]=w;
   729 	    }
   730 	    _flow->set(e, c);
   731 	    excess.set(w, excess[w]+c);
   732 	  }
   733 	}
   734 	break;
   735 
   736 	case GEN_FLOW:
   737 	for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
   738 	{
   739 	  Num exc=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);
   743 	}
   744 
   745 	//the starting flow
   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]]);
   753 	      first[level[w]]=w;
   754 	    }   
   755 	    _flow->set(e, (*_capacity)[e]);
   756 	    excess.set(w, excess[w]+rem);
   757 	  }
   758 	}
   759 	
   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]]);
   766 	      first[level[w]]=w;
   767 	    }  
   768 	    excess.set(w, excess[w]+(*_flow)[e]);
   769 	    _flow->set(e, 0);
   770 	  }
   771 	}
   772 	break;
   773 
   774 	case PRE_FLOW:	
   775 	//the starting flow
   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]);
   781 	}
   782 	
   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);
   787 	}
   788 	
   789 	//computing the excess
   790 	for(NodeIt w(*_g); w!=INVALID; ++w) {
   791 	  Num exc=0;
   792 	  for(InEdgeIt e(*_g,w); e!=INVALID; ++e) exc+=(*_flow)[e];
   793 	  for(OutEdgeIt e(*_g,w); e!=INVALID; ++e) exc-=(*_flow)[e];
   794 	  excess.set(w,exc);
   795 	  
   796 	  //putting the active nodes into the stack
   797 	  int lev=level[w];
   798 	    if ( exc > 0 && lev < _node_num && Node(w) != _target ) {
   799 	      next.set(w,first[lev]);
   800 	      first[lev]=w;
   801 	    }
   802 	}
   803 	break;
   804       } //switch
   805     } //preflowPreproc
   806 
   807 
   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 )
   811     {
   812 
   813       int lev=level[w];
   814 
   815       Node right_n=right[w];
   816       Node left_n=left[w];
   817 
   818       //unlacing starts
   819       if ( right_n!=INVALID ) {
   820 	if ( left_n!=INVALID ) {
   821 	  right.set(left_n, right_n);
   822 	  left.set(right_n, left_n);
   823 	} else {
   824 	  level_list[lev]=right_n;
   825 	  left.set(right_n, INVALID);
   826 	}
   827       } else {
   828 	if ( left_n!=INVALID ) {
   829 	  right.set(left_n, INVALID);
   830 	} else {
   831 	  level_list[lev]=INVALID;
   832 	}
   833       }
   834       //unlacing ends
   835 
   836       if ( level_list[lev]==INVALID ) {
   837 
   838 	//gapping starts
   839 	for (int i=lev; i!=k ; ) {
   840 	  Node v=level_list[++i];
   841 	  while ( v!=INVALID ) {
   842 	    level.set(v,_node_num);
   843 	    v=right[v];
   844 	  }
   845 	  level_list[i]=INVALID;
   846 	  if ( !what_heur ) first[i]=INVALID;
   847 	}
   848 
   849 	level.set(w,_node_num);
   850 	b=lev-1;
   851 	k=b;
   852 	//gapping ends
   853 
   854       } else {
   855 
   856 	if ( newlevel == _node_num ) level.set(w,_node_num);
   857 	else {
   858 	  level.set(w,++newlevel);
   859 	  next.set(w,first[newlevel]);
   860 	  first[newlevel]=w;
   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);
   865 	  right.set(w,z);
   866 	  left.set(w,INVALID);
   867 	  level_list[newlevel]=w;
   868 	}
   869       }
   870     } //relabel
   871 
   872   }; 
   873 
   874   ///\ingroup flowalgs
   875   ///\brief Function type interface for Preflow algorithm.
   876   ///
   877   ///Function type interface for Preflow algorithm.
   878   ///\sa Preflow
   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,
   883 			    const CM &cap,
   884 			    FM &flow
   885 			    )
   886   {
   887     return Preflow<GR,typename CM::Value,CM,FM>(g,source,target,cap,flow);
   888   }
   889 
   890 } //namespace lemon
   891 
   892 #endif //LEMON_PREFLOW_H