0

For directed graph G(V, E) with n nodes, I want to create an integer array a, and its length is n. If there is a path from node 1 to 2, then a[1] <= a[2], if they are in the same strongly connected component a[1] = a[2], if if there is no path from node 2 to 3, we have a[2] > a[3].

I think the time complexity should be O(n + m), because the time complexity of seeking strongly connected component is it. But I am not sure how to output an array for it, could anybody help? Thanks.

user8142520
  • 751
  • 1
  • 6
  • 20

2 Answers2

1

Once you have found every strongly connected components (SCC) of a graph, you can build the condensation of the graph by contracting each SCC into a single vertex. The condensation is a directed acyclic graph in which you can number the vertices using topological sorting. Every step has linear complexity.

Nelfeal
  • 12,593
  • 1
  • 20
  • 39
  • An additional topological sorting is **unnecessary** if you are using Tarjan's algo to compute SCCs. See here: https://stackoverflow.com/questions/32750511/does-tarjans-scc-algorithm-give-a-topological-sort-of-the-scc – Andrey Tyukin Feb 02 '18 at 18:16
0

Tarjan's SCC algorithm already does almost what you want, you need only one additional bookkeeping step.

Recall that Tarjan's SCC outputs the strongly connected components one by one already in a topologically sorted order. That is, all you have to do is to save the index of the SCC in all cells which correspond to the nodes of the current SCC. This is already the array that you want.

Depending on the representation of the graph and the implementation, you might want to save N - idx in the array cells, where N is the total number of found clusters. This is because it essentially doesn't matter in which direction you traverse the graph: the strongly connected components of a graph with the reversed arrows are the same. It depends on what is easier and faster to access in your concrete implementation.

Tarjan's algo traverses the graph twice, and has O(|V| + |E|) runtime. Keeping an additional array doesn't add anything to the equation.

Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93