What algorithm should I use to find the number of rooted trees in an undirected graph? This problem requires it
# | User | Rating |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
# | User | Contrib. |
---|---|---|
1 | cry | 164 |
1 | maomao90 | 164 |
3 | Um_nik | 163 |
4 | atcoder_official | 160 |
5 | -is-this-fft- | 158 |
6 | adamant | 157 |
6 | awoo | 157 |
8 | TheScrasse | 154 |
8 | nor | 154 |
10 | djm03178 | 153 |
What algorithm should I use to find the number of rooted trees in an undirected graph? This problem requires it
Name |
---|
No, it doesn't. You just need to check if the graph has only one cycle and is connected. It can be done with a simple DFS or with DSU. See here -> 22406598
Can you please prove how you deduced it to the above properties?
Suppose we have a tree with n nodes. Thus, it has n — 1 edges. Now whenever i join an edge between any two nodes in the tree(connect two existing nodes, non adjacent), a cycle of at least 3 nodes will be formed. Thus the new graph should have n edges and has only one component.
Well, there's another kind of a time consuming way to solve it. First find if a cycle in the graph. Then check if there are no other cycles except the previously found one(run dfs rooted from the nodes from the previously found cycle and test for cycles while not visiting nodes of the previously found cycle) . Finally check if all nodes are in the same component.
I am sorry but while checking my code again I found a bug(fails on some case). The solution is wrong.