/* 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: bipartite.tcc,v 1.5 2005/04/26 08:52:29 witte Exp $"

#include <vector>
#include <list>
#include <bipartite.h>

namespace polymake { namespace graph {

template <typename Graph>
bool is_bipartite(const Graph& G)
{
   const int nodes=G.nodes();
   bool bipartite = true;
   std::vector<int> color(nodes, -1);  // coloring the nodes: -1 = not visited, 0/1 = colors
   std::list<int> node_queue(nodes);
      
   color[0]=0;
   node_queue.push_back(0);
      
   while (!node_queue.empty()) {
      const int n=node_queue.front();
      node_queue.pop_front();

      for (typename Entire<typename Graph::out_edge_list>::const_iterator e=entire(G.out_edges(n)); !e.at_end(); ++e) {
	 const int nn=e.to_node();
	 if (color[nn] < 0) {
	    color[nn] = !color[n];
	    node_queue.push_back(nn);
	 } else {
	    if (color[nn]==color[n]) {
	       bipartite = false;
	       node_queue.clear();
	       break;
	    }
	 }
      }
   }
   return bipartite;
}

template <typename Graph>
int is_bipartite_sign(const Graph& G)
{
   const int nodes=G.nodes();
   bool bipartite = true;
   std::vector<int> color(nodes,0);  // coloring the nodes: 0 = not visited, -1/1 = colors
   std::list<int> node_queue;
     
   int sign = color[0] = -1;
   node_queue.push_back(0);
      
   while (!node_queue.empty()) {
      const int n=node_queue.front();
      node_queue.pop_front();

      for (typename Entire<typename Graph::out_edge_list>::const_iterator e=entire(G.out_edges(n)); !e.at_end(); ++e) {
	 const int nn=e.to_node();
	 if (!color[nn]) {
	    sign += color[nn] = -color[n];
	    node_queue.push_back(nn);
	 } else {
	    if (color[nn]==color[n]) {
	       bipartite = false;
	       node_queue.clear();
	       break;
	    }
	 }
      }
   }

   return bipartite ? abs(sign) : -1;
}

} }

// Local Variables:
// mode:C++
// c-basic-offset:3
// End:
