问题
I've been studying SCC and algorithms about them, and I've seen that people almost always mention that Kosaraju's algorithm finds the SCC and also gives them ordered in a (reversed) topological sort.
My question is: doesn't Tarjan's algorithm also find a (reversed) topological sort? I've found that it isn't mentioned (at least from where I've read, except wikipedia).
I've been thinking about it and make perfect sense. When tarjans_dfs is called on some node u, all SCCs that are reachable from u will be found before u's SCC. Am I wrong?
Wikipedia says it actually does find it:
"While there is nothing special about the order of the nodes within each strongly connected component, one useful property of the algorithm is that no strongly connected component will be identified before any of its successors. Therefore, the order in which the strongly connected components are identified constitutes a reverse topological sort of the DAG formed by the strongly connected components."
Is it my idea, or is it much more known that Kosaraju's algorithm finds the topological order than the fact that Tarjan's also does it?
回答1:
Yes, it does. Tarjan's SCC algorithm works by performing a DFS on a graph and keeping track of the roots of the SCCs on a stack. One method of finding a topological sort is performing a DFS on a graph and keeping track of the exit order. The exit order of these nodes in Tarjan's SCC algorithm provide a topological sort.
Donald Knuth even mentions it in an interview when talking about Tarjan's SCC algorithm, which he says is one of his favorite:
The data structures that he devised for this problem fit together in an amazingly beautiful way, so that the quantities you need to look at while exploring a directed graph are always magically at your fingertips. And his algorithm also does topological sorting as a byproduct.
回答2:
Yes. As Tarjan is based on Depth First Search all you have to do is to add the vertexes to the top of a list when each vertex reach the "closed" state.(ie. its dfs/tarjan call ends for that vertex)
Here is a C/C++/Pseudo-Code example:
void tarjan(int u) {
visited[u] = true;
closed[u] = false;
//dfs + tarjan processing
for (vi v = G[u].begin(); v != G[u].end(); v++) {
if (!visited[*v]) {
dfs(*v);
} else if (!closed[*v]) {
// has Cycle
}
}
closed[u] = true;
//add u to the top of your list here
}
回答3:
it does, i've been using it and the same question came to my mind.
I actually haven't had time to demonstrate it but every test case (lot of thousands) always returns an topological sorted condensed graph.
来源:https://stackoverflow.com/questions/32750511/does-tarjans-scc-algorithm-give-a-topological-sort-of-the-scc