// -*- c++ -*-
#ifndef HUGO_MINLENGTHPATHS_H
#define HUGO_MINLENGTHPATHS_H

///\ingroup galgs
///\file
///\brief An algorithm for finding k paths of minimal total length.

#include <iostream>
#include <dijkstra.h>
#include <graph_wrapper.h>
#include <maps.h>
#include <vector.h>


namespace hugo {

/// \addtogroup galgs
/// @{

  ///\brief Implementation of an algorithm for finding k paths between 2 nodes 
  /// of minimal total length 
  ///
  /// The class \ref hugo::MinLengthPaths "MinLengthPaths" implements
  /// an algorithm for finding k edge-disjoint paths
  /// from a given source node to a given target node in an
  /// edge-weighted directed graph having minimal total weigth (length).
  ///
  ///\author Attila Bernath
  template <typename Graph, typename LengthMap>
  class MinLengthPaths {

    typedef typename LengthMap::ValueType Length;
    
    typedef typename Graph::Node Node;
    typedef typename Graph::NodeIt NodeIt;
    typedef typename Graph::Edge Edge;
    typedef typename Graph::OutEdgeIt OutEdgeIt;
    typedef typename Graph::template EdgeMap<int> EdgeIntMap;

    typedef ConstMap<Edge,int> ConstMap;

    typedef ResGraphWrapper<const Graph,int,ConstMap,EdgeIntMap> ResGraphType;

    class ModLengthMap {   
      typedef typename ResGraphType::template NodeMap<Length> NodeMap;
      const ResGraphType& G;
      const EdgeIntMap& rev;
      const LengthMap &ol;
      const NodeMap &pot;
    public :
      typedef typename LengthMap::KeyType KeyType;
      typedef typename LengthMap::ValueType ValueType;
	
      ValueType operator[](typename ResGraphType::Edge e) const {     
	//if ( (1-2*rev[e])*ol[e]-(pot[G.head(e)]-pot[G.tail(e)] ) <0 ){
	//  std::cout<<"Negative length!!"<<std::endl;
	//}
	return (1-2*rev[e])*ol[e]-(pot[G.head(e)]-pot[G.tail(e)]);   
      }     
	
      ModLengthMap(const ResGraphType& _G, const EdgeIntMap& _rev, 
		   const LengthMap &o,  const NodeMap &p) : 
	G(_G), rev(_rev), ol(o), pot(p){}; 
    };//ModLengthMap


    

    const Graph& G;
    const LengthMap& length;

    //auxiliary variables

    //The value is 1 iff the edge is reversed. 
    //If the algorithm has finished, the edges of the seeked paths are 
    //exactly those that are reversed 
    EdgeIntMap reversed; 
    
    //Container to store found paths
    std::vector< std::vector<Edge> > paths;
    //typedef DirPath<Graph> DPath;
    //DPath paths;


    Length total_length;

  public :


    MinLengthPaths(Graph& _G, LengthMap& _length) : G(_G), 
      length(_length), reversed(_G)/*, dijkstra_dist(_G)*/{ }

    
    ///Runs the algorithm.

    ///Runs the algorithm.
    ///Returns k if there are at least k edge-disjoint paths from s to t.
    ///Otherwise it returns the number of found edge-disjoint paths from s to t.
    int run(Node s, Node t, int k) {
      ConstMap const1map(1);


      //We need a residual graph, in which some of the edges are reversed
      ResGraphType res_graph(G, const1map, reversed);

      //Initialize the copy of the Dijkstra potential to zero
      typename ResGraphType::template NodeMap<Length> dijkstra_dist(res_graph);
      ModLengthMap mod_length(res_graph, reversed, length, dijkstra_dist);

      Dijkstra<ResGraphType, ModLengthMap> dijkstra(res_graph, mod_length);

      int i;
      for (i=0; i<k; ++i){
	dijkstra.run(s);
	if (!dijkstra.reached(t)){
	  //There are no k paths from s to t
	  break;
	};
	
	{
	  //We have to copy the potential
	  typename ResGraphType::NodeIt n;
	  for ( res_graph.first(n) ; res_graph.valid(n) ; res_graph.next(n) ) {
	      dijkstra_dist[n] += dijkstra.distMap()[n];
	  }
	}


	//Reversing the sortest path
	Node n=t;
	Edge e;
	while (n!=s){
	  e = dijkstra.pred(n);
	  n = dijkstra.predNode(n);
	  reversed[e] = 1-reversed[e];
	}

	  
      }
      
      //Let's find the paths
      //We put the paths into stl vectors (as an inner representation). 
      //In the meantime we lose the information stored in 'reversed'.
      //We suppose the lengths to be positive now.

      //Meanwhile we put the total length of the found paths 
      //in the member variable total_length
      paths.clear();
      total_length=0;
      paths.resize(k);
      for (int j=0; j<i; ++j){
	Node n=s;
	OutEdgeIt e;

	while (n!=t){


	  G.first(e,n);
	  
	  while (!reversed[e]){
	    G.next(e);
	  }
	  n = G.head(e);
	  paths[j].push_back(e);
	  total_length += length[e];
	  reversed[e] = 1-reversed[e];
	}
	
      }

      return i;
    }

    ///This function gives back the total length of the found paths.
    ///Assumes that \c run() has been run and nothing changed since then.
    Length totalLength(){
      return total_length;
    }

    ///This function gives back the \c j-th path in argument p.
    ///Assumes that \c run() has been run and nothing changed since then.
    /// \warning It is assumed that \c p is constructed to be a path of graph \c G. If \c j is greater than the result of previous \c run, then the result here will be an empty path.
    template<typename DirPath>
    void getPath(DirPath& p, int j){
      p.clear();
      typename DirPath::Builder B(p);
      for(typename std::vector<Edge>::iterator i=paths[j].begin(); 
	  i!=paths[j].end(); ++i ){
	B.pushBack(*i);
      }

      B.commit();
    }

  }; //class MinLengthPaths

  ///@}

} //namespace hugo

#endif //HUGO_MINLENGTHPATHS_H
