marci@478: // -*- C++ -*-
marci@478: 
marci@478: /*
marci@485:   Heuristics: 
marci@485:   2 phase
marci@485:   gap
marci@485:   list 'level_list' on the nodes on level i implemented by hand
marci@485:   stack 'active' on the active nodes on level i
marci@485:   runs heuristic 'highest label' for H1*n relabels
marci@485:   runs heuristic 'bound decrease' for H0*n relabels, starts with 'highest label'
marci@478:  
marci@485:   Parameters H0 and H1 are initialized to 20 and 1.
marci@478: 
marci@485:   Constructors:
marci@478: 
marci@485:   Preflow(Graph, Node, Node, CapMap, FlowMap, bool) : bool must be false if 
marci@485:   FlowMap is not constant zero, and should be true if it is
marci@478: 
marci@485:   Members:
marci@478: 
marci@485:   void run()
marci@478: 
marci@485:   Num flowValue() : returns the value of a maximum flow
marci@478: 
marci@485:   void minMinCut(CutMap& M) : sets M to the characteristic vector of the 
marci@485:   minimum min cut. M should be a map of bools initialized to false. ??Is it OK?
marci@478: 
marci@485:   void maxMinCut(CutMap& M) : sets M to the characteristic vector of the 
marci@485:   maximum min cut. M should be a map of bools initialized to false.
marci@478: 
marci@485:   void minCut(CutMap& M) : sets M to the characteristic vector of 
marci@485:   a min cut. M should be a map of bools initialized to false.
marci@478: 
marci@478: */
marci@478: 
marci@480: #ifndef HUGO_MAX_FLOW_H
marci@480: #define HUGO_MAX_FLOW_H
marci@478: 
marci@478: #define H0 20
marci@478: #define H1 1
marci@478: 
marci@478: #include <vector>
marci@478: #include <queue>
marci@478: #include <stack>
marci@478: 
marci@478: #include <graph_wrapper.h>
marci@478: #include <bfs_iterator.h>
marci@478: #include <invalid.h>
marci@478: #include <maps.h>
marci@478: #include <for_each_macros.h>
marci@478: 
marci@488: /// \file
marci@488: /// \brief Dimacs file format reader.
marci@478: 
marci@478: namespace hugo {
marci@478: 
marci@488: 
marci@488: //  ///\author Marton Makai, Jacint Szabo
marci@488:   /// A class for computing max flows and related quantities.
marci@478:   template <typename Graph, typename Num, 
marci@478: 	    typename CapMap=typename Graph::template EdgeMap<Num>, 
marci@478:             typename FlowMap=typename Graph::template EdgeMap<Num> >
marci@478:   class MaxFlow {
marci@478:     
marci@478:     typedef typename Graph::Node Node;
marci@478:     typedef typename Graph::NodeIt NodeIt;
marci@478:     typedef typename Graph::OutEdgeIt OutEdgeIt;
marci@478:     typedef typename Graph::InEdgeIt InEdgeIt;
marci@478: 
marci@478:     typedef typename std::vector<std::stack<Node> > VecStack;
marci@478:     typedef typename Graph::template NodeMap<Node> NNMap;
marci@478:     typedef typename std::vector<Node> VecNode;
marci@478: 
marci@478:     const Graph* g;
marci@478:     Node s;
marci@478:     Node t;
marci@478:     const CapMap* capacity;  
marci@478:     FlowMap* flow;
marci@478:     int n;      //the number of nodes of G
marci@478:     typedef ResGraphWrapper<const Graph, Num, CapMap, FlowMap> ResGW;
marci@478:     typedef typename ResGW::OutEdgeIt ResGWOutEdgeIt;
marci@478:     typedef typename ResGW::Edge ResGWEdge;
marci@478:     //typedef typename ResGW::template NodeMap<bool> ReachedMap;
marci@478:     typedef typename Graph::template NodeMap<int> ReachedMap;
marci@478:     ReachedMap level;
marci@478:     //level works as a bool map in augmenting path algorithms 
marci@478:     //and is used by bfs for storing reached information.
marci@478:     //In preflow, it shows levels of nodes.
marci@478:     //typename Graph::template NodeMap<int> level;    
marci@478:     typename Graph::template NodeMap<Num> excess; 
marci@478: 
marci@478:   public:
marci@478:  
marci@487:     ///\todo Document this
marci@478:     enum flowEnum{
marci@478:       ZERO_FLOW=0,
marci@478:       GEN_FLOW=1,
marci@478:       PREFLOW=2
marci@478:     };
marci@478: 
marci@478:     MaxFlow(const Graph& _G, Node _s, Node _t, const CapMap& _capacity, 
marci@478: 	    FlowMap& _flow) :
marci@478:       g(&_G), s(_s), t(_t), capacity(&_capacity), 
marci@478:       flow(&_flow), n(_G.nodeNum()), level(_G), excess(_G,0) {}
marci@478: 
marci@485:     /// A max flow algorithm is run.
marci@485:     ///\pre the flow have to be 0 at the beginning.
marci@478:     void run() {
marci@488:       preflow(ZERO_FLOW);
marci@478:     }
marci@478:     
marci@487:     /// A preflow algorithm is run. 
marci@487:     ///\pre The initial edge-map have to be a 
marci@487:     /// zero flow if \c fe is \c ZERO_FLOW,
marci@487:     /// a flow if \c fe is \c GEN_FLOW, 
marci@487:     /// and a pre-flow it is \c PREFLOW.
marci@488:     void preflow(flowEnum fe) {
marci@478:       preflowPhase0(fe);
marci@478:       preflowPhase1();
marci@478:     }
marci@478: 
marci@485:     /// Run the first phase of preflow, starting from a 0 flow, from a flow, 
marci@485:     /// or from a preflow, according to \c fe.
marci@478:     void preflowPhase0( flowEnum fe );
marci@478: 
marci@485:     /// Second phase of preflow.
marci@478:     void preflowPhase1();
marci@478: 
marci@485:     /// Starting from a flow, this method searches for an augmenting path 
marci@485:     /// according to the Edmonds-Karp algorithm 
marci@485:     /// and augments the flow on if any. 
marci@487:     /// The return value shows if the augmentation was succesful.
marci@478:     bool augmentOnShortestPath();
marci@478: 
marci@485:     /// Starting from a flow, this method searches for an augmenting blockin 
marci@485:     /// flow according to Dinits' algorithm and augments the flow on if any. 
marci@485:     /// The blocking flow is computed in a physically constructed 
marci@485:     /// residual graph of type \c Mutablegraph.
marci@487:     /// The return value show sif the augmentation was succesful.
marci@478:     template<typename MutableGraph> bool augmentOnBlockingFlow();
marci@478: 
marci@485:     /// The same as \c augmentOnBlockingFlow<MutableGraph> but the 
marci@485:     /// residual graph is not constructed physically.
marci@487:     /// The return value shows if the augmentation was succesful.
marci@478:     bool augmentOnBlockingFlow2();
marci@478: 
marci@478:     /// Returns the actual flow value.
marci@478:     /// More precisely, it returns the negative excess of s, thus 
marci@478:     /// this works also for preflows.
marci@478:     Num flowValue() { 
marci@478:       Num a=0;
marci@478:       FOR_EACH_INC_LOC(OutEdgeIt, e, *g, s) a+=(*flow)[e];
marci@478:       FOR_EACH_INC_LOC(InEdgeIt, e, *g, s) a-=(*flow)[e];
marci@478:       return a;
marci@478:     }
marci@478: 
marci@485:     /// Should be used between preflowPhase0 and preflowPhase1.
marci@485:     ///\todo We have to make some status variable which shows the actual state 
marci@485:     /// of the class. This enables us to determine which methods are valid 
marci@485:     /// for MinCut computation
marci@478:     template<typename _CutMap>
marci@478:     void actMinCut(_CutMap& M) {
marci@478:       NodeIt v;
marci@485:       for(g->first(v); g->valid(v); g->next(v)) {
marci@485: 	if ( level[v] < n ) {
marci@485: 	  M.set(v,false);
marci@485: 	} else {
marci@485: 	  M.set(v,true);
marci@485: 	}
marci@478:       }
marci@478:     }
marci@478: 
marci@485:     /// The unique inclusionwise minimum cut is computed by 
marci@485:     /// processing a bfs from s in the residual graph.
marci@485:     ///\pre flow have to be a max flow otherwise it will the whole node-set.
marci@478:     template<typename _CutMap>
marci@478:     void minMinCut(_CutMap& M) {
marci@478:     
marci@478:       std::queue<Node> queue;
marci@478:       
marci@478:       M.set(s,true);      
marci@478:       queue.push(s);
marci@478: 
marci@478:       while (!queue.empty()) {
marci@478:         Node w=queue.front();
marci@478: 	queue.pop();
marci@478: 
marci@478: 	OutEdgeIt e;
marci@478: 	for(g->first(e,w) ; g->valid(e); g->next(e)) {
marci@478: 	  Node v=g->head(e);
marci@478: 	  if (!M[v] && (*flow)[e] < (*capacity)[e] ) {
marci@478: 	    queue.push(v);
marci@478: 	    M.set(v, true);
marci@478: 	  }
marci@478: 	} 
marci@478: 
marci@478: 	InEdgeIt f;
marci@478: 	for(g->first(f,w) ; g->valid(f); g->next(f)) {
marci@478: 	  Node v=g->tail(f);
marci@478: 	  if (!M[v] && (*flow)[f] > 0 ) {
marci@478: 	    queue.push(v);
marci@478: 	    M.set(v, true);
marci@478: 	  }
marci@478: 	} 
marci@478:       }
marci@478:     }
marci@478: 
marci@478: 
marci@485:     /// The unique inclusionwise maximum cut is computed by 
marci@485:     /// processing a reverse bfs from t in the residual graph.
marci@485:     ///\pre flow have to be a max flow otherwise it will be empty.
marci@478:     template<typename _CutMap>
marci@478:     void maxMinCut(_CutMap& M) {
marci@478: 
marci@478:       NodeIt v;
marci@478:       for(g->first(v) ; g->valid(v); g->next(v)) {
marci@478: 	M.set(v, true);
marci@478:       }
marci@478: 
marci@478:       std::queue<Node> queue;
marci@478:       
marci@478:       M.set(t,false);        
marci@478:       queue.push(t);
marci@478: 
marci@478:       while (!queue.empty()) {
marci@478:         Node w=queue.front();
marci@478: 	queue.pop();
marci@478: 
marci@478: 
marci@478: 	InEdgeIt e;
marci@478: 	for(g->first(e,w) ; g->valid(e); g->next(e)) {
marci@478: 	  Node v=g->tail(e);
marci@478: 	  if (M[v] && (*flow)[e] < (*capacity)[e] ) {
marci@478: 	    queue.push(v);
marci@478: 	    M.set(v, false);
marci@478: 	  }
marci@478: 	}
marci@478: 	
marci@478: 	OutEdgeIt f;
marci@478: 	for(g->first(f,w) ; g->valid(f); g->next(f)) {
marci@478: 	  Node v=g->head(f);
marci@478: 	  if (M[v] && (*flow)[f] > 0 ) {
marci@478: 	    queue.push(v);
marci@478: 	    M.set(v, false);
marci@478: 	  }
marci@478: 	}
marci@478:       }
marci@478:     }
marci@478: 
marci@478: 
marci@485:     /// A minimum cut is computed.
marci@478:     template<typename CutMap>
marci@485:     void minCut(CutMap& M) { minMinCut(M); }
marci@478: 
marci@485:     ///
marci@487:     void resetSource(Node _s) { s=_s; }
marci@487:     ///
marci@487:     void resetTarget(Node _t) { t=_t; }
marci@478:    
marci@485:     /// capacity-map is changed.
marci@485:     void resetCap(const CapMap& _cap) { capacity=&_cap; }
marci@478:     
marci@485:     /// flow-map is changed. 
marci@485:     void resetFlow(FlowMap& _flow) { flow=&_flow; }
marci@478: 
marci@478: 
marci@478:   private:
marci@478: 
marci@478:     int push(Node w, VecStack& active) {
marci@478:       
marci@478:       int lev=level[w];
marci@478:       Num exc=excess[w];
marci@478:       int newlevel=n;       //bound on the next level of w
marci@478: 	  
marci@478:       OutEdgeIt e;
marci@478:       for(g->first(e,w); g->valid(e); g->next(e)) {
marci@478: 	    
marci@478: 	if ( (*flow)[e] >= (*capacity)[e] ) continue; 
marci@478: 	Node v=g->head(e);            
marci@478: 	    
marci@478: 	if( lev > level[v] ) { //Push is allowed now
marci@478: 	  
marci@478: 	  if ( excess[v]<=0 && v!=t && v!=s ) {
marci@478: 	    int lev_v=level[v];
marci@478: 	    active[lev_v].push(v);
marci@478: 	  }
marci@478: 	  
marci@478: 	  Num cap=(*capacity)[e];
marci@478: 	  Num flo=(*flow)[e];
marci@478: 	  Num remcap=cap-flo;
marci@478: 	  
marci@478: 	  if ( remcap >= exc ) { //A nonsaturating push.
marci@478: 	    
marci@478: 	    flow->set(e, flo+exc);
marci@478: 	    excess.set(v, excess[v]+exc);
marci@478: 	    exc=0;
marci@478: 	    break; 
marci@478: 	    
marci@478: 	  } else { //A saturating push.
marci@478: 	    flow->set(e, cap);
marci@478: 	    excess.set(v, excess[v]+remcap);
marci@478: 	    exc-=remcap;
marci@478: 	  }
marci@478: 	} else if ( newlevel > level[v] ) newlevel = level[v];
marci@478:       } //for out edges wv 
marci@478:       
marci@478:       if ( exc > 0 ) {	
marci@478: 	InEdgeIt e;
marci@478: 	for(g->first(e,w); g->valid(e); g->next(e)) {
marci@478: 	  
marci@478: 	  if( (*flow)[e] <= 0 ) continue; 
marci@478: 	  Node v=g->tail(e); 
marci@478: 	  
marci@478: 	  if( lev > level[v] ) { //Push is allowed now
marci@478: 	    
marci@478: 	    if ( excess[v]<=0 && v!=t && v!=s ) {
marci@478: 	      int lev_v=level[v];
marci@478: 	      active[lev_v].push(v);
marci@478: 	    }
marci@478: 	    
marci@478: 	    Num flo=(*flow)[e];
marci@478: 	    
marci@478: 	    if ( flo >= exc ) { //A nonsaturating push.
marci@478: 	      
marci@478: 	      flow->set(e, flo-exc);
marci@478: 	      excess.set(v, excess[v]+exc);
marci@478: 	      exc=0;
marci@478: 	      break; 
marci@478: 	    } else {  //A saturating push.
marci@478: 	      
marci@478: 	      excess.set(v, excess[v]+flo);
marci@478: 	      exc-=flo;
marci@478: 	      flow->set(e,0);
marci@478: 	    }  
marci@478: 	  } else if ( newlevel > level[v] ) newlevel = level[v];
marci@478: 	} //for in edges vw
marci@478: 	
marci@478:       } // if w still has excess after the out edge for cycle
marci@478:       
marci@478:       excess.set(w, exc);
marci@478:       
marci@478:       return newlevel;
marci@485:     }
marci@478: 
marci@478: 
marci@478:     void preflowPreproc ( flowEnum fe, VecStack& active, 
marci@478: 			  VecNode& level_list, NNMap& left, NNMap& right ) {
marci@478: 
marci@485: 			    std::queue<Node> bfs_queue;
marci@478:       
marci@485: 			    switch ( fe ) {
marci@485: 			    case ZERO_FLOW: 
marci@485: 			      {
marci@485: 				//Reverse_bfs from t, to find the starting level.
marci@485: 				level.set(t,0);
marci@485: 				bfs_queue.push(t);
marci@478: 	
marci@485: 				while (!bfs_queue.empty()) {
marci@478: 	    
marci@485: 				  Node v=bfs_queue.front();	
marci@485: 				  bfs_queue.pop();
marci@485: 				  int l=level[v]+1;
marci@478: 	    
marci@485: 				  InEdgeIt e;
marci@485: 				  for(g->first(e,v); g->valid(e); g->next(e)) {
marci@485: 				    Node w=g->tail(e);
marci@485: 				    if ( level[w] == n && w != s ) {
marci@485: 				      bfs_queue.push(w);
marci@485: 				      Node first=level_list[l];
marci@485: 				      if ( g->valid(first) ) left.set(first,w);
marci@485: 				      right.set(w,first);
marci@485: 				      level_list[l]=w;
marci@485: 				      level.set(w, l);
marci@485: 				    }
marci@485: 				  }
marci@485: 				}
marci@478: 	  
marci@485: 				//the starting flow
marci@485: 				OutEdgeIt e;
marci@485: 				for(g->first(e,s); g->valid(e); g->next(e)) 
marci@485: 				  {
marci@485: 				    Num c=(*capacity)[e];
marci@485: 				    if ( c <= 0 ) continue;
marci@485: 				    Node w=g->head(e);
marci@485: 				    if ( level[w] < n ) {	  
marci@485: 				      if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
marci@485: 				      flow->set(e, c); 
marci@485: 				      excess.set(w, excess[w]+c);
marci@485: 				    }
marci@485: 				  }
marci@485: 				break;
marci@485: 			      }
marci@478: 	
marci@485: 			    case GEN_FLOW:
marci@485: 			    case PREFLOW:
marci@485: 			      {
marci@485: 				//Reverse_bfs from t in the residual graph, 
marci@485: 				//to find the starting level.
marci@485: 				level.set(t,0);
marci@485: 				bfs_queue.push(t);
marci@478: 	  
marci@485: 				while (!bfs_queue.empty()) {
marci@478: 	    
marci@485: 				  Node v=bfs_queue.front();	
marci@485: 				  bfs_queue.pop();
marci@485: 				  int l=level[v]+1;
marci@478: 	    
marci@485: 				  InEdgeIt e;
marci@485: 				  for(g->first(e,v); g->valid(e); g->next(e)) {
marci@485: 				    if ( (*capacity)[e] <= (*flow)[e] ) continue;
marci@485: 				    Node w=g->tail(e);
marci@485: 				    if ( level[w] == n && w != s ) {
marci@485: 				      bfs_queue.push(w);
marci@485: 				      Node first=level_list[l];
marci@485: 				      if ( g->valid(first) ) left.set(first,w);
marci@485: 				      right.set(w,first);
marci@485: 				      level_list[l]=w;
marci@485: 				      level.set(w, l);
marci@485: 				    }
marci@485: 				  }
marci@478: 	    
marci@485: 				  OutEdgeIt f;
marci@485: 				  for(g->first(f,v); g->valid(f); g->next(f)) {
marci@485: 				    if ( 0 >= (*flow)[f] ) continue;
marci@485: 				    Node w=g->head(f);
marci@485: 				    if ( level[w] == n && w != s ) {
marci@485: 				      bfs_queue.push(w);
marci@485: 				      Node first=level_list[l];
marci@485: 				      if ( g->valid(first) ) left.set(first,w);
marci@485: 				      right.set(w,first);
marci@485: 				      level_list[l]=w;
marci@485: 				      level.set(w, l);
marci@485: 				    }
marci@485: 				  }
marci@485: 				}
marci@478: 	  
marci@478: 	  
marci@485: 				//the starting flow
marci@485: 				OutEdgeIt e;
marci@485: 				for(g->first(e,s); g->valid(e); g->next(e)) 
marci@485: 				  {
marci@485: 				    Num rem=(*capacity)[e]-(*flow)[e];
marci@485: 				    if ( rem <= 0 ) continue;
marci@485: 				    Node w=g->head(e);
marci@485: 				    if ( level[w] < n ) {	  
marci@485: 				      if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
marci@485: 				      flow->set(e, (*capacity)[e]); 
marci@485: 				      excess.set(w, excess[w]+rem);
marci@485: 				    }
marci@485: 				  }
marci@478: 	  
marci@485: 				InEdgeIt f;
marci@485: 				for(g->first(f,s); g->valid(f); g->next(f)) 
marci@485: 				  {
marci@485: 				    if ( (*flow)[f] <= 0 ) continue;
marci@485: 				    Node w=g->tail(f);
marci@485: 				    if ( level[w] < n ) {	  
marci@485: 				      if ( excess[w] <= 0 && w!=t ) active[level[w]].push(w);
marci@485: 				      excess.set(w, excess[w]+(*flow)[f]);
marci@485: 				      flow->set(f, 0); 
marci@485: 				    }
marci@485: 				  }  
marci@485: 				break;
marci@485: 			      } //case PREFLOW
marci@485: 			    }
marci@485: 			  } //preflowPreproc
marci@478: 
marci@478: 
marci@478: 
marci@478:     void relabel(Node w, int newlevel, VecStack& active,  
marci@478: 		 VecNode& level_list, NNMap& left, 
marci@478: 		 NNMap& right, int& b, int& k, bool what_heur ) 
marci@478:     {
marci@478: 
marci@478:       Num lev=level[w];	
marci@478:       
marci@478:       Node right_n=right[w];
marci@478:       Node left_n=left[w];
marci@478:       
marci@478:       //unlacing starts
marci@478:       if ( g->valid(right_n) ) {
marci@478: 	if ( g->valid(left_n) ) {
marci@478: 	  right.set(left_n, right_n);
marci@478: 	  left.set(right_n, left_n);
marci@478: 	} else {
marci@478: 	  level_list[lev]=right_n;   
marci@478: 	  left.set(right_n, INVALID);
marci@478: 	} 
marci@478:       } else {
marci@478: 	if ( g->valid(left_n) ) {
marci@478: 	  right.set(left_n, INVALID);
marci@478: 	} else { 
marci@478: 	  level_list[lev]=INVALID;   
marci@478: 	} 
marci@478:       } 
marci@478:       //unlacing ends
marci@478: 		
marci@478:       if ( !g->valid(level_list[lev]) ) {
marci@478: 	      
marci@478: 	//gapping starts
marci@478: 	for (int i=lev; i!=k ; ) {
marci@478: 	  Node v=level_list[++i];
marci@478: 	  while ( g->valid(v) ) {
marci@478: 	    level.set(v,n);
marci@478: 	    v=right[v];
marci@478: 	  }
marci@478: 	  level_list[i]=INVALID;
marci@478: 	  if ( !what_heur ) {
marci@478: 	    while ( !active[i].empty() ) {
marci@478: 	      active[i].pop();    //FIXME: ezt szebben kene
marci@478: 	    }
marci@478: 	  }	     
marci@478: 	}
marci@478: 	
marci@478: 	level.set(w,n);
marci@478: 	b=lev-1;
marci@478: 	k=b;
marci@478: 	//gapping ends
marci@478: 	
marci@478:       } else {
marci@478: 	
marci@478: 	if ( newlevel == n ) level.set(w,n); 
marci@478: 	else {
marci@478: 	  level.set(w,++newlevel);
marci@478: 	  active[newlevel].push(w);
marci@478: 	  if ( what_heur ) b=newlevel;
marci@478: 	  if ( k < newlevel ) ++k;      //now k=newlevel
marci@478: 	  Node first=level_list[newlevel];
marci@478: 	  if ( g->valid(first) ) left.set(first,w);
marci@478: 	  right.set(w,first);
marci@478: 	  left.set(w,INVALID);
marci@478: 	  level_list[newlevel]=w;
marci@478: 	}
marci@478:       }
marci@478:       
marci@478:     } //relabel
marci@478: 
marci@478: 
marci@478:     template<typename MapGraphWrapper> 
marci@478:     class DistanceMap {
marci@478:     protected:
marci@478:       const MapGraphWrapper* g;
marci@478:       typename MapGraphWrapper::template NodeMap<int> dist; 
marci@478:     public:
marci@478:       DistanceMap(MapGraphWrapper& _g) : g(&_g), dist(*g, g->nodeNum()) { }
marci@478:       void set(const typename MapGraphWrapper::Node& n, int a) { 
marci@478: 	dist.set(n, a); 
marci@478:       }
marci@478:       int operator[](const typename MapGraphWrapper::Node& n) 
marci@485:       { return dist[n]; }
marci@485:       //       int get(const typename MapGraphWrapper::Node& n) const { 
marci@485:       // 	return dist[n]; }
marci@485:       //       bool get(const typename MapGraphWrapper::Edge& e) const { 
marci@485:       // 	return (dist.get(g->tail(e))<dist.get(g->head(e))); }
marci@478:       bool operator[](const typename MapGraphWrapper::Edge& e) const { 
marci@478: 	return (dist[g->tail(e)]<dist[g->head(e)]); 
marci@478:       }
marci@478:     };
marci@478:     
marci@478:   };
marci@478: 
marci@478: 
marci@478:   template <typename Graph, typename Num, typename CapMap, typename FlowMap>
marci@478:   void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase0( flowEnum fe ) 
marci@478:   {
marci@478:       
marci@485:     int heur0=(int)(H0*n);  //time while running 'bound decrease' 
marci@485:     int heur1=(int)(H1*n);  //time while running 'highest label'
marci@485:     int heur=heur1;         //starting time interval (#of relabels)
marci@485:     int numrelabel=0;
marci@478:      
marci@485:     bool what_heur=1;       
marci@485:     //It is 0 in case 'bound decrease' and 1 in case 'highest label'
marci@478: 
marci@485:     bool end=false;     
marci@485:     //Needed for 'bound decrease', true means no active nodes are above bound b.
marci@478: 
marci@485:     int k=n-2;  //bound on the highest level under n containing a node
marci@485:     int b=k;    //bound on the highest level under n of an active node
marci@478:       
marci@485:     VecStack active(n);
marci@478:       
marci@485:     NNMap left(*g, INVALID);
marci@485:     NNMap right(*g, INVALID);
marci@485:     VecNode level_list(n,INVALID);
marci@485:     //List of the nodes in level i<n, set to n.
marci@478: 
marci@485:     NodeIt v;
marci@485:     for(g->first(v); g->valid(v); g->next(v)) level.set(v,n);
marci@485:     //setting each node to level n
marci@478:       
marci@485:     switch ( fe ) {
marci@485:     case PREFLOW:
marci@485:       {
marci@485: 	//counting the excess
marci@485: 	NodeIt v;
marci@485: 	for(g->first(v); g->valid(v); g->next(v)) {
marci@478: 	  Num exc=0;
marci@478: 	  
marci@478: 	  InEdgeIt e;
marci@485: 	  for(g->first(e,v); g->valid(e); g->next(e)) exc+=(*flow)[e];
marci@478: 	  OutEdgeIt f;
marci@485: 	  for(g->first(f,v); g->valid(f); g->next(f)) exc-=(*flow)[f];
marci@485: 	    
marci@485: 	  excess.set(v,exc);	  
marci@485: 	    
marci@485: 	  //putting the active nodes into the stack
marci@485: 	  int lev=level[v];
marci@485: 	  if ( exc > 0 && lev < n && v != t ) active[lev].push(v);
marci@478: 	}
marci@478: 	break;
marci@478:       }
marci@485:     case GEN_FLOW:
marci@485:       {
marci@485: 	//Counting the excess of t
marci@485: 	Num exc=0;
marci@485: 	  
marci@485: 	InEdgeIt e;
marci@485: 	for(g->first(e,t); g->valid(e); g->next(e)) exc+=(*flow)[e];
marci@485: 	OutEdgeIt f;
marci@485: 	for(g->first(f,t); g->valid(f); g->next(f)) exc-=(*flow)[f];
marci@485: 	  
marci@485: 	excess.set(t,exc);	
marci@485: 	  
marci@485: 	break;
marci@485:       }
marci@485:     default:
marci@485:       break;
marci@485:     }
marci@478:       
marci@485:     preflowPreproc( fe, active, level_list, left, right );
marci@485:     //End of preprocessing 
marci@478:       
marci@478:       
marci@485:     //Push/relabel on the highest level active nodes.
marci@485:     while ( true ) {
marci@485:       if ( b == 0 ) {
marci@485: 	if ( !what_heur && !end && k > 0 ) {
marci@485: 	  b=k;
marci@485: 	  end=true;
marci@485: 	} else break;
marci@485:       }
marci@485: 	
marci@485:       if ( active[b].empty() ) --b; 
marci@485:       else {
marci@485: 	end=false;  
marci@485: 	Node w=active[b].top();
marci@485: 	active[b].pop();
marci@485: 	int newlevel=push(w,active);
marci@485: 	if ( excess[w] > 0 ) relabel(w, newlevel, active, level_list, 
marci@485: 				     left, right, b, k, what_heur);
marci@485: 	  
marci@485: 	++numrelabel; 
marci@485: 	if ( numrelabel >= heur ) {
marci@485: 	  numrelabel=0;
marci@485: 	  if ( what_heur ) {
marci@485: 	    what_heur=0;
marci@485: 	    heur=heur0;
marci@485: 	    end=false;
marci@485: 	  } else {
marci@485: 	    what_heur=1;
marci@485: 	    heur=heur1;
marci@485: 	    b=k; 
marci@485: 	  }
marci@478: 	}
marci@478:       } 
marci@485:     } 
marci@485:   }
marci@478: 
marci@478: 
marci@478: 
marci@478:   template <typename Graph, typename Num, typename CapMap, typename FlowMap>
marci@478:   void MaxFlow<Graph, Num, CapMap, FlowMap>::preflowPhase1() 
marci@478:   {
marci@478:       
marci@485:     int k=n-2;  //bound on the highest level under n containing a node
marci@485:     int b=k;    //bound on the highest level under n of an active node
marci@478:       
marci@485:     VecStack active(n);
marci@485:     level.set(s,0);
marci@485:     std::queue<Node> bfs_queue;
marci@485:     bfs_queue.push(s);
marci@478: 	    
marci@485:     while (!bfs_queue.empty()) {
marci@478: 	
marci@485:       Node v=bfs_queue.front();	
marci@485:       bfs_queue.pop();
marci@485:       int l=level[v]+1;
marci@478: 	      
marci@485:       InEdgeIt e;
marci@485:       for(g->first(e,v); g->valid(e); g->next(e)) {
marci@485: 	if ( (*capacity)[e] <= (*flow)[e] ) continue;
marci@485: 	Node u=g->tail(e);
marci@485: 	if ( level[u] >= n ) { 
marci@485: 	  bfs_queue.push(u);
marci@485: 	  level.set(u, l);
marci@485: 	  if ( excess[u] > 0 ) active[l].push(u);
marci@478: 	}
marci@478:       }
marci@485: 	
marci@485:       OutEdgeIt f;
marci@485:       for(g->first(f,v); g->valid(f); g->next(f)) {
marci@485: 	if ( 0 >= (*flow)[f] ) continue;
marci@485: 	Node u=g->head(f);
marci@485: 	if ( level[u] >= n ) { 
marci@485: 	  bfs_queue.push(u);
marci@485: 	  level.set(u, l);
marci@485: 	  if ( excess[u] > 0 ) active[l].push(u);
marci@485: 	}
marci@485:       }
marci@485:     }
marci@485:     b=n-2;
marci@478: 
marci@485:     while ( true ) {
marci@478: 	
marci@485:       if ( b == 0 ) break;
marci@478: 
marci@485:       if ( active[b].empty() ) --b; 
marci@485:       else {
marci@485: 	Node w=active[b].top();
marci@485: 	active[b].pop();
marci@485: 	int newlevel=push(w,active);	  
marci@478: 
marci@485: 	//relabel
marci@485: 	if ( excess[w] > 0 ) {
marci@485: 	  level.set(w,++newlevel);
marci@485: 	  active[newlevel].push(w);
marci@485: 	  b=newlevel;
marci@485: 	}
marci@485:       }  // if stack[b] is nonempty
marci@485:     } // while(true)
marci@485:   }
marci@478: 
marci@478: 
marci@478: 
marci@478:   template <typename Graph, typename Num, typename CapMap, typename FlowMap>
marci@478:   bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnShortestPath() 
marci@478:   {
marci@485:     ResGW res_graph(*g, *capacity, *flow);
marci@485:     bool _augment=false;
marci@478:       
marci@485:     //ReachedMap level(res_graph);
marci@485:     FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
marci@485:     BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
marci@485:     bfs.pushAndSetReached(s);
marci@478: 	
marci@485:     typename ResGW::template NodeMap<ResGWEdge> pred(res_graph); 
marci@485:     pred.set(s, INVALID);
marci@478:       
marci@485:     typename ResGW::template NodeMap<Num> free(res_graph);
marci@478: 	
marci@485:     //searching for augmenting path
marci@485:     while ( !bfs.finished() ) { 
marci@485:       ResGWOutEdgeIt e=bfs;
marci@485:       if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
marci@485: 	Node v=res_graph.tail(e);
marci@485: 	Node w=res_graph.head(e);
marci@485: 	pred.set(w, e);
marci@485: 	if (res_graph.valid(pred[v])) {
marci@485: 	  free.set(w, std::min(free[v], res_graph.resCap(e)));
marci@485: 	} else {
marci@485: 	  free.set(w, res_graph.resCap(e)); 
marci@478: 	}
marci@485: 	if (res_graph.head(e)==t) { _augment=true; break; }
marci@485:       }
marci@478: 	
marci@485:       ++bfs;
marci@485:     } //end of searching augmenting path
marci@478: 
marci@485:     if (_augment) {
marci@485:       Node n=t;
marci@485:       Num augment_value=free[t];
marci@485:       while (res_graph.valid(pred[n])) { 
marci@485: 	ResGWEdge e=pred[n];
marci@485: 	res_graph.augment(e, augment_value); 
marci@485: 	n=res_graph.tail(e);
marci@478:       }
marci@485:     }
marci@478: 
marci@485:     return _augment;
marci@485:   }
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478:   template <typename Graph, typename Num, typename CapMap, typename FlowMap>
marci@478:   template<typename MutableGraph> 
marci@478:   bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow() 
marci@478:   {      
marci@485:     typedef MutableGraph MG;
marci@485:     bool _augment=false;
marci@478: 
marci@485:     ResGW res_graph(*g, *capacity, *flow);
marci@478: 
marci@485:     //bfs for distances on the residual graph
marci@485:     //ReachedMap level(res_graph);
marci@485:     FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
marci@485:     BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
marci@485:     bfs.pushAndSetReached(s);
marci@485:     typename ResGW::template NodeMap<int> 
marci@485:       dist(res_graph); //filled up with 0's
marci@478: 
marci@485:     //F will contain the physical copy of the residual graph
marci@485:     //with the set of edges which are on shortest paths
marci@485:     MG F;
marci@485:     typename ResGW::template NodeMap<typename MG::Node> 
marci@485:       res_graph_to_F(res_graph);
marci@485:     {
marci@485:       typename ResGW::NodeIt n;
marci@485:       for(res_graph.first(n); res_graph.valid(n); res_graph.next(n)) {
marci@485: 	res_graph_to_F.set(n, F.addNode());
marci@478:       }
marci@485:     }
marci@478: 
marci@485:     typename MG::Node sF=res_graph_to_F[s];
marci@485:     typename MG::Node tF=res_graph_to_F[t];
marci@485:     typename MG::template EdgeMap<ResGWEdge> original_edge(F);
marci@485:     typename MG::template EdgeMap<Num> residual_capacity(F);
marci@478: 
marci@485:     while ( !bfs.finished() ) { 
marci@485:       ResGWOutEdgeIt e=bfs;
marci@485:       if (res_graph.valid(e)) {
marci@485: 	if (bfs.isBNodeNewlyReached()) {
marci@485: 	  dist.set(res_graph.head(e), dist[res_graph.tail(e)]+1);
marci@485: 	  typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)], res_graph_to_F[res_graph.head(e)]);
marci@485: 	  original_edge.update();
marci@485: 	  original_edge.set(f, e);
marci@485: 	  residual_capacity.update();
marci@485: 	  residual_capacity.set(f, res_graph.resCap(e));
marci@485: 	} else {
marci@485: 	  if (dist[res_graph.head(e)]==(dist[res_graph.tail(e)]+1)) {
marci@478: 	    typename MG::Edge f=F.addEdge(res_graph_to_F[res_graph.tail(e)], res_graph_to_F[res_graph.head(e)]);
marci@478: 	    original_edge.update();
marci@478: 	    original_edge.set(f, e);
marci@478: 	    residual_capacity.update();
marci@478: 	    residual_capacity.set(f, res_graph.resCap(e));
marci@478: 	  }
marci@478: 	}
marci@485:       }
marci@485:       ++bfs;
marci@485:     } //computing distances from s in the residual graph
marci@478: 
marci@485:     bool __augment=true;
marci@478: 
marci@485:     while (__augment) {
marci@485:       __augment=false;
marci@485:       //computing blocking flow with dfs
marci@485:       DfsIterator< MG, typename MG::template NodeMap<bool> > dfs(F);
marci@485:       typename MG::template NodeMap<typename MG::Edge> pred(F);
marci@485:       pred.set(sF, INVALID);
marci@485:       //invalid iterators for sources
marci@478: 
marci@485:       typename MG::template NodeMap<Num> free(F);
marci@478: 
marci@485:       dfs.pushAndSetReached(sF);      
marci@485:       while (!dfs.finished()) {
marci@485: 	++dfs;
marci@485: 	if (F.valid(/*typename MG::OutEdgeIt*/(dfs))) {
marci@485: 	  if (dfs.isBNodeNewlyReached()) {
marci@485: 	    typename MG::Node v=F.aNode(dfs);
marci@485: 	    typename MG::Node w=F.bNode(dfs);
marci@485: 	    pred.set(w, dfs);
marci@485: 	    if (F.valid(pred[v])) {
marci@485: 	      free.set(w, std::min(free[v], residual_capacity[dfs]));
marci@485: 	    } else {
marci@485: 	      free.set(w, residual_capacity[dfs]); 
marci@485: 	    }
marci@485: 	    if (w==tF) { 
marci@485: 	      __augment=true; 
marci@485: 	      _augment=true;
marci@485: 	      break; 
marci@485: 	    }
marci@478: 	      
marci@485: 	  } else {
marci@485: 	    F.erase(/*typename MG::OutEdgeIt*/(dfs));
marci@485: 	  }
marci@485: 	} 
marci@485:       }
marci@485: 
marci@485:       if (__augment) {
marci@485: 	typename MG::Node n=tF;
marci@485: 	Num augment_value=free[tF];
marci@485: 	while (F.valid(pred[n])) { 
marci@485: 	  typename MG::Edge e=pred[n];
marci@485: 	  res_graph.augment(original_edge[e], augment_value); 
marci@485: 	  n=F.tail(e);
marci@485: 	  if (residual_capacity[e]==augment_value) 
marci@485: 	    F.erase(e); 
marci@485: 	  else 
marci@485: 	    residual_capacity.set(e, residual_capacity[e]-augment_value);
marci@478: 	}
marci@485:       }
marci@478: 	
marci@485:     }
marci@478:             
marci@485:     return _augment;
marci@485:   }
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478:   template <typename Graph, typename Num, typename CapMap, typename FlowMap>
marci@478:   bool MaxFlow<Graph, Num, CapMap, FlowMap>::augmentOnBlockingFlow2() 
marci@478:   {
marci@485:     bool _augment=false;
marci@478: 
marci@485:     ResGW res_graph(*g, *capacity, *flow);
marci@478:       
marci@485:     //ReachedMap level(res_graph);
marci@485:     FOR_EACH_LOC(typename Graph::NodeIt, e, *g) level.set(e, 0);
marci@485:     BfsIterator<ResGW, ReachedMap> bfs(res_graph, level);
marci@478: 
marci@485:     bfs.pushAndSetReached(s);
marci@485:     DistanceMap<ResGW> dist(res_graph);
marci@485:     while ( !bfs.finished() ) { 
marci@485:       ResGWOutEdgeIt e=bfs;
marci@485:       if (res_graph.valid(e) && bfs.isBNodeNewlyReached()) {
marci@485: 	dist.set(res_graph.head(e), dist[res_graph.tail(e)]+1);
marci@485:       }
marci@485:       ++bfs;
marci@485:     } //computing distances from s in the residual graph
marci@478: 
marci@478:       //Subgraph containing the edges on some shortest paths
marci@485:     ConstMap<typename ResGW::Node, bool> true_map(true);
marci@485:     typedef SubGraphWrapper<ResGW, ConstMap<typename ResGW::Node, bool>, 
marci@485:       DistanceMap<ResGW> > FilterResGW;
marci@485:     FilterResGW filter_res_graph(res_graph, true_map, dist);
marci@478: 
marci@485:     //Subgraph, which is able to delete edges which are already 
marci@485:     //met by the dfs
marci@485:     typename FilterResGW::template NodeMap<typename FilterResGW::OutEdgeIt> 
marci@485:       first_out_edges(filter_res_graph);
marci@485:     typename FilterResGW::NodeIt v;
marci@485:     for(filter_res_graph.first(v); filter_res_graph.valid(v); 
marci@485: 	filter_res_graph.next(v)) 
marci@478:       {
marci@478:  	typename FilterResGW::OutEdgeIt e;
marci@478:  	filter_res_graph.first(e, v);
marci@478:  	first_out_edges.set(v, e);
marci@478:       }
marci@485:     typedef ErasingFirstGraphWrapper<FilterResGW, typename FilterResGW::
marci@485:       template NodeMap<typename FilterResGW::OutEdgeIt> > ErasingResGW;
marci@485:     ErasingResGW erasing_res_graph(filter_res_graph, first_out_edges);
marci@478: 
marci@485:     bool __augment=true;
marci@478: 
marci@485:     while (__augment) {
marci@478: 
marci@485:       __augment=false;
marci@485:       //computing blocking flow with dfs
marci@485:       DfsIterator< ErasingResGW, 
marci@485: 	typename ErasingResGW::template NodeMap<bool> > 
marci@485: 	dfs(erasing_res_graph);
marci@485:       typename ErasingResGW::
marci@485: 	template NodeMap<typename ErasingResGW::OutEdgeIt> 
marci@485: 	pred(erasing_res_graph); 
marci@485:       pred.set(s, INVALID);
marci@485:       //invalid iterators for sources
marci@478: 
marci@485:       typename ErasingResGW::template NodeMap<Num> 
marci@485: 	free1(erasing_res_graph);
marci@478: 
marci@485:       dfs.pushAndSetReached(
marci@485: 			    typename ErasingResGW::Node(
marci@485: 							typename FilterResGW::Node(
marci@485: 										   typename ResGW::Node(s)
marci@485: 										   )
marci@485: 							)
marci@485: 			    );
marci@485:       while (!dfs.finished()) {
marci@485: 	++dfs;
marci@485: 	if (erasing_res_graph.valid(
marci@485: 				    typename ErasingResGW::OutEdgeIt(dfs))) 
marci@478:  	  { 
marci@478:   	    if (dfs.isBNodeNewlyReached()) {
marci@478: 	  
marci@478:  	      typename ErasingResGW::Node v=erasing_res_graph.aNode(dfs);
marci@478:  	      typename ErasingResGW::Node w=erasing_res_graph.bNode(dfs);
marci@478: 
marci@478:  	      pred.set(w, /*typename ErasingResGW::OutEdgeIt*/(dfs));
marci@478:  	      if (erasing_res_graph.valid(pred[v])) {
marci@478:  		free1.set(w, std::min(free1[v], res_graph.resCap(
marci@485: 								 typename ErasingResGW::OutEdgeIt(dfs))));
marci@478:  	      } else {
marci@478:  		free1.set(w, res_graph.resCap(
marci@485: 					      typename ErasingResGW::OutEdgeIt(dfs))); 
marci@478:  	      }
marci@478: 	      
marci@478:  	      if (w==t) { 
marci@478:  		__augment=true; 
marci@478:  		_augment=true;
marci@478:  		break; 
marci@478:  	      }
marci@478:  	    } else {
marci@478:  	      erasing_res_graph.erase(dfs);
marci@478: 	    }
marci@478: 	  }
marci@485:       }	
marci@478: 
marci@485:       if (__augment) {
marci@485: 	typename ErasingResGW::Node n=typename FilterResGW::Node(typename ResGW::Node(t));
marci@485: 	// 	  typename ResGW::NodeMap<Num> a(res_graph);
marci@485: 	// 	  typename ResGW::Node b;
marci@485: 	// 	  Num j=a[b];
marci@485: 	// 	  typename FilterResGW::NodeMap<Num> a1(filter_res_graph);
marci@485: 	// 	  typename FilterResGW::Node b1;
marci@485: 	// 	  Num j1=a1[b1];
marci@485: 	// 	  typename ErasingResGW::NodeMap<Num> a2(erasing_res_graph);
marci@485: 	// 	  typename ErasingResGW::Node b2;
marci@485: 	// 	  Num j2=a2[b2];
marci@485: 	Num augment_value=free1[n];
marci@485: 	while (erasing_res_graph.valid(pred[n])) { 
marci@485: 	  typename ErasingResGW::OutEdgeIt e=pred[n];
marci@485: 	  res_graph.augment(e, augment_value);
marci@485: 	  n=erasing_res_graph.tail(e);
marci@485: 	  if (res_graph.resCap(e)==0)
marci@485: 	    erasing_res_graph.erase(e);
marci@478: 	}
marci@478:       }
marci@478:       
marci@485:     } //while (__augment) 
marci@478:             
marci@485:     return _augment;
marci@485:   }
marci@478: 
marci@478: 
marci@478: 
marci@478: 
marci@478: } //namespace hugo
marci@478: 
marci@480: #endif //HUGO_MAX_FLOW_H
marci@478: 
marci@478: 
marci@478: 
marci@478: