lemon/preflow.h
author deba
Tue, 09 Oct 2007 17:11:42 +0000
changeset 2491 b63ae56979ef
parent 2391 14a343be7a5a
child 2514 57143c09dc20
permissions -rw-r--r--
Documentation for lemon tools
     1 /* -*- C++ -*-
     2  *
     3  * This file is a part of LEMON, a generic C++ optimization library
     4  *
     5  * Copyright (C) 2003-2007
     6  * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
     7  * (Egervary Research Group on Combinatorial Optimization, EGRES).
     8  *
     9  * Permission to use, modify and distribute this software is granted
    10  * provided that this copyright notice appears in all copies. For
    11  * precise terms see the accompanying LICENSE file.
    12  *
    13  * This software is provided "AS IS" with no warranty of any kind,
    14  * express or implied, and with no claim as to its suitability for any
    15  * purpose.
    16  *
    17  */
    18 
    19 #ifndef LEMON_PREFLOW_H
    20 #define LEMON_PREFLOW_H
    21 
    22 #include <vector>
    23 #include <queue>
    24 
    25 #include <lemon/error.h>
    26 #include <lemon/bits/invalid.h>
    27 #include <lemon/tolerance.h>
    28 #include <lemon/maps.h>
    29 #include <lemon/graph_utils.h>
    30 
    31 /// \file
    32 /// \ingroup max_flow
    33 /// \brief Implementation of the preflow algorithm.
    34 
    35 namespace lemon {
    36 
    37   ///\ingroup max_flow
    38   ///\brief %Preflow algorithms class.
    39   ///
    40   ///This class provides an implementation of the \e preflow \e
    41   ///algorithm producing a flow of maximum value in a directed
    42   ///graph. The preflow algorithms are the fastest known max flow algorithms. 
    43   ///The \e source node, the \e target node, the \e
    44   ///capacity of the edges and the \e starting \e flow value of the
    45   ///edges should be passed to the algorithm through the
    46   ///constructor. It is possible to change these quantities using the
    47   ///functions \ref source, \ref target, \ref capacityMap and \ref
    48   ///flowMap.
    49   ///
    50   ///After running \ref lemon::Preflow::phase1() "phase1()"
    51   ///or \ref lemon::Preflow::run() "run()", the maximal flow
    52   ///value can be obtained by calling \ref flowValue(). The minimum
    53   ///value cut can be written into a <tt>bool</tt> node map by
    54   ///calling \ref minCut(). (\ref minMinCut() and \ref maxMinCut() writes
    55   ///the inclusionwise minimum and maximum of the minimum value cuts,
    56   ///resp.)
    57   ///
    58   ///\param Graph The directed graph type the algorithm runs on.
    59   ///\param Num The number type of the capacities and the flow values.
    60   ///\param CapacityMap The capacity map type.
    61   ///\param FlowMap The flow map type.
    62   ///\param Tol The tolerance type. 
    63   ///
    64   ///\author Jacint Szabo 
    65   ///\todo Second template parameter is superfluous
    66   template <typename Graph, typename Num,
    67 	    typename CapacityMap=typename Graph::template EdgeMap<Num>,
    68             typename FlowMap=typename Graph::template EdgeMap<Num>,
    69 	    typename Tol=Tolerance<Num> >
    70   class Preflow {
    71   protected:
    72     typedef typename Graph::Node Node;
    73     typedef typename Graph::NodeIt NodeIt;
    74     typedef typename Graph::EdgeIt EdgeIt;
    75     typedef typename Graph::OutEdgeIt OutEdgeIt;
    76     typedef typename Graph::InEdgeIt InEdgeIt;
    77 
    78     typedef typename Graph::template NodeMap<Node> NNMap;
    79     typedef typename std::vector<Node> VecNode;
    80 
    81     const Graph* _g;
    82     Node _source;
    83     Node _target;
    84     const CapacityMap* _capacity;
    85     FlowMap* _flow;
    86 
    87     Tol _surely;
    88     
    89     int _node_num;      //the number of nodes of G
    90     
    91     typename Graph::template NodeMap<int> level;  
    92     typename Graph::template NodeMap<Num> excess;
    93 
    94     // constants used for heuristics
    95     static const int H0=20;
    96     static const int H1=1;
    97 
    98   public:
    99 
   100     ///\ref Exception for the case when s=t.
   101 
   102     ///\ref Exception for the case when the source equals the target.
   103     class InvalidArgument : public lemon::LogicError {
   104     public:
   105       virtual const char* what() const throw() {
   106 	return "lemon::Preflow::InvalidArgument";
   107       }
   108     };
   109     
   110     
   111     ///Indicates the property of the starting flow map.
   112     
   113     ///Indicates the property of the starting flow map.
   114     ///
   115     enum FlowEnum{
   116       ///indicates an unspecified edge map. \c flow will be 
   117       ///set to the constant zero flow in the beginning of
   118       ///the algorithm in this case.
   119       NO_FLOW,
   120       ///constant zero flow
   121       ZERO_FLOW,
   122       ///any flow, i.e. the sum of the in-flows equals to
   123       ///the sum of the out-flows in every node except the \c source and
   124       ///the \c target.
   125       GEN_FLOW,
   126       ///any preflow, i.e. the sum of the in-flows is at 
   127       ///least the sum of the out-flows in every node except the \c source.
   128       PRE_FLOW
   129     };
   130 
   131     ///Indicates the state of the preflow algorithm.
   132 
   133     ///Indicates the state of the preflow algorithm.
   134     ///
   135     enum StatusEnum {
   136       ///before running the algorithm or
   137       ///at an unspecified state.
   138       AFTER_NOTHING,
   139       ///right after running \ref phase1()
   140       AFTER_PREFLOW_PHASE_1,      
   141       ///after running \ref phase2()
   142       AFTER_PREFLOW_PHASE_2
   143     };
   144     
   145   protected: 
   146     FlowEnum flow_prop;
   147     StatusEnum status; // Do not needle this flag only if necessary.
   148     
   149   public: 
   150     ///The constructor of the class.
   151 
   152     ///The constructor of the class. 
   153     ///\param _gr The directed graph the algorithm runs on. 
   154     ///\param _s The source node.
   155     ///\param _t The target node.
   156     ///\param _cap The capacity of the edges. 
   157     ///\param _f The flow of the edges. 
   158     ///\param _sr Tol class.
   159     ///Except the graph, all of these parameters can be reset by
   160     ///calling \ref source, \ref target, \ref capacityMap and \ref
   161     ///flowMap, resp.
   162     Preflow(const Graph& _gr, Node _s, Node _t, 
   163             const CapacityMap& _cap, FlowMap& _f,
   164             const Tol &_sr=Tol()) :
   165 	_g(&_gr), _source(_s), _target(_t), _capacity(&_cap),
   166 	_flow(&_f), _surely(_sr),
   167 	_node_num(countNodes(_gr)), level(_gr), excess(_gr,0), 
   168 	flow_prop(NO_FLOW), status(AFTER_NOTHING) { 
   169 	if ( _source==_target )
   170 	  throw InvalidArgument();
   171     }
   172     
   173     ///Give a reference to the tolerance handler class
   174 
   175     ///Give a reference to the tolerance handler class
   176     ///\sa Tolerance
   177     Tol &tolerance() { return _surely; }
   178 
   179     ///Runs the preflow algorithm.  
   180 
   181     ///Runs the preflow algorithm.
   182     ///
   183     void run() {
   184       phase1(flow_prop);
   185       phase2();
   186     }
   187     
   188     ///Runs the preflow algorithm.  
   189     
   190     ///Runs the preflow algorithm. 
   191     ///\pre The starting flow map must be
   192     /// - a constant zero flow if \c fp is \c ZERO_FLOW,
   193     /// - an arbitrary flow if \c fp is \c GEN_FLOW,
   194     /// - an arbitrary preflow if \c fp is \c PRE_FLOW,
   195     /// - any map if \c fp is NO_FLOW.
   196     ///If the starting flow map is a flow or a preflow then 
   197     ///the algorithm terminates faster.
   198     void run(FlowEnum fp) {
   199       flow_prop=fp;
   200       run();
   201     }
   202       
   203     ///Runs the first phase of the preflow algorithm.
   204 
   205     ///The preflow algorithm consists of two phases, this method runs
   206     ///the first phase. After the first phase the maximum flow value
   207     ///and a minimum value cut can already be computed, although a
   208     ///maximum flow is not yet obtained. So after calling this method
   209     ///\ref flowValue returns the value of a maximum flow and \ref
   210     ///minCut returns a minimum cut.     
   211     ///\warning \ref minMinCut and \ref maxMinCut do not give minimum
   212     ///value cuts unless calling \ref phase2.  
   213     ///\warning A real flow map (i.e. not \ref lemon::NullMap "NullMap")
   214     ///is needed for this phase.
   215     ///\pre The starting flow must be 
   216     ///- a constant zero flow if \c fp is \c ZERO_FLOW, 
   217     ///- an arbitary flow if \c fp is \c GEN_FLOW, 
   218     ///- an arbitary preflow if \c fp is \c PRE_FLOW, 
   219     ///- any map if \c fp is NO_FLOW.
   220     void phase1(FlowEnum fp)
   221     {
   222       flow_prop=fp;
   223       phase1();
   224     }
   225 
   226     
   227     ///Runs the first phase of the preflow algorithm.
   228 
   229     ///The preflow algorithm consists of two phases, this method runs
   230     ///the first phase. After the first phase the maximum flow value
   231     ///and a minimum value cut can already be computed, although a
   232     ///maximum flow is not yet obtained. So after calling this method
   233     ///\ref flowValue returns the value of a maximum flow and \ref
   234     ///minCut returns a minimum cut.
   235     ///\warning \ref minMinCut() and \ref maxMinCut() do not
   236     ///give minimum value cuts unless calling \ref phase2().
   237     ///\warning A real flow map (i.e. not \ref lemon::NullMap "NullMap")
   238     ///is needed for this phase.
   239     void phase1()
   240     {
   241       int heur0=int(H0*_node_num);  //time while running 'bound decrease'
   242       int heur1=int(H1*_node_num);  //time while running 'highest label'
   243       int heur=heur1;         //starting time interval (#of relabels)
   244       int numrelabel=0;
   245 
   246       bool what_heur=1;
   247       //It is 0 in case 'bound decrease' and 1 in case 'highest label'
   248 
   249       bool end=false;
   250       //Needed for 'bound decrease', true means no active 
   251       //nodes are above bound b.
   252 
   253       int k=_node_num-2;  //bound on the highest level under n containing a node
   254       int b=k;    //bound on the highest level under n containing an active node
   255 
   256       VecNode first(_node_num, INVALID);
   257       NNMap next(*_g, INVALID);
   258 
   259       NNMap left(*_g, INVALID);
   260       NNMap right(*_g, INVALID);
   261       VecNode level_list(_node_num,INVALID);
   262       //List of the nodes in level i<n, set to n.
   263 
   264       preflowPreproc(first, next, level_list, left, right);
   265 
   266       //Push/relabel on the highest level active nodes.
   267       while ( true ) {
   268 	if ( b == 0 ) {
   269 	  if ( !what_heur && !end && k > 0 ) {
   270 	    b=k;
   271 	    end=true;
   272 	  } else break;
   273 	}
   274 
   275 	if ( first[b]==INVALID ) --b;
   276 	else {
   277 	  end=false;
   278 	  Node w=first[b];
   279 	  first[b]=next[w];
   280 	  int newlevel=push(w, next, first);
   281 	  if ( excess[w] != 0 ) {
   282             relabel(w, newlevel, first, next, level_list, 
   283                     left, right, b, k, what_heur);
   284           }
   285 
   286 	  ++numrelabel;
   287 	  if ( numrelabel >= heur ) {
   288 	    numrelabel=0;
   289 	    if ( what_heur ) {
   290 	      what_heur=0;
   291 	      heur=heur0;
   292 	      end=false;
   293 	    } else {
   294 	      what_heur=1;
   295 	      heur=heur1;
   296 	      b=k;
   297 	    }
   298 	  }
   299 	}
   300       }
   301       flow_prop=PRE_FLOW;
   302       status=AFTER_PREFLOW_PHASE_1;
   303     }
   304     // Heuristics:
   305     //   2 phase
   306     //   gap
   307     //   list 'level_list' on the nodes on level i implemented by hand
   308     //   stack 'active' on the active nodes on level i      
   309     //   runs heuristic 'highest label' for H1*n relabels
   310     //   runs heuristic 'bound decrease' for H0*n relabels,
   311     //        starts with 'highest label'
   312     //   Parameters H0 and H1 are initialized to 20 and 1.
   313 
   314 
   315     ///Runs the second phase of the preflow algorithm.
   316 
   317     ///The preflow algorithm consists of two phases, this method runs
   318     ///the second phase. After calling \ref phase1() and then
   319     ///\ref phase2(),
   320     /// \ref flowMap() return a maximum flow, \ref flowValue
   321     ///returns the value of a maximum flow, \ref minCut returns a
   322     ///minimum cut, while the methods \ref minMinCut and \ref
   323     ///maxMinCut return the inclusionwise minimum and maximum cuts of
   324     ///minimum value, resp.  \pre \ref phase1 must be called before.
   325     ///
   326     /// \todo The inexact computation can cause positive excess on a set of 
   327     /// unpushable nodes. We may have to watch the empty level in this case 
   328     /// due to avoid the terrible long running time.
   329     void phase2()
   330     {
   331 
   332       int k=_node_num-2;  //bound on the highest level under n containing a node
   333       int b=k;    //bound on the highest level under n of an active node
   334 
   335     
   336       VecNode first(_node_num, INVALID);
   337       NNMap next(*_g, INVALID); 
   338       level.set(_source,0);
   339       std::queue<Node> bfs_queue;
   340       bfs_queue.push(_source);
   341 
   342       while ( !bfs_queue.empty() ) {
   343 
   344 	Node v=bfs_queue.front();
   345 	bfs_queue.pop();
   346 	int l=level[v]+1;
   347 
   348 	for(InEdgeIt e(*_g,v); e!=INVALID; ++e) {
   349 	  if ( !_surely.positive((*_capacity)[e] - (*_flow)[e])) continue;
   350 	  Node u=_g->source(e);
   351 	  if ( level[u] >= _node_num ) {
   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 	for(OutEdgeIt e(*_g,v); e!=INVALID; ++e) {
   362 	  if ( !_surely.positive((*_flow)[e]) ) continue;
   363 	  Node u=_g->target(e);
   364 	  if ( level[u] >= _node_num ) {
   365 	    bfs_queue.push(u);
   366 	    level.set(u, l);
   367 	    if ( excess[u] != 0 ) {
   368 	      next.set(u,first[l]);
   369 	      first[l]=u;
   370 	    }
   371 	  }
   372 	}
   373       }
   374       b=_node_num-2;
   375 
   376       while ( true ) {
   377 
   378 	if ( b == 0 ) break;
   379 	if ( first[b]==INVALID ) --b;
   380 	else {
   381 	  Node w=first[b];
   382 	  first[b]=next[w];
   383 	  int newlevel=push(w,next, first);
   384 	  
   385           if ( newlevel == _node_num) {
   386             excess.set(w, 0);
   387 	    level.set(w,_node_num);
   388           }
   389 	  //relabel
   390 	  if ( excess[w] != 0 ) {
   391 	    level.set(w,++newlevel);
   392 	    next.set(w,first[newlevel]);
   393 	    first[newlevel]=w;
   394 	    b=newlevel;
   395 	  }
   396 	} 
   397       } // while(true)
   398       flow_prop=GEN_FLOW;
   399       status=AFTER_PREFLOW_PHASE_2;
   400     }
   401 
   402     /// Returns the value of the maximum flow.
   403 
   404     /// Returns the value of the maximum flow by returning the excess
   405     /// of the target node \c t. This value equals to the value of
   406     /// the maximum flow already after running \ref phase1.
   407     Num flowValue() const {
   408       return excess[_target];
   409     }
   410 
   411 
   412     ///Returns a minimum value cut.
   413 
   414     ///Sets \c M to the characteristic vector of a minimum value
   415     ///cut. This method can be called both after running \ref
   416     ///phase1 and \ref phase2. It is much faster after
   417     ///\ref phase1.  \pre M should be a bool-valued node-map. \pre
   418     ///If \ref minCut() is called after \ref phase2() then M should
   419     ///be initialized to false.
   420     template<typename _CutMap>
   421     void minCut(_CutMap& M) const {
   422       switch ( status ) {
   423 	case AFTER_PREFLOW_PHASE_1:
   424 	for(NodeIt v(*_g); v!=INVALID; ++v) {
   425 	  if (level[v] < _node_num) {
   426 	    M.set(v, false);
   427 	  } else {
   428 	    M.set(v, true);
   429 	  }
   430 	}
   431 	break;
   432 	case AFTER_PREFLOW_PHASE_2:
   433 	minMinCut(M);
   434 	break;
   435 	case AFTER_NOTHING:
   436 	break;
   437       }
   438     }
   439 
   440     ///Returns the inclusionwise minimum of the minimum value cuts.
   441 
   442     ///Sets \c M to the characteristic vector of the minimum value cut
   443     ///which is inclusionwise minimum. It is computed by processing a
   444     ///bfs from the source node \c s in the residual graph.  \pre M
   445     ///should be a node map of bools initialized to false.  \pre \ref
   446     ///phase2 should already be run.
   447     template<typename _CutMap>
   448     void minMinCut(_CutMap& M) const {
   449 
   450       std::queue<Node> queue;
   451       M.set(_source,true);
   452       queue.push(_source);
   453       
   454       while (!queue.empty()) {
   455 	Node w=queue.front();
   456 	queue.pop();
   457 	
   458 	for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   459 	  Node v=_g->target(e);
   460 	  if (!M[v] && _surely.positive((*_capacity)[e] -(*_flow)[e]) ) {
   461 	    queue.push(v);
   462 	    M.set(v, true);
   463 	  }
   464 	}
   465 	
   466 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   467 	  Node v=_g->source(e);
   468 	  if (!M[v] && _surely.positive((*_flow)[e]) ) {
   469 	    queue.push(v);
   470 	    M.set(v, true);
   471 	  }
   472 	}
   473       }
   474     }
   475     
   476     ///Returns the inclusionwise maximum of the minimum value cuts.
   477 
   478     ///Sets \c M to the characteristic vector of the minimum value cut
   479     ///which is inclusionwise maximum. It is computed by processing a
   480     ///backward bfs from the target node \c t in the residual graph.
   481     ///\pre \ref phase2() or run() should already be run.
   482     template<typename _CutMap>
   483     void maxMinCut(_CutMap& M) const {
   484 
   485       for(NodeIt v(*_g) ; v!=INVALID; ++v) M.set(v, true);
   486 
   487       std::queue<Node> queue;
   488 
   489       M.set(_target,false);
   490       queue.push(_target);
   491 
   492       while (!queue.empty()) {
   493         Node w=queue.front();
   494 	queue.pop();
   495 
   496 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   497 	  Node v=_g->source(e);
   498 	  if (M[v] && _surely.positive((*_capacity)[e] - (*_flow)[e]) ) {
   499 	    queue.push(v);
   500 	    M.set(v, false);
   501 	  }
   502 	}
   503 
   504 	for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   505 	  Node v=_g->target(e);
   506 	  if (M[v] && _surely.positive((*_flow)[e]) ) {
   507 	    queue.push(v);
   508 	    M.set(v, false);
   509 	  }
   510 	}
   511       }
   512     }
   513 
   514     ///Sets the source node to \c _s.
   515 
   516     ///Sets the source node to \c _s.
   517     /// 
   518     void source(Node _s) { 
   519       _source=_s; 
   520       if ( flow_prop != ZERO_FLOW ) flow_prop=NO_FLOW;
   521       status=AFTER_NOTHING; 
   522     }
   523 
   524     ///Returns the source node.
   525 
   526     ///Returns the source node.
   527     /// 
   528     Node source() const { 
   529       return _source;
   530     }
   531 
   532     ///Sets the target node to \c _t.
   533 
   534     ///Sets the target node to \c _t.
   535     ///
   536     void target(Node _t) { 
   537       _target=_t; 
   538       if ( flow_prop == GEN_FLOW ) flow_prop=PRE_FLOW;
   539       status=AFTER_NOTHING; 
   540     }
   541 
   542     ///Returns the target node.
   543 
   544     ///Returns the target node.
   545     /// 
   546     Node target() const { 
   547       return _target;
   548     }
   549 
   550     /// Sets the edge map of the capacities to _cap.
   551 
   552     /// Sets the edge map of the capacities to _cap.
   553     /// 
   554     void capacityMap(const CapacityMap& _cap) { 
   555       _capacity=&_cap; 
   556       status=AFTER_NOTHING; 
   557     }
   558     /// Returns a reference to capacity map.
   559 
   560     /// Returns a reference to capacity map.
   561     /// 
   562     const CapacityMap &capacityMap() const { 
   563       return *_capacity;
   564     }
   565 
   566     /// Sets the edge map of the flows to _flow.
   567 
   568     /// Sets the edge map of the flows to _flow.
   569     /// 
   570     void flowMap(FlowMap& _f) { 
   571       _flow=&_f; 
   572       flow_prop=NO_FLOW;
   573       status=AFTER_NOTHING; 
   574     }
   575      
   576     /// Returns a reference to flow map.
   577 
   578     /// Returns a reference to flow map.
   579     /// 
   580     const FlowMap &flowMap() const { 
   581       return *_flow;
   582     }
   583 
   584   private:
   585 
   586     int push(Node w, NNMap& next, VecNode& first) {
   587 
   588       int lev=level[w];
   589       Num exc=excess[w];
   590       int newlevel=_node_num;       //bound on the next level of w
   591 
   592       for(OutEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   593 	if ( !_surely.positive((*_capacity)[e] - (*_flow)[e])) continue;
   594 	Node v=_g->target(e);
   595 	
   596 	if( lev > level[v] ) { //Push is allowed now
   597 	  
   598 	  if ( excess[v] == 0 && v!=_target && v!=_source ) {
   599 	    next.set(v,first[level[v]]);
   600 	    first[level[v]]=v;
   601 	  }
   602 
   603 	  Num cap=(*_capacity)[e];
   604 	  Num flo=(*_flow)[e];
   605 	  Num remcap=cap-flo;
   606 	  
   607 	  if ( ! _surely.less(remcap, exc) ) { //A nonsaturating push.
   608 	    
   609 	    _flow->set(e, flo+exc);
   610 	    excess.set(v, excess[v]+exc);
   611 	    exc=0;
   612 	    break;
   613 
   614 	  } else { //A saturating push.
   615 	    _flow->set(e, cap);
   616 	    excess.set(v, excess[v]+remcap);
   617 	    exc-=remcap;
   618 	  }
   619 	} else if ( newlevel > level[v] ) newlevel = level[v];
   620       } //for out edges wv
   621 
   622       if ( exc != 0 ) {
   623 	for(InEdgeIt e(*_g,w) ; e!=INVALID; ++e) {
   624 	  
   625 	  if ( !_surely.positive((*_flow)[e]) ) continue;
   626 	  Node v=_g->source(e);
   627 	  
   628 	  if( lev > level[v] ) { //Push is allowed now
   629 
   630 	    if ( excess[v] == 0 && v!=_target && v!=_source ) {
   631 	      next.set(v,first[level[v]]);
   632 	      first[level[v]]=v;
   633 	    }
   634 
   635 	    Num flo=(*_flow)[e];
   636 
   637 	    if ( !_surely.less(flo, exc) ) { //A nonsaturating push.
   638 
   639 	      _flow->set(e, flo-exc);
   640 	      excess.set(v, excess[v]+exc);
   641 	      exc=0;
   642 	      break;
   643 	    } else {  //A saturating push.
   644 
   645 	      excess.set(v, excess[v]+flo);
   646 	      exc-=flo;
   647 	      _flow->set(e,0);
   648 	    }
   649 	  } else if ( newlevel > level[v] ) newlevel = level[v];
   650 	} //for in edges vw
   651 
   652       } // if w still has excess after the out edge for cycle
   653 
   654       excess.set(w, exc);
   655       
   656       return newlevel;
   657     }
   658     
   659     
   660     
   661     void preflowPreproc(VecNode& first, NNMap& next, 
   662 			VecNode& level_list, NNMap& left, NNMap& right)
   663     {
   664       for(NodeIt v(*_g); v!=INVALID; ++v) level.set(v,_node_num);
   665       std::queue<Node> bfs_queue;
   666       
   667       if ( flow_prop == GEN_FLOW || flow_prop == PRE_FLOW ) {
   668 	//Reverse_bfs from t in the residual graph,
   669 	//to find the starting level.
   670 	level.set(_target,0);
   671 	bfs_queue.push(_target);
   672 	
   673 	while ( !bfs_queue.empty() ) {
   674 	  
   675 	  Node v=bfs_queue.front();
   676 	  bfs_queue.pop();
   677 	  int l=level[v]+1;
   678 	  
   679 	  for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
   680 	    if ( !_surely.positive((*_capacity)[e] - (*_flow)[e] )) continue;
   681 	    Node w=_g->source(e);
   682 	    if ( level[w] == _node_num && w != _source ) {
   683 	      bfs_queue.push(w);
   684 	      Node z=level_list[l];
   685 	      if ( z!=INVALID ) left.set(z,w);
   686 	      right.set(w,z);
   687 	      level_list[l]=w;
   688 	      level.set(w, l);
   689 	    }
   690 	  }
   691 	  
   692 	  for(OutEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
   693 	    if ( !_surely.positive((*_flow)[e]) ) continue;
   694 	    Node w=_g->target(e);
   695 	    if ( level[w] == _node_num && w != _source ) {
   696 	      bfs_queue.push(w);
   697 	      Node z=level_list[l];
   698 	      if ( z!=INVALID ) left.set(z,w);
   699 	      right.set(w,z);
   700 	      level_list[l]=w;
   701 	      level.set(w, l);
   702 	    }
   703 	  }
   704 	} //while
   705       } //if
   706 
   707 
   708       switch (flow_prop) {
   709 	case NO_FLOW:  
   710 	for(EdgeIt e(*_g); e!=INVALID; ++e) _flow->set(e,0);
   711 	case ZERO_FLOW:
   712 	for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
   713 	
   714 	//Reverse_bfs from t, to find the starting level.
   715 	level.set(_target,0);
   716 	bfs_queue.push(_target);
   717 	
   718 	while ( !bfs_queue.empty() ) {
   719 	  
   720 	  Node v=bfs_queue.front();
   721 	  bfs_queue.pop();
   722 	  int l=level[v]+1;
   723 	  
   724 	  for(InEdgeIt e(*_g,v) ; e!=INVALID; ++e) {
   725 	    Node w=_g->source(e);
   726 	    if ( level[w] == _node_num && w != _source ) {
   727 	      bfs_queue.push(w);
   728 	      Node z=level_list[l];
   729 	      if ( z!=INVALID ) left.set(z,w);
   730 	      right.set(w,z);
   731 	      level_list[l]=w;
   732 	      level.set(w, l);
   733 	    }
   734 	  }
   735 	}
   736 	
   737 	//the starting flow
   738 	for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
   739 	  Num c=(*_capacity)[e];
   740 	  if ( !_surely.positive(c) ) continue;
   741 	  Node w=_g->target(e);
   742 	  if ( level[w] < _node_num ) {
   743 	    if ( excess[w] == 0 && w!=_target ) { //putting into the stack
   744 	      next.set(w,first[level[w]]);
   745 	      first[level[w]]=w;
   746 	    }
   747 	    _flow->set(e, c);
   748 	    excess.set(w, excess[w]+c);
   749 	  }
   750 	}
   751 	break;
   752 
   753 	case GEN_FLOW:
   754 	for(NodeIt v(*_g); v!=INVALID; ++v) excess.set(v,0);
   755 	{
   756 	  Num exc=0;
   757 	  for(InEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc+=(*_flow)[e];
   758 	  for(OutEdgeIt e(*_g,_target) ; e!=INVALID; ++e) exc-=(*_flow)[e];
   759           if (!_surely.positive(exc)) {
   760             exc = 0;
   761           }
   762           excess.set(_target,exc);
   763 	}
   764 
   765 	//the starting flow
   766 	for(OutEdgeIt e(*_g,_source); e!=INVALID; ++e)	{
   767 	  Num rem=(*_capacity)[e]-(*_flow)[e];
   768 	  if ( !_surely.positive(rem) ) continue;
   769 	  Node w=_g->target(e);
   770 	  if ( level[w] < _node_num ) {
   771 	    if ( excess[w] == 0 && w!=_target ) { //putting into the stack
   772 	      next.set(w,first[level[w]]);
   773 	      first[level[w]]=w;
   774 	    }   
   775 	    _flow->set(e, (*_capacity)[e]);
   776 	    excess.set(w, excess[w]+rem);
   777 	  }
   778 	}
   779 	
   780 	for(InEdgeIt e(*_g,_source); e!=INVALID; ++e) {
   781 	  if ( !_surely.positive((*_flow)[e]) ) continue;
   782 	  Node w=_g->source(e);
   783 	  if ( level[w] < _node_num ) {
   784 	    if ( excess[w] == 0 && w!=_target ) {
   785 	      next.set(w,first[level[w]]);
   786 	      first[level[w]]=w;
   787 	    }  
   788 	    excess.set(w, excess[w]+(*_flow)[e]);
   789 	    _flow->set(e, 0);
   790 	  }
   791 	}
   792 	break;
   793 
   794 	case PRE_FLOW:	
   795 	//the starting flow
   796 	for(OutEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
   797 	  Num rem=(*_capacity)[e]-(*_flow)[e];
   798 	  if ( !_surely.positive(rem) ) continue;
   799 	  Node w=_g->target(e);
   800 	  if ( level[w] < _node_num ) _flow->set(e, (*_capacity)[e]);
   801 	}
   802 	
   803 	for(InEdgeIt e(*_g,_source) ; e!=INVALID; ++e) {
   804 	  if ( !_surely.positive((*_flow)[e]) ) continue;
   805 	  Node w=_g->source(e);
   806 	  if ( level[w] < _node_num ) _flow->set(e, 0);
   807 	}
   808 	
   809 	//computing the excess
   810 	for(NodeIt w(*_g); w!=INVALID; ++w) {
   811 	  Num exc=0;
   812 	  for(InEdgeIt e(*_g,w); e!=INVALID; ++e) exc+=(*_flow)[e];
   813 	  for(OutEdgeIt e(*_g,w); e!=INVALID; ++e) exc-=(*_flow)[e];
   814           if (!_surely.positive(exc)) {
   815             exc = 0;
   816           }
   817 	  excess.set(w,exc);
   818 	  
   819 	  //putting the active nodes into the stack
   820 	  int lev=level[w];
   821 	    if ( exc != 0 && lev < _node_num && Node(w) != _target ) {
   822 	      next.set(w,first[lev]);
   823 	      first[lev]=w;
   824 	    }
   825 	}
   826 	break;
   827       } //switch
   828     } //preflowPreproc
   829 
   830 
   831     void relabel(Node w, int newlevel, VecNode& first, NNMap& next, 
   832 		 VecNode& level_list, NNMap& left,
   833 		 NNMap& right, int& b, int& k, bool what_heur )
   834     {
   835 
   836       int lev=level[w];
   837 
   838       Node right_n=right[w];
   839       Node left_n=left[w];
   840 
   841       //unlacing starts
   842       if ( right_n!=INVALID ) {
   843 	if ( left_n!=INVALID ) {
   844 	  right.set(left_n, right_n);
   845 	  left.set(right_n, left_n);
   846 	} else {
   847 	  level_list[lev]=right_n;
   848 	  left.set(right_n, INVALID);
   849 	}
   850       } else {
   851 	if ( left_n!=INVALID ) {
   852 	  right.set(left_n, INVALID);
   853 	} else {
   854 	  level_list[lev]=INVALID;
   855 	}
   856       }
   857       //unlacing ends
   858 
   859       if ( level_list[lev]==INVALID ) {
   860 
   861 	//gapping starts
   862 	for (int i=lev; i!=k ; ) {
   863 	  Node v=level_list[++i];
   864 	  while ( v!=INVALID ) {
   865 	    level.set(v,_node_num);
   866 	    v=right[v];
   867 	  }
   868 	  level_list[i]=INVALID;
   869 	  if ( !what_heur ) first[i]=INVALID;
   870 	}
   871 
   872 	level.set(w,_node_num);
   873 	b=lev-1;
   874 	k=b;
   875 	//gapping ends
   876 
   877       } else {
   878 
   879 	if ( newlevel == _node_num ) level.set(w,_node_num);
   880 	else {
   881 	  level.set(w,++newlevel);
   882 	  next.set(w,first[newlevel]);
   883 	  first[newlevel]=w;
   884 	  if ( what_heur ) b=newlevel;
   885 	  if ( k < newlevel ) ++k;      //now k=newlevel
   886 	  Node z=level_list[newlevel];
   887 	  if ( z!=INVALID ) left.set(z,w);
   888 	  right.set(w,z);
   889 	  left.set(w,INVALID);
   890 	  level_list[newlevel]=w;
   891 	}
   892       }
   893     } //relabel
   894 
   895   }; 
   896 
   897   ///\ingroup max_flow
   898   ///\brief Function type interface for Preflow algorithm.
   899   ///
   900   ///Function type interface for Preflow algorithm.
   901   ///\sa Preflow
   902   template<class GR, class CM, class FM>
   903   Preflow<GR,typename CM::Value,CM,FM> preflow(const GR &g,
   904 			    typename GR::Node source,
   905 			    typename GR::Node target,
   906 			    const CM &cap,
   907 			    FM &flow
   908 			    )
   909   {
   910     return Preflow<GR,typename CM::Value,CM,FM>(g,source,target,cap,flow);
   911   }
   912 
   913 } //namespace lemon
   914 
   915 #endif //LEMON_PREFLOW_H