/* Copyright (c) 1997-2004
   Ewgenij Gawrilow, Michael Joswig (Technische Universitaet Berlin, Germany)
   http://www.math.tu-berlin.de/polymake,  mailto:polymake@math.tu-berlin.de

   This program is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 2, or (at your option) any
   later version: http://www.gnu.org/licenses/gpl.txt.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
*/

#ident "$Project: polymake $$Id: random_edge_epl.cc,v 1.21 2004/07/27 18:07:48 gawrilow Exp $"

#include <list>
#include <vector>
#include <algorithm>
#include <Rational.h>
#include <Poly.h>
#include <Graph.h>
#include <Vector.h>
#include <Set.h>

namespace polymake { namespace polytope {

void random_edge_epl(Poly& p)
{
   typedef Graph<nothing,nothing,directed> graph;
   const graph G=p.give("DIRECTED_GRAPH");
   const int nodes=G.nodes();

   std::vector<int> outgoing_edges(nodes);
   std::vector<Rational> average_path_length(nodes);
   std::list<int> node_queue;

   for (int v=0; v<nodes; ++v) {          // initialize all nodes
      if (!(outgoing_edges[v]=G.out_degree(v)))
	 node_queue.push_back(v);
   }

   while (!node_queue.empty()) {
      const int v=node_queue.front();
      node_queue.pop_front();
      Rational APL(0);
      for (Entire<graph::out_edge_list>::const_iterator e=entire(G.out_edges(v));  !e.at_end();  ++e)
	 APL+=average_path_length[e.to_node()];

      if (G.out_degree(v)) average_path_length[v] = APL/G.out_degree(v) + 1;

      for (Entire<graph::in_edge_list>::const_iterator e=entire(G.in_edges(v));  !e.at_end();  ++e) {
	 const int v=e.from_node();
	 if (!(--outgoing_edges[v])) node_queue.push_back(v);
      }
   }

   p.take("RANDOM_EDGE_EPL") << average_path_length;
}

} }

using namespace polymake;

/** @file random_edge_epl
 *
 *  For each vertex compute the expected path length to the maximum.
 *  The random edge pivot rule is applied.
 *
 *  @synopsis random_edge_epl <file>
 *
 *  @reading  DIRECTED_GRAPH
 *  @writing  RANDOM_EDGE_EPL
 */

int main(int argc, const char *argv[])
{
   if (argc != 2) {
      cerr << "usage: " << argv[0] << " <file>\n";
      return 1;
   }
   try {
      Poly p(argv[1], ios::in | ios::out);
      polytope::random_edge_epl(p);
   }
   catch (const std::exception& e) {
      cerr << e.what() << endl;
      return 1;
   }
   return 0;
}
