N
N
Nem0_o2015-03-03 17:21:21
Programming
Nem0_o, 2015-03-03 17:21:21

How to complement topological sorting?

Part of the code, DFS and topological sort:

void dfs (int v) {
  used[v] = true;
  for (size_t i=0; i<g[v].size(); ++i) {
    int to = g[v][i];
    if (!used[to])
      dfs (to);}
  ans.push_back (v);
}
void t_sort() {
  for (int i=0; i<n; ++i)
    used[i] = false;
  ans.clear();
  for (int i=0; i<n+1; ++i)
    if (!used[i])
    dfs(i);
}

It is not possible to make it so that sorting does not occur when there is a cycle in the graph.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2015-03-10
@Nem0_o

With two-digit visit marks (bool used[]) - no way.
You need to switch to three-digit labels (UNVISITED, PARTLY_VISITED, VISITED).

void dfs (int v) {
  state[v] = PARTLY_VISITED;
    .....
  state[v] = VISITED;
  ans.push_back (v);
}

There is a good example in your previous question.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question