I need to find all pairs of nodes which have a common ancestor in a DAG in O(n^2 + m) time. I can use O(n^2 memory).
Please suggest a method to do this ?
# | User | Rating |
---|---|---|
1 | tourist | 3993 |
2 | jiangly | 3743 |
3 | orzdevinwang | 3707 |
4 | Radewoosh | 3627 |
5 | jqdai0815 | 3620 |
6 | Benq | 3564 |
7 | Kevin114514 | 3443 |
8 | ksun48 | 3434 |
9 | Rewinding | 3397 |
10 | Um_nik | 3396 |
# | User | Contrib. |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
I need to find all pairs of nodes which have a common ancestor in a DAG in O(n^2 + m) time. I can use O(n^2 memory).
Please suggest a method to do this ?
Name |
---|
I think we can consecutively choose all nodes, run dfs from the current node and then for those vertices having parent the current node (say this is the set of vertices K) we want to count in how many ways we can choose two vertices from set V (the vertices of the initial graph) such that both of them have an ancestor from set K and their ancestors are different. It makes O((N+M)*N) time and O(N) additional memory. But I am not sure if this will work, once I tried such problem with this strategy and didn't get AC :(
UPD: The complexity is actually O((N+M)*N).
I did not get exactly what are you saying ?
or if I got u right, then the aalgo will take O(n^2 m) time not O(n^2 + m)
Oops, I am sorry, the complexity is O((N+M)*N). Will this be enough or no? The problem I was trying to solve had constraints N,M<=10^4 so this was enough but I got WA, still I don't see a mistake :)
So you can count the number of pair which do not have common ancestor and then decrease it from n*(n-1)/2 (n=number of nodes).
Let's say you want to count this number for node x.You make a dfs to see all his ancestors(nodes from which u can reach x).Then from all those ancestor make a single bfs to see what other nodes u can reach.(in queue u put first all ancestors,so actually complexity will be O(n+m)) After that,for all nodes that are nodes that are not visited(by any possible ancestor of x),it means they do not have a common ancestor :)
Complexity O((n+m)*n) memory O(n+m);