/* 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: greedy_coloring.cc,v 1.2 2005/04/19 09:19:23 witte Exp $"

#include <Rational.h>
#include <Poly.h>
#include <Graph.h>
#include <Bitset.h>
#include <Array.h>

#include <list>

namespace polymake { namespace polytope {
  
  void coloring(Poly& p, const char* graph_section, const char* coloring_section)
  {
    typedef Graph<> graph;
    const graph G=p.give(graph_section);

    Array<int> C(G.nodes());
    for (int i=0; i<C.size(); ++i)
      C[i]=-1;
    
    // init node queue
    std::list<int> node_queue;
    Bitset visited(G.nodes());
    
    node_queue.push_back(0);
    visited += 0;
    
    // BFS
    while (!node_queue.empty()) {
      const int n=node_queue.front();
      node_queue.pop_front();
      
      Set<int> forbidden_colors;
      for (Entire<graph::out_edge_list>::const_iterator e=entire(G.out_edges(n));
	   !e.at_end(); ++e) {
	const int nn=e.to_node();
	forbidden_colors += C[nn];
	
	if (!visited.contains(nn)) {
	  visited += nn;
	  node_queue.push_back(nn);
	}
      }
      forbidden_colors -= -1;
      
      // find color of n
      int c=0;
      for (Entire< Set<int> >::const_iterator fc=entire(forbidden_colors);
	   !fc.at_end(); ++fc, ++c)
	if (c!=*fc) {
	  C[n]=c;
	  break;
	}
      if (C[n]==-1)  // no color found
	C[n] = forbidden_colors.size();      
    }  // end !node_queue.empty()
    
    p.take(coloring_section) << C;
  }
  
} }

using namespace polymake;

/** @file greedy_coloring
 *
 *  Computes a coloring.
 *
 *  @synopsis projectivities <file> <graph_section> <coloring_section>
 *
 *  @reading  <graph_section>
 *  @writing  <coloring_section>
 */

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