Have a DAG and we want that for each node v find the number of vertex that existence a path from v to that vertexes
for n <= 1e5
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3831 |
3 | Radewoosh | 3646 |
4 | jqdai0815 | 3620 |
4 | Benq | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | gamegame | 3386 |
10 | ksun48 | 3373 |
# | User | Contrib. |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | -is-this-fft- | 158 |
6 | awoo | 157 |
7 | adamant | 156 |
8 | TheScrasse | 154 |
8 | nor | 154 |
10 | Dominater069 | 153 |
Have a DAG and we want that for each node v find the number of vertex that existence a path from v to that vertexes
for n <= 1e5
Name |
---|
I think simple traversing can helpful.
That is Good but the order is O(n^2);
Not really because you are using the adjacency-list representation of the graph.
Actually the answer is just to run DFS/BFS on that node and see how many nodes are visited in the process.
Complexity O(E + V)
That not for each vertex
Then you can find the condensation graph into SCC and run DFS to find the answer recursively. Complexity doesn't change
I have modified the code to make it run in O(n)
Can we really compute the number of vertices that can be reached from vertex v with this algorithm?
I think this graph is a counterexample.
(UPD: Sorry, the number with the red color font actually should be 6)
You can use a bit-parallel strategy.
Assuming bit operations for one word is O(1), and let |word| the word-length of your machine, and then the time complexity would be O(NM/|word|). The memory complexity to store the reachability can be O(N*|word|) if you only care about the reachability from |word| vertices at the same time.
In other words, in today's 64-bit environment, it's nearly 64x faster than the naive algorithm to check the reachability from each vertex to all vertices one by one.