#include <iostream.h>
#include <limits.h>
#include <LINK/algorithm/Algorithms.h>
#include <LINK/graph/Attribute.h>
#include <LINK/graph/Graph.h>

void PathToSource(Graph *g, Vertex *v, Set<Edge*>& edges)
{
	Vertex *pred;
	getAttribute((GraphObject*)v, "pred", pred);
	while (pred) {
		Edge *e = g->isEdge(pred, v);
		edges.insert(e);
		v = pred;
		getAttribute((GraphObject*)pred, "pred", pred);
	}
}
		

int Girth(Graph* g)
{
	int girth = INT_MAX;
	if (!g || !g->simpleQ())
		return girth;

	Set<Edge*> cycle_edges;

	Vertex **vertices = g->vertexStart();
	int i, order = g->order();
	for (i=0; i<order; i++) {
		BreadthFirstSearch(g, vertices[i]);
		Edge *e;
		Iterator<Edge*> get_edge(&g->edges());
		int cycle_length;
		while (get_edge(e)) {
			getAttribute((GraphObject*)e, "distance", cycle_length);
			if (cycle_length < girth) {
				cycle_edges.clear();
				Collection<Vertex*> *edge_verts = e->vertices();
				if (!edge_verts || edge_verts->size() != 2)
					continue;
				cycle_edges.insert(e);
				PathToSource(g,edge_verts->ref(0),cycle_edges);
				PathToSource(g,edge_verts->ref(1),cycle_edges);
				girth = cycle_length;
			}
		}
	}
	Iterator<Edge*> get_cycle_edge(&cycle_edges);
	Edge *e;
	while (get_cycle_edge(e)) {
		setAttribute((GraphObject*) e, "width", 4);
	}
	return girth;
}
