/*
preflow_push_max_flow_hh
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 put 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

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

#ifndef PREFLOW_PUSH_MAX_FLOW_HH
#define PREFLOW_PUSH_MAX_FLOW_HH

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

#include <marci_list_graph.hh>
#include <marci_graph_traits.hh>
#include <marci_property_vector.hh>
#include <reverse_bfs.hh>


namespace marci {

  template <typename graph_type, typename T>
  class preflow_push_max_flow {
    
    typedef typename graph_traits<graph_type>::node_iterator node_iterator;
    typedef typename graph_traits<graph_type>::each_node_iterator each_node_iterator;
    typedef typename graph_traits<graph_type>::out_edge_iterator out_edge_iterator;
    typedef typename graph_traits<graph_type>::in_edge_iterator in_edge_iterator;
    
    graph_type& G;
    node_iterator s;
    node_iterator t;
    edge_property_vector<graph_type, T>& capacity; 
    T value;
    node_property_vector<graph_type, bool> mincutvector;    


     
  public:
        
    preflow_push_max_flow(graph_type& _G, node_iterator _s, node_iterator _t, edge_property_vector<graph_type, 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() {
 
      edge_property_vector<graph_type, T> flow(G, 0);         //the flow value, 0 everywhere  
      node_property_vector<graph_type, int> level(G);         //level of node
      node_property_vector<graph_type, T> excess(G);          //excess of node
            
      int n=number_of(G.first_node());                        //number of nodes 
      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<node_iterator> > stack(2*n-1);    //Stack of the active nodes in level i.



      /*Reverse_bfs from t, to find the starting level.*/

      reverse_bfs<list_graph> bfs(G, t);
      bfs.run();
      for(each_node_iterator v=G.first_node(); v.is_valid(); ++v) 
	{
	  int dist=bfs.dist(v);
	  level.put(v, dist); 
	  ++numb[dist];
	}

      /*The level of s is fixed to n*/ 
      level.put(s,n);


      /* Starting flow. It is everywhere 0 at the moment. */
     
      for(out_edge_iterator i=G.first_out_edge(s); i.is_valid(); ++i) 
	{
	  node_iterator w=G.head(i);
	  flow.put(i, capacity.get(i)); 
	  stack[bfs.dist(w)].push(w); 
	  excess.put(w, capacity.get(i));
	}


      /* 
	 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 {

	  node_iterator 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(out_edge_iterator e=G.first_out_edge(w); e.is_valid(); ++e) {
	    node_iterator 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.put(e, flow.get(e)+excess.get(w));
		  excess.put(v, excess.get(v)+excess.get(w));
		  excess.put(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.put(v, excess.get(v)+capacity.get(e)-flow.get(e));
		  excess.put(w, excess.get(w)-capacity.get(e)+flow.get(e));
		  flow.put(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(out_edge_iterator e=G.first_out_edge(w); e.is_valid(); ++e) 
	  


	  for(in_edge_iterator e=G.first_in_edge(w); e.is_valid(); ++e) {
	    node_iterator 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.put(e, flow.get(e)-excess.get(w));
		  excess.put(v, excess.get(v)+excess.get(w));
		  excess.put(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.put(e,0);
		  excess.put(v, excess.get(v)+flow.get(e));
		  excess.put(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.put(w,n);
	      
	    } else {
	      
	      if (numb[l]) {
		/*If the level of w remains nonempty.*/
		
		level.put(w,++newlevel);
		++numb[newlevel];
		stack[newlevel].push(w);
		b=newlevel;
	      } else { 
		/*If the level of w gets empty.*/
	      
		for (each_node_iterator v=G.first_node() ; v.is_valid() ; ++v) {
		  if (level.get(v) >= l ) { 
		    level.put(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 (each_node_iterator v=G.first_node(); v.is_valid(); ++v) {
	if (level.get(v) > e) mincutvector.put(v, true);
      }
      

    } // void run()



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

    T maxflow() {
      return value;
    }



    /*
      Returns a minimum cut.
    */
    
    node_property_vector<graph_type, bool> mincut() {
      return mincutvector;
    }
    

  };
}//namespace marci
#endif 





