Блог пользователя nownikhil

Автор nownikhil, 11 лет назад, По-английски

Can anyone suggest me a method for finding all the cycles and their lengths in a directed graph. Cycles might be overlapping. Lets say the graph had 2 OVERLAPPING cycles, so answer should be 3 along with their lengths. We must find smaller as well as larger cycles in the graph.

Thanks in advance.

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
11 лет назад, # |
Rev. 3   Проголосовать: нравится -14 Проголосовать: не нравится
int n;
vector < vector<int> > g;
vector<char> cl;
vector<int> p;
int cycle_st, cycle_end;

bool dfs (int v) {
	cl[v] = 1;
	for (size_t i=0; i<g[v].size(); ++i) {
		int to = g[v][i];
		if (cl[to] == 0) {
			p[to] = v;
			if (dfs (to))  return true;
		}
		else if (cl[to] == 1) {
			cycle_end = v;
			cycle_st = to;
			return true;
		}
	}
	cl[v] = 2;
	return false;
}

int main() {
	... read the graph ...

	p.assign (n, -1);
	cl.assign (n, 0);
	cycle_st = -1;
	for (int i=0; i<n; ++i)
		if (dfs (i))
			break;

	if (cycle_st == -1)
		puts ("Acyclic");
	else {
		puts ("Cyclic");
		vector<int> cycle;
		cycle.push_back (cycle_st);
		for (int v=cycle_end; v!=cycle_st; v=p[v])
			cycle.push_back (v);
		cycle.push_back (cycle_st);
		reverse (cycle.begin(), cycle.end());
		for (size_t i=0; i<cycle.size(); ++i)
			printf ("%d ", cycle[i]+1);
	}
}

This code is copied from e-maxx.ru , very good web-site.

This code checks the graph for being acyclic or cyclic and if it is cyclic it finds the cycle. So just modify this code so that it does what you need. Hope it helps you.

  • »
    »
    11 лет назад, # ^ |
    Rev. 2   Проголосовать: нравится +13 Проголосовать: не нравится

    AA: Can anyone help me? I want to learn dijkstra on heap.

    BB: Here is [link] standart dijkstra. So just modify this code so that it does what you need.

»
11 лет назад, # |
Rev. 2   Проголосовать: нравится +8 Проголосовать: не нравится

This problem is NP (if exist polynomial solution for this problem, then it also gives polynomial solution for Hamiltonian cycle problem).

So, full search seems the best idea:)

  • »
    »
    11 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    I think there is solution in O(K*P(N)) where K is number of different cycles, P(N) — polynomial of N. But i don't think author understand what he wants.