/*
preflow_push_max_flow_h
by jacint. 
Runs a preflow push algorithm with the modification, 
that we do not push on nodes with level at least n. 
Moreover, if a level gets empty, we set all nodes above that
level to level n. Hence, in the end, we arrive at a maximum preflow 
with value of a max flow value. An empty level gives a minimum cut.

Member functions:

void run() : runs the algorithm

  The following functions should be used after run() was already run.

T maxflow() : returns the value of a maximum flow

NodeMap<bool> mincut(): returns a 
     characteristic vector of a minimum cut.
*/

#ifndef PREFLOW_PUSH_MAX_FLOW_H
#define PREFLOW_PUSH_MAX_FLOW_H

#include <algorithm>
#include <vector>
#include <stack>

#include <reverse_bfs.h>


namespace marci {

  template <typename Graph, typename T>
  class preflow_push_max_flow {
    
    typedef typename Graph::NodeIt NodeIt;
    typedef typename Graph::EachNodeIt EachNodeIt;
    typedef typename Graph::OutEdgeIt OutEdgeIt;
    typedef typename Graph::InEdgeIt InEdgeIt;
    
    Graph& G;
    NodeIt s;
    NodeIt t;
    typename Graph::EdgeMap<T>& capacity; 
    T value;
    typename Graph::NodeMap<bool> mincutvector;    


     
  public:
        
    preflow_push_max_flow ( Graph& _G, NodeIt _s, NodeIt _t, 
			    typename Graph::EdgeMap<T>& _capacity) : 
      G(_G), s(_s), t(_t), capacity(_capacity), mincutvector(_G, false) { }


    /*
      The run() function runs a modified version of the 
      highest label preflow-push, which only 
      finds a maximum preflow, hence giving the value of a maximum flow.
    */
    void run() {
 
      typename Graph::EdgeMap<T> flow(G, 0); 
      typename Graph::NodeMap<int> level(G);   
      typename Graph::NodeMap<T> excess(G);    
            
      int n=G.nodeNum();                       
      int b=n-2; 
      /*
	b is a bound on the highest level of an active Node. 
	In the beginning it is at most n-2.
      */
      
      std::vector<int> numb(n);     //The number of Nodes on level i < n.
      std::vector<std::stack<NodeIt> > stack(2*n-1);    
      //Stack of the active Nodes in level i.

      /*Reverse_bfs from t, to find the starting level.*/
      reverse_bfs<Graph> bfs(G, t);
      bfs.run();
      for(EachNodeIt v=G.template first<EachNodeIt>(); v.valid(); ++v) 
	{
	  int dist=bfs.dist(v);
	  level.set(v, dist); 
	  ++numb[dist];
	}

      level.set(s,n);

      /* Starting flow. It is everywhere 0 at the moment. */
      for(OutEdgeIt e=G.template first<OutEdgeIt>(s); e.valid(); ++e) 
	{
	  if ( capacity.get(e) > 0 ) {
	    NodeIt w=G.head(e);
	    flow.set(e, capacity.get(e)); 
	    stack[level.get(w)].push(w); 
	    excess.set(w, excess.get(w)+capacity.get(e));
	  }
	}

      /* 
	 End of preprocessing 
      */



      /*
	Push/relabel on the highest level active Nodes.
      */
	
      /*While there exists an active Node.*/
      while (b) { 

	/*We decrease the bound if there is no active node of level b.*/
	if (stack[b].empty()) {
	  --b;
	} else {

	  NodeIt w=stack[b].top();    //w is the highest label active Node.
	  stack[b].pop();                    //We delete w from the stack.
	
	  int newlevel=2*n-2;                //In newlevel we maintain the next level of w.
	
	  for(OutEdgeIt e=G.template first<OutEdgeIt>(w); e.valid(); ++e) {
	    NodeIt v=G.head(e);
	    /*e is the Edge wv.*/

	    if (flow.get(e)<capacity.get(e)) {              
	      /*e is an Edge of the residual graph */

	      if(level.get(w)==level.get(v)+1) {      
		/*Push is allowed now*/

		if (capacity.get(e)-flow.get(e) > excess.get(w)) {       
		  /*A nonsaturating push.*/
		  
		  if (excess.get(v)==0 && v != s) stack[level.get(v)].push(v); 
		  /*v becomes active.*/
		  
		  flow.set(e, flow.get(e)+excess.get(w));
		  excess.set(v, excess.get(v)+excess.get(w));
		  excess.set(w,0);
		  //std::cout << w << " " << v <<" elore elen nonsat pump "  << std::endl;
		  break; 
		} else { 
		  /*A saturating push.*/

		  if (excess.get(v)==0 && v != s) stack[level.get(v)].push(v); 
		  /*v becomes active.*/

		  excess.set(v, excess.get(v)+capacity.get(e)-flow.get(e));
		  excess.set(w, excess.get(w)-capacity.get(e)+flow.get(e));
		  flow.set(e, capacity.get(e));
		  //std::cout << w <<" " << v <<" elore elen sat pump "   << std::endl;
		  if (excess.get(w)==0) break; 
		  /*If w is not active any more, then we go on to the next Node.*/
		  
		} // if (capacity.get(e)-flow.get(e) > excess.get(w))
	      } // if (level.get(w)==level.get(v)+1)
	    
	      else {newlevel = newlevel < level.get(v) ? newlevel : level.get(v);}
	    
	    } //if (flow.get(e)<capacity.get(e))
	 
	  } //for(OutEdgeIt e=G.first_OutEdge(w); e.valid(); ++e) 
	  


	  for(InEdgeIt e=G.template first<InEdgeIt>(w); e.valid(); ++e) {
	    NodeIt v=G.tail(e);
	    /*e is the Edge vw.*/

	    if (excess.get(w)==0) break;
	    /*It may happen, that w became inactive in the first 'for' cycle.*/		
  
	    if(flow.get(e)>0) {             
	      /*e is an Edge of the residual graph */

	      if(level.get(w)==level.get(v)+1) {  
		/*Push is allowed now*/
		
		if (flow.get(e) > excess.get(w)) { 
		  /*A nonsaturating push.*/
		  
		  if (excess.get(v)==0 && v != s) stack[level.get(v)].push(v); 
		  /*v becomes active.*/

		  flow.set(e, flow.get(e)-excess.get(w));
		  excess.set(v, excess.get(v)+excess.get(w));
		  excess.set(w,0);
		  //std::cout << v << " " << w << " vissza elen nonsat pump "     << std::endl;
		  break; 
		} else {                                               
		  /*A saturating push.*/
		  
		  if (excess.get(v)==0 && v != s) stack[level.get(v)].push(v); 
		  /*v becomes active.*/
		  
		  flow.set(e,0);
		  excess.set(v, excess.get(v)+flow.get(e));
		  excess.set(w, excess.get(w)-flow.get(e));
		  //std::cout << v <<" " << w << " vissza elen sat pump "     << std::endl;
		  if (excess.get(w)==0) { break;}
		} //if (flow.get(e) > excess.get(v)) 
	      } //if(level.get(w)==level.get(v)+1)
	      
	      else {newlevel = newlevel < level.get(v) ? newlevel : level.get(v);}
	      //std::cout << "Leveldecrease of Node " << w << " to " << newlevel << std::endl; 

	    } //if (flow.get(e)>0)

	  } //for in-Edge




	  /*
	    Relabel
	  */
	  if (excess.get(w)>0) {
	    /*Now newlevel <= n*/

	    int l=level.get(w);	        //l is the old level of w.
	    --numb[l];
	   
	    if (newlevel == n) {
	      level.set(w,n);
	      
	    } else {
	      
	      if (numb[l]) {
		/*If the level of w remains nonempty.*/
		
		level.set(w,++newlevel);
		++numb[newlevel];
		stack[newlevel].push(w);
		b=newlevel;
	      } else { 
		/*If the level of w gets empty.*/
	      
		for (EachNodeIt v=G.template first<EachNodeIt>(); v.valid() ; ++v) {
		  if (level.get(v) >= l ) { 
		    level.set(v,n);  
		  }
		}
		
		for (int i=l+1 ; i!=n ; ++i) numb[i]=0; 
	      } //if (numb[l])
	
	    } // if (newlevel = n)
	 
	  } // if (excess.get(w)>0)


	} //else
       
      } //while(b)

      value=excess.get(t);
      /*Max flow value.*/
      


      /*
	We find an empty level, e. The Nodes above this level give 
	a minimum cut.
      */
      
      int e=1;
      
      while(e) {
	if(numb[e]) ++e;
	else break;
      } 
      for (EachNodeIt v=G.template first<EachNodeIt>(); v.valid(); ++v) {
	if (level.get(v) > e) mincutvector.set(v, true);
      }
      

    } // void run()



    /*
      Returns the maximum value of a flow.
     */

    T maxflow() {
      return value;
    }



    /*
      Returns a minimum cut.
    */
    
    typename Graph::NodeMap<bool> mincut() {
      return mincutvector;
    }
    

  };
}//namespace marci
#endif 





