lemon/preflow.h
author hegyi
Thu, 12 Jan 2006 15:24:24 +0000
changeset 1893 4a35c7847c77
parent 1835 eb6c34c76501
child 1898 f030c01e6173
permissions -rw-r--r--
Documenatation of MapWin.
     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     ///The meanings are as follows:
   112     ///- \c ZERO_FLOW: constant zero flow
   113     ///- \c GEN_FLOW: any flow, i.e. the sum of the in-flows equals to
   114     ///the sum of the out-flows in every node except the \e source and
   115     ///the \e target.
   116     ///- \c PRE_FLOW: any preflow, i.e. the sum of the in-flows is at 
   117     ///least the sum of the out-flows in every node except the \e source.
   118     ///- \c NO_FLOW: indicates an unspecified edge map. \c flow will be 
   119     ///set to the constant zero flow in the beginning of
   120     ///the algorithm in this case.
   121     ///
   122     enum FlowEnum{
   123       NO_FLOW,
   124       ZERO_FLOW,
   125       GEN_FLOW,
   126       PRE_FLOW
   127     };
   128 
   129     ///Indicates the state of the preflow algorithm.
   130 
   131     ///Indicates the state of the preflow algorithm.
   132     ///The meanings are as follows:
   133     ///- \c AFTER_NOTHING: before running the algorithm or
   134     ///  at an unspecified state.
   135     ///- \c AFTER_PREFLOW_PHASE_1: right after running \c phase1
   136     ///- \c AFTER_PREFLOW_PHASE_2: after running \ref phase2()
   137     ///
   138     enum StatusEnum {
   139       AFTER_NOTHING,
   140       AFTER_PREFLOW_PHASE_1,      
   141       AFTER_PREFLOW_PHASE_2
   142     };
   143     
   144   protected: 
   145     FlowEnum flow_prop;
   146     StatusEnum status; // Do not needle this flag only if necessary.
   147     
   148   public: 
   149     ///The constructor of the class.
   150 
   151     ///The constructor of the class. 
   152     ///\param _gr The directed graph the algorithm runs on. 
   153     ///\param _s The source node.
   154     ///\param _t The target node.
   155     ///\param _cap The capacity of the edges. 
   156     ///\param _f The flow of the edges. 
   157     ///Except the graph, all of these parameters can be reset by
   158     ///calling \ref source, \ref target, \ref capacityMap and \ref
   159     ///flowMap, resp.
   160       Preflow(const Graph& _gr, Node _s, Node _t, 
   161 	      const CapacityMap& _cap, FlowMap& _f,
   162 	      const TOL &tol=TOL()) :
   163 	_g(&_gr), _source(_s), _target(_t), _capacity(&_cap),
   164 	_flow(&_f), surely(tol),
   165 	_node_num(countNodes(_gr)), level(_gr), excess(_gr,0), 
   166 	flow_prop(NO_FLOW), status(AFTER_NOTHING) { 
   167 	if ( _source==_target )
   168 	  throw InvalidArgument();
   169       }
   170     
   171 
   172                                                                               
   173     ///Runs the preflow algorithm.  
   174 
   175     ///Runs the preflow algorithm.
   176     ///
   177     void run() {
   178       phase1(flow_prop);
   179       phase2();
   180     }
   181     
   182     ///Runs the preflow algorithm.  
   183     
   184     ///Runs the preflow algorithm. 
   185     ///\pre The starting flow map must be
   186     /// - a constant zero flow if \c fp is \c ZERO_FLOW,
   187     /// - an arbitrary flow if \c fp is \c GEN_FLOW,
   188     /// - an arbitrary preflow if \c fp is \c PRE_FLOW,
   189     /// - any map if \c fp is NO_FLOW.
   190     ///If the starting flow map is a flow or a preflow then 
   191     ///the algorithm terminates faster.
   192     void run(FlowEnum fp) {
   193       flow_prop=fp;
   194       run();
   195     }
   196       
   197     ///Runs the first phase of the preflow algorithm.
   198 
   199     ///The preflow algorithm consists of two phases, this method runs
   200     ///the first phase. After the first phase the maximum flow value
   201     ///and a minimum value cut can already be computed, although a
   202     ///maximum flow is not yet obtained. So after calling this method
   203     ///\ref flowValue returns the value of a maximum flow and \ref
   204     ///minCut returns a minimum cut.     
   205     ///\warning \ref minMinCut and \ref maxMinCut do not give minimum
   206     ///value cuts unless calling \ref phase2.  
   207     ///\pre The starting flow must be 
   208     ///- a constant zero flow if \c fp is \c ZERO_FLOW, 
   209     ///- an arbitary flow if \c fp is \c GEN_FLOW, 
   210     ///- an arbitary preflow if \c fp is \c PRE_FLOW, 
   211     ///- any map if \c fp is NO_FLOW.
   212     void phase1(FlowEnum fp)
   213     {
   214       flow_prop=fp;
   215       phase1();
   216     }
   217 
   218     
   219     ///Runs the first phase of the preflow algorithm.
   220 
   221     ///The preflow algorithm consists of two phases, this method runs
   222     ///the first phase. After the first phase the maximum flow value
   223     ///and a minimum value cut can already be computed, although a
   224     ///maximum flow is not yet obtained. So after calling this method
   225     ///\ref flowValue returns the value of a maximum flow and \ref
   226     ///minCut returns a minimum cut.
   227     ///\warning \ref minMinCut() and \ref maxMinCut() do not
   228     ///give minimum value cuts unless calling \ref phase2().
   229     void phase1()
   230     {
   231       int heur0=(int)(H0*_node_num);  //time while running 'bound decrease'
   232       int heur1=(int)(H1*_node_num);  //time while running 'highest label'
   233       int heur=heur1;         //starting time interval (#of relabels)
   234       int numrelabel=0;
   235 
   236       bool what_heur=1;
   237       //It is 0 in case 'bound decrease' and 1 in case 'highest label'
   238 
   239       bool end=false;
   240       //Needed for 'bound decrease', true means no active 
   241       //nodes are above bound b.
   242 
   243       int k=_node_num-2;  //bound on the highest level under n containing a node
   244       int b=k;    //bound on the highest level under n of an active node
   245 
   246       VecNode first(_node_num, INVALID);
   247       NNMap next(*_g, INVALID);
   248 
   249       NNMap left(*_g, INVALID);
   250       NNMap right(*_g, INVALID);
   251       VecNode level_list(_node_num,INVALID);
   252       //List of the nodes in level i<n, set to n.
   253 
   254       preflowPreproc(first, next, level_list, left, right);
   255 
   256       //Push/relabel on the highest level active nodes.
   257       while ( true ) {
   258 	if ( b == 0 ) {
   259 	  if ( !what_heur && !end && k > 0 ) {
   260 	    b=k;
   261 	    end=true;
   262 	  } else break;
   263 	}
   264 
   265 	if ( first[b]==INVALID ) --b;
   266 	else {
   267 	  end=false;
   268 	  Node w=first[b];
   269 	  first[b]=next[w];
   270 	  int newlevel=push(w, next, first);
   271 	  if ( excess[w] > 0 ) relabel(w, newlevel, first, next, level_list, 
   272 				       left, right, b, k, what_heur);
   273 
   274 	  ++numrelabel;
   275 	  if ( numrelabel >= heur ) {
   276 	    numrelabel=0;
   277 	    if ( what_heur ) {
   278 	      what_heur=0;
   279 	      heur=heur0;
   280 	      end=false;
   281 	    } else {
   282 	      what_heur=1;
   283 	      heur=heur1;
   284 	      b=k;
   285 	    }
   286 	  }
   287 	}
   288       }
   289       flow_prop=PRE_FLOW;
   290       status=AFTER_PREFLOW_PHASE_1;
   291     }
   292     // Heuristics:
   293     //   2 phase
   294     //   gap
   295     //   list 'level_list' on the nodes on level i implemented by hand
   296     //   stack 'active' on the active nodes on level i      
   297     //   runs heuristic 'highest label' for H1*n relabels
   298     //   runs heuristic 'bound decrease' for H0*n relabels,
   299     //        starts with 'highest label'
   300     //   Parameters H0 and H1 are initialized to 20 and 1.
   301 
   302 
   303     ///Runs the second phase of the preflow algorithm.
   304 
   305     ///The preflow algorithm consists of two phases, this method runs
   306     ///the second phase. After calling \ref phase1() and then
   307     ///\ref phase2(),
   308     /// \ref flowMap() return a maximum flow, \ref flowValue
   309     ///returns the value of a maximum flow, \ref minCut returns a
   310     ///minimum cut, while the methods \ref minMinCut and \ref
   311     ///maxMinCut return the inclusionwise minimum and maximum cuts of
   312     ///minimum value, resp.  \pre \ref phase1 must be called before.
   313     void phase2()
   314     {
   315 
   316       int k=_node_num-2;  //bound on the highest level under n containing a node
   317       int b=k;    //bound on the highest level under n of an active node
   318 
   319     
   320       VecNode first(_node_num, INVALID);
   321       NNMap next(*_g, INVALID); 
   322       level.set(_source,0);
   323       std::queue<Node> bfs_queue;
   324       bfs_queue.push(_source);
   325 
   326       while ( !bfs_queue.empty() ) {
   327 
   328 	Node v=bfs_queue.front();
   329 	bfs_queue.pop();
   330 	int l=level[v]+1;
   331 
   332 	for(InEdgeIt e(*_g,v); e!=INVALID; ++e) {
   333 	  if ( (*_capacity)[e] <= (*_flow)[e] ) continue;
   334 	  Node u=_g->source(e);
   335 	  if ( level[u] >= _node_num ) {
   336 	    bfs_queue.push(u);
   337 	    level.set(u, l);
   338 	    if ( excess[u] > 0 ) {
   339 	      next.set(u,first[l]);
   340 	      first[l]=u;
   341 	    }
   342 	  }
   343 	}
   344 
   345 	for(OutEdgeIt e(*_g,v); e!=INVALID; ++e) {
   346 	  if ( 0 >= (*_flow)[e] ) continue;
   347 	  Node u=_g->target(e);
   348 	  if ( level[u] >= _node_num ) {
   349 	    bfs_queue.push(u);
   350 	    level.set(u, l);
   351 	    if ( excess[u] > 0 ) {
   352 	      next.set(u,first[l]);
   353 	      first[l]=u;
   354 	    }
   355 	  }
   356 	}
   357       }
   358       b=_node_num-2;
   359 
   360       while ( true ) {
   361 
   362 	if ( b == 0 ) break;
   363 	if ( first[b]==INVALID ) --b;
   364 	else {
   365 	  Node w=first[b];
   366 	  first[b]=next[w];
   367 	  int newlevel=push(w,next, first);
   368 	  
   369 	  //relabel
   370 	  if ( excess[w] > 0 ) {
   371 	    level.set(w,++newlevel);
   372 	    next.set(w,first[newlevel]);
   373 	    first[newlevel]=w;
   374 	    b=newlevel;
   375 	  }
   376 	} 
   377       } // while(true)
   378       flow_prop=GEN_FLOW;
   379       status=AFTER_PREFLOW_PHASE_2;
   380     }
   381 
   382     /// Returns the value of the maximum flow.
   383 
   384     /// Returns the value of the maximum flow by returning the excess
   385     /// of the target node \c t. This value equals to the value of
   386     /// the maximum flow already after running \ref phase1.
   387     Num flowValue() const {
   388       return excess[_target];
   389     }
   390 
   391 
   392     ///Returns a minimum value cut.
   393 
   394     ///Sets \c M to the characteristic vector of a minimum value
   395     ///cut. This method can be called both after running \ref
   396     ///phase1 and \ref phase2. It is much faster after
   397     ///\ref phase1.  \pre M should be a bool-valued node-map. \pre
   398     ///If \ref minCut() is called after \ref phase2() then M should
   399     ///be initialized to false.
   400     template<typename _CutMap>
   401     void minCut(_CutMap& M) const {
   402       switch ( status ) {
   403 	case AFTER_PREFLOW_PHASE_1:
   404 	for(NodeIt v(*_g); v!=INVALID; ++v) {
   405 	  if (level[v] < _node_num) {
   406 	    M.set(v, false);
   407 	  } else {
   408 	    M.set(v, true);
   409 	  }
   410 	}
   411 	break;
   412 	case AFTER_PREFLOW_PHASE_2:
   413 	minMinCut(M);
   414 	break;
   415 	case AFTER_NOTHING:
   416 	break;
   417       }
   418     }
   419 
   420     ///Returns the inclusionwise minimum of the minimum value cuts.
   421 
   422     ///Sets \c M to the characteristic vector of the minimum value cut
   423     ///which is inclusionwise minimum. It is computed by processing a
   424     ///bfs from the source node \c s in the residual graph.  \pre M
   425     ///should be a node map of bools initialized to false.  \pre \ref
   426     ///phase2 should already be run.
   427     template<typename _CutMap>
   428     void minMinCut(_CutMap& M) const {
   429 
   430       std::queue<Node> queue;
   431       M.set(_source,true);
   432       queue.push(_source);
   433       
   434       while (!queue.empty()) {
   435 	Node w=queue.front();
   436 	queue.pop();
   437 	
   438 	for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   439 	  Node v=_g->target(e);
   440 	  if (!M[v] && (*_flow)[e] < (*_capacity)[e] ) {
   441 	    queue.push(v);
   442 	    M.set(v, true);
   443 	  }
   444 	}
   445 	
   446 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   447 	  Node v=_g->source(e);
   448 	  if (!M[v] && (*_flow)[e] > 0 ) {
   449 	    queue.push(v);
   450 	    M.set(v, true);
   451 	  }
   452 	}
   453       }
   454     }
   455     
   456     ///Returns the inclusionwise maximum of the minimum value cuts.
   457 
   458     ///Sets \c M to the characteristic vector of the minimum value cut
   459     ///which is inclusionwise maximum. It is computed by processing a
   460     ///backward bfs from the target node \c t in the residual graph.
   461     ///\pre \ref phase2() or run() should already be run.
   462     template<typename _CutMap>
   463     void maxMinCut(_CutMap& M) const {
   464 
   465       for(NodeIt v(*_g) ; v!=INVALID; ++v) M.set(v, true);
   466 
   467       std::queue<Node> queue;
   468 
   469       M.set(_target,false);
   470       queue.push(_target);
   471 
   472       while (!queue.empty()) {
   473         Node w=queue.front();
   474 	queue.pop();
   475 
   476 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   477 	  Node v=_g->source(e);
   478 	  if (M[v] && (*_flow)[e] < (*_capacity)[e] ) {
   479 	    queue.push(v);
   480 	    M.set(v, false);
   481 	  }
   482 	}
   483 
   484 	for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   485 	  Node v=_g->target(e);
   486 	  if (M[v] && (*_flow)[e] > 0 ) {
   487 	    queue.push(v);
   488 	    M.set(v, false);
   489 	  }
   490 	}
   491       }
   492     }
   493 
   494     ///Sets the source node to \c _s.
   495 
   496     ///Sets the source node to \c _s.
   497     /// 
   498     void source(Node _s) { 
   499       _source=_s; 
   500       if ( flow_prop != ZERO_FLOW ) flow_prop=NO_FLOW;
   501       status=AFTER_NOTHING; 
   502     }
   503 
   504     ///Returns the source node.
   505 
   506     ///Returns the source node.
   507     /// 
   508     Node source() const { 
   509       return _source;
   510     }
   511 
   512     ///Sets the target node to \c _t.
   513 
   514     ///Sets the target node to \c _t.
   515     ///
   516     void target(Node _t) { 
   517       _target=_t; 
   518       if ( flow_prop == GEN_FLOW ) flow_prop=PRE_FLOW;
   519       status=AFTER_NOTHING; 
   520     }
   521 
   522     ///Returns the target node.
   523 
   524     ///Returns the target node.
   525     /// 
   526     Node target() const { 
   527       return _target;
   528     }
   529 
   530     /// Sets the edge map of the capacities to _cap.
   531 
   532     /// Sets the edge map of the capacities to _cap.
   533     /// 
   534     void capacityMap(const CapacityMap& _cap) { 
   535       _capacity=&_cap; 
   536       status=AFTER_NOTHING; 
   537     }
   538     /// Returns a reference to capacity map.
   539 
   540     /// Returns a reference to capacity map.
   541     /// 
   542     const CapacityMap &capacityMap() const { 
   543       return *_capacity;
   544     }
   545 
   546     /// Sets the edge map of the flows to _flow.
   547 
   548     /// Sets the edge map of the flows to _flow.
   549     /// 
   550     void flowMap(FlowMap& _f) { 
   551       _flow=&_f; 
   552       flow_prop=NO_FLOW;
   553       status=AFTER_NOTHING; 
   554     }
   555      
   556     /// Returns a reference to flow map.
   557 
   558     /// Returns a reference to flow map.
   559     /// 
   560     const FlowMap &flowMap() const { 
   561       return *_flow;
   562     }
   563 
   564   private:
   565 
   566     int push(Node w, NNMap& next, VecNode& first) {
   567 
   568       int lev=level[w];
   569       Num exc=excess[w];
   570       int newlevel=_node_num;       //bound on the next level of w
   571 
   572       for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   573 	if ( (*_flow)[e] >= (*_capacity)[e] ) continue;
   574 	Node v=_g->target(e);
   575 
   576 	if( lev > level[v] ) { //Push is allowed now
   577 	  
   578 	  if ( excess[v]<=0 && v!=_target && v!=_source ) {
   579 	    next.set(v,first[level[v]]);
   580 	    first[level[v]]=v;
   581 	  }
   582 
   583 	  Num cap=(*_capacity)[e];
   584 	  Num flo=(*_flow)[e];
   585 	  Num remcap=cap-flo;
   586 	  
   587 	  if ( remcap >= exc ) { //A nonsaturating push.
   588 	    
   589 	    _flow->set(e, flo+exc);
   590 	    excess.set(v, excess[v]+exc);
   591 	    exc=0;
   592 	    break;
   593 
   594 	  } else { //A saturating push.
   595 	    _flow->set(e, cap);
   596 	    excess.set(v, excess[v]+remcap);
   597 	    exc-=remcap;
   598 	  }
   599 	} else if ( newlevel > level[v] ) newlevel = level[v];
   600       } //for out edges wv
   601 
   602       if ( exc > 0 ) {
   603 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   604 	  
   605 	  if( (*_flow)[e] <= 0 ) continue;
   606 	  Node v=_g->source(e);
   607 
   608 	  if( lev > level[v] ) { //Push is allowed now
   609 
   610 	    if ( excess[v]<=0 && v!=_target && v!=_source ) {
   611 	      next.set(v,first[level[v]]);
   612 	      first[level[v]]=v;
   613 	    }
   614 
   615 	    Num flo=(*_flow)[e];
   616 
   617 	    if ( flo >= exc ) { //A nonsaturating push.
   618 
   619 	      _flow->set(e, flo-exc);
   620 	      excess.set(v, excess[v]+exc);
   621 	      exc=0;
   622 	      break;
   623 	    } else {  //A saturating push.
   624 
   625 	      excess.set(v, excess[v]+flo);
   626 	      exc-=flo;
   627 	      _flow->set(e,0);
   628 	    }
   629 	  } else if ( newlevel > level[v] ) newlevel = level[v];
   630 	} //for in edges vw
   631 
   632       } // if w still has excess after the out edge for cycle
   633 
   634       excess.set(w, exc);
   635       
   636       return newlevel;
   637     }
   638     
   639     
   640     
   641     void preflowPreproc(VecNode& first, NNMap& next, 
   642 			VecNode& level_list, NNMap& left, NNMap& right)
   643     {
   644       for(NodeIt v(*_g); v!=INVALID; ++v) level.set(v,_node_num);
   645       std::queue<Node> bfs_queue;
   646       
   647       if ( flow_prop == GEN_FLOW || flow_prop == PRE_FLOW ) {
   648 	//Reverse_bfs from t in the residual graph,
   649 	//to find the starting level.
   650 	level.set(_target,0);
   651 	bfs_queue.push(_target);
   652 	
   653 	while ( !bfs_queue.empty() ) {
   654 	  
   655 	  Node v=bfs_queue.front();
   656 	  bfs_queue.pop();
   657 	  int l=level[v]+1;
   658 	  
   659 	  for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
   660 	    if ( (*_capacity)[e] <= (*_flow)[e] ) continue;
   661 	    Node w=_g->source(e);
   662 	    if ( level[w] == _node_num && w != _source ) {
   663 	      bfs_queue.push(w);
   664 	      Node z=level_list[l];
   665 	      if ( z!=INVALID ) left.set(z,w);
   666 	      right.set(w,z);
   667 	      level_list[l]=w;
   668 	      level.set(w, l);
   669 	    }
   670 	  }
   671 	  
   672 	  for(OutEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
   673 	    if ( 0 >= (*_flow)[e] ) continue;
   674 	    Node w=_g->target(e);
   675 	    if ( level[w] == _node_num && w != _source ) {
   676 	      bfs_queue.push(w);
   677 	      Node z=level_list[l];
   678 	      if ( z!=INVALID ) left.set(z,w);
   679 	      right.set(w,z);
   680 	      level_list[l]=w;
   681 	      level.set(w, l);
   682 	    }
   683 	  }
   684 	} //while
   685       } //if
   686 
   687 
   688       switch (flow_prop) {
   689 	case NO_FLOW:  
   690 	for(EdgeIt e(*_g); e!=INVALID; ++e) _flow->set(e,0);
   691 	case ZERO_FLOW:
   692 	for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
   693 	
   694 	//Reverse_bfs from t, to find the starting level.
   695 	level.set(_target,0);
   696 	bfs_queue.push(_target);
   697 	
   698 	while ( !bfs_queue.empty() ) {
   699 	  
   700 	  Node v=bfs_queue.front();
   701 	  bfs_queue.pop();
   702 	  int l=level[v]+1;
   703 	  
   704 	  for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
   705 	    Node w=_g->source(e);
   706 	    if ( level[w] == _node_num && w != _source ) {
   707 	      bfs_queue.push(w);
   708 	      Node z=level_list[l];
   709 	      if ( z!=INVALID ) left.set(z,w);
   710 	      right.set(w,z);
   711 	      level_list[l]=w;
   712 	      level.set(w, l);
   713 	    }
   714 	  }
   715 	}
   716 	
   717 	//the starting flow
   718 	for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
   719 	  Num c=(*_capacity)[e];
   720 	  if ( c <= 0 ) continue;
   721 	  Node w=_g->target(e);
   722 	  if ( level[w] < _node_num ) {
   723 	    if ( excess[w] <= 0 && w!=_target ) { //putting into the stack
   724 	      next.set(w,first[level[w]]);
   725 	      first[level[w]]=w;
   726 	    }
   727 	    _flow->set(e, c);
   728 	    excess.set(w, excess[w]+c);
   729 	  }
   730 	}
   731 	break;
   732 
   733 	case GEN_FLOW:
   734 	for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
   735 	{
   736 	  Num exc=0;
   737 	  for(InEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc+=(*_flow)[e];
   738 	  for(OutEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc-=(*_flow)[e];
   739 	  excess.set(_target,exc);
   740 	}
   741 
   742 	//the starting flow
   743 	for(OutEdgeIt e(*_g,_source); e!=INVALID; ++e)	{
   744 	  Num rem=(*_capacity)[e]-(*_flow)[e];
   745 	  if ( rem <= 0 ) continue;
   746 	  Node w=_g->target(e);
   747 	  if ( level[w] < _node_num ) {
   748 	    if ( excess[w] <= 0 && w!=_target ) { //putting into the stack
   749 	      next.set(w,first[level[w]]);
   750 	      first[level[w]]=w;
   751 	    }   
   752 	    _flow->set(e, (*_capacity)[e]);
   753 	    excess.set(w, excess[w]+rem);
   754 	  }
   755 	}
   756 	
   757 	for(InEdgeIt e(*_g,_source); e!=INVALID; ++e) {
   758 	  if ( (*_flow)[e] <= 0 ) continue;
   759 	  Node w=_g->source(e);
   760 	  if ( level[w] < _node_num ) {
   761 	    if ( excess[w] <= 0 && w!=_target ) {
   762 	      next.set(w,first[level[w]]);
   763 	      first[level[w]]=w;
   764 	    }  
   765 	    excess.set(w, excess[w]+(*_flow)[e]);
   766 	    _flow->set(e, 0);
   767 	  }
   768 	}
   769 	break;
   770 
   771 	case PRE_FLOW:	
   772 	//the starting flow
   773 	for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
   774 	  Num rem=(*_capacity)[e]-(*_flow)[e];
   775 	  if ( rem <= 0 ) continue;
   776 	  Node w=_g->target(e);
   777 	  if ( level[w] < _node_num ) _flow->set(e, (*_capacity)[e]);
   778 	}
   779 	
   780 	for(InEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
   781 	  if ( (*_flow)[e] <= 0 ) continue;
   782 	  Node w=_g->source(e);
   783 	  if ( level[w] < _node_num ) _flow->set(e, 0);
   784 	}
   785 	
   786 	//computing the excess
   787 	for(NodeIt w(*_g); w!=INVALID; ++w) {
   788 	  Num exc=0;
   789 	  for(InEdgeIt e(*_g,w); e!=INVALID; ++e) exc+=(*_flow)[e];
   790 	  for(OutEdgeIt e(*_g,w); e!=INVALID; ++e) exc-=(*_flow)[e];
   791 	  excess.set(w,exc);
   792 	  
   793 	  //putting the active nodes into the stack
   794 	  int lev=level[w];
   795 	    if ( exc > 0 && lev < _node_num && Node(w) != _target ) {
   796 	      next.set(w,first[lev]);
   797 	      first[lev]=w;
   798 	    }
   799 	}
   800 	break;
   801       } //switch
   802     } //preflowPreproc
   803 
   804 
   805     void relabel(Node w, int newlevel, VecNode& first, NNMap& next, 
   806 		 VecNode& level_list, NNMap& left,
   807 		 NNMap& right, int& b, int& k, bool what_heur )
   808     {
   809 
   810       int lev=level[w];
   811 
   812       Node right_n=right[w];
   813       Node left_n=left[w];
   814 
   815       //unlacing starts
   816       if ( right_n!=INVALID ) {
   817 	if ( left_n!=INVALID ) {
   818 	  right.set(left_n, right_n);
   819 	  left.set(right_n, left_n);
   820 	} else {
   821 	  level_list[lev]=right_n;
   822 	  left.set(right_n, INVALID);
   823 	}
   824       } else {
   825 	if ( left_n!=INVALID ) {
   826 	  right.set(left_n, INVALID);
   827 	} else {
   828 	  level_list[lev]=INVALID;
   829 	}
   830       }
   831       //unlacing ends
   832 
   833       if ( level_list[lev]==INVALID ) {
   834 
   835 	//gapping starts
   836 	for (int i=lev; i!=k ; ) {
   837 	  Node v=level_list[++i];
   838 	  while ( v!=INVALID ) {
   839 	    level.set(v,_node_num);
   840 	    v=right[v];
   841 	  }
   842 	  level_list[i]=INVALID;
   843 	  if ( !what_heur ) first[i]=INVALID;
   844 	}
   845 
   846 	level.set(w,_node_num);
   847 	b=lev-1;
   848 	k=b;
   849 	//gapping ends
   850 
   851       } else {
   852 
   853 	if ( newlevel == _node_num ) level.set(w,_node_num);
   854 	else {
   855 	  level.set(w,++newlevel);
   856 	  next.set(w,first[newlevel]);
   857 	  first[newlevel]=w;
   858 	  if ( what_heur ) b=newlevel;
   859 	  if ( k < newlevel ) ++k;      //now k=newlevel
   860 	  Node z=level_list[newlevel];
   861 	  if ( z!=INVALID ) left.set(z,w);
   862 	  right.set(w,z);
   863 	  left.set(w,INVALID);
   864 	  level_list[newlevel]=w;
   865 	}
   866       }
   867     } //relabel
   868 
   869   }; 
   870 
   871   ///\ingroup flowalgs
   872   ///\brief Function type interface for Preflow algorithm.
   873   ///
   874   ///Function type interface for Preflow algorithm.
   875   ///\sa Preflow
   876   template<class GR, class CM, class FM>
   877   Preflow<GR,typename CM::Value,CM,FM> preflow(const GR &g,
   878 			    typename GR::Node source,
   879 			    typename GR::Node target,
   880 			    const CM &cap,
   881 			    FM &flow
   882 			    )
   883   {
   884     return Preflow<GR,typename CM::Value,CM,FM>(g,source,target,cap,flow);
   885   }
   886 
   887 } //namespace lemon
   888 
   889 #endif //LEMON_PREFLOW_H