/* -*- C++ -*-
 * src/hugo/min_cost_flow.h - Part of HUGOlib, a generic C++ optimization library
 *
 * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
 * (Egervary Combinatorial Optimization Research Group, EGRES).
 *
 * Permission to use, modify and distribute this software is granted
 * provided that this copyright notice appears in all copies. For
 * precise terms see the accompanying LICENSE file.
 *
 * This software is provided "AS IS" with no warranty of any kind,
 * express or implied, and with no claim as to its suitability for any
 * purpose.
 *
 */

#ifndef HUGO_MIN_COST_FLOW_H
#define HUGO_MIN_COST_FLOW_H

///\ingroup flowalgs
///\file
///\brief An algorithm for finding a flow of value \c k (for small values of \c k) having minimal total cost 


#include <hugo/dijkstra.h>
#include <hugo/graph_wrapper.h>
#include <hugo/maps.h>
#include <vector>

namespace hugo {

/// \addtogroup flowalgs
/// @{

  ///\brief Implementation of an algorithm for finding a flow of value \c k 
  ///(for small values of \c k) having minimal total cost between 2 nodes 
  /// 
  ///
  /// The class \ref hugo::MinCostFlow "MinCostFlow" implements
  /// an algorithm for finding a flow of value \c k 
  /// having minimal total cost 
  /// from a given source node to a given target node in an
  /// edge-weighted directed graph. To this end, 
  /// the edge-capacities and edge-weitghs have to be nonnegative. 
  /// The edge-capacities should be integers, but the edge-weights can be 
  /// integers, reals or of other comparable numeric type.
  /// This algorithm is intended to use only for small values of \c k, 
  /// since it is only polynomial in k, 
  /// not in the length of k (which is log k). 
  /// In order to find the minimum cost flow of value \c k it 
  /// finds the minimum cost flow of value \c i for every 
  /// \c i between 0 and \c k. 
  ///
  ///\param Graph The directed graph type the algorithm runs on.
  ///\param LengthMap The type of the length map.
  ///\param CapacityMap The capacity map type.
  ///
  ///\author Attila Bernath
  template <typename Graph, typename LengthMap, typename CapacityMap>
  class MinCostFlow {

    typedef typename LengthMap::ValueType Length;

    //Warning: this should be integer type
    typedef typename CapacityMap::ValueType Capacity;
    
    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 ResGraphWrapper<const Graph,int,CapacityMap,EdgeIntMap> ResGW;
    typedef typename ResGW::Edge ResGraphEdge;

    class ModLengthMap {   
      typedef typename Graph::template NodeMap<Length> NodeMap;
      const ResGW& G;
      const LengthMap &ol;
      const NodeMap &pot;
    public :
      typedef typename LengthMap::KeyType KeyType;
      typedef typename LengthMap::ValueType ValueType;
	
      ValueType operator[](typename ResGW::Edge e) const {     
	if (G.forward(e))
	  return  ol[e]-(pot[G.head(e)]-pot[G.tail(e)]);   
	else
	  return -ol[e]-(pot[G.head(e)]-pot[G.tail(e)]);   
      }     
	
      ModLengthMap(const ResGW& _G,
		   const LengthMap &o,  const NodeMap &p) : 
	G(_G), /*rev(_rev),*/ ol(o), pot(p){}; 
    };//ModLengthMap


  protected:
    
    //Input
    const Graph& G;
    const LengthMap& length;
    const CapacityMap& capacity;


    //auxiliary variables

    //To store the flow
    EdgeIntMap flow; 
    //To store the potential (dual variables)
    typedef typename Graph::template NodeMap<Length> PotentialMap;
    PotentialMap potential;
    

    Length total_length;


  public :

    /// The constructor of the class.
    
    ///\param _G The directed graph the algorithm runs on. 
    ///\param _length The length (weight or cost) of the edges. 
    ///\param _cap The capacity of the edges. 
    MinCostFlow(Graph& _G, LengthMap& _length, CapacityMap& _cap) : G(_G), 
      length(_length), capacity(_cap), flow(_G), potential(_G){ }

    
    ///Runs the algorithm.
    
    ///Runs the algorithm.
    ///Returns k if there is a flow of value at least k edge-disjoint 
    ///from s to t.
    ///Otherwise it returns the maximum value of a flow from s to t.
    ///
    ///\param s The source node.
    ///\param t The target node.
    ///\param k The value of the flow we are looking for.
    ///
    ///\todo May be it does make sense to be able to start with a nonzero 
    /// feasible primal-dual solution pair as well.
    int run(Node s, Node t, int k) {

      //Resetting variables from previous runs
      total_length = 0;
      
      for (typename Graph::EdgeIt e(G); e!=INVALID; ++e) flow.set(e, 0);

      //Initialize the potential to zero
      for (typename Graph::NodeIt n(G); n!=INVALID; ++n) potential.set(n, 0);
      
      
      //We need a residual graph
      ResGW res_graph(G, capacity, flow);


      ModLengthMap mod_length(res_graph, length, potential);

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

      int i;
      for (i=0; i<k; ++i){
	dijkstra.run(s);
	if (!dijkstra.reached(t)){
	  //There are no flow of value k from s to t
	  break;
	};
	
	//We have to change the potential
        for(typename ResGW::NodeIt n(res_graph); n!=INVALID; ++n)
	  potential[n] += dijkstra.distMap()[n];


	//Augmenting on the sortest path
	Node n=t;
	ResGraphEdge e;
	while (n!=s){
	  e = dijkstra.pred(n);
	  n = dijkstra.predNode(n);
	  res_graph.augment(e,1);
	  //Let's update the total length
	  if (res_graph.forward(e))
	    total_length += length[e];
	  else 
	    total_length -= length[e];	    
	}

	  
      }
      

      return i;
    }



    /// Gives back the total weight of the found flow.

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

    ///Returns a const reference to the EdgeMap \c flow. 

    ///Returns a const reference to the EdgeMap \c flow. 
    ///\pre \ref run() must
    ///be called before using this function.
    const EdgeIntMap &getFlow() const { return flow;}

    ///Returns a const reference to the NodeMap \c potential (the dual solution).

    ///Returns a const reference to the NodeMap \c potential (the dual solution).
    /// \pre \ref run() must be called before using this function.
    const PotentialMap &getPotential() const { return potential;}

    /// Checking the complementary slackness optimality criteria

    ///This function checks, whether the given solution is optimal
    ///If executed after the call of \c run() then it should return with true.
    ///This function only checks optimality, doesn't bother with feasibility.
    ///It is meant for testing purposes.
    ///
    bool checkComplementarySlackness(){
      Length mod_pot;
      Length fl_e;
        for(typename Graph::EdgeIt e(G); e!=INVALID; ++e) {
	//C^{\Pi}_{i,j}
	mod_pot = length[e]-potential[G.head(e)]+potential[G.tail(e)];
	fl_e = flow[e];
	if (0<fl_e && fl_e<capacity[e]) {
	  /// \todo better comparison is needed for real types, moreover, 
	  /// this comparison here is superfluous.
	  if (mod_pot != 0)
	    return false;
	} 
	else {
	  if (mod_pot > 0 && fl_e != 0)
	    return false;
	  if (mod_pot < 0 && fl_e != capacity[e])
	    return false;
	}
      }
      return true;
    }
    

  }; //class MinCostFlow

  ///@}

} //namespace hugo

#endif //HUGO_MIN_COST_FLOW_H
