Hi how to solve this question.
# | User | Rating |
---|---|---|
1 | tourist | 3757 |
2 | jiangly | 3647 |
3 | Benq | 3581 |
4 | orzdevinwang | 3570 |
5 | Geothermal | 3569 |
5 | cnnfls_csy | 3569 |
7 | Radewoosh | 3509 |
8 | ecnerwala | 3486 |
9 | jqdai0815 | 3474 |
10 | gyh20 | 3447 |
# | User | Contrib. |
---|---|---|
1 | maomao90 | 171 |
2 | awoo | 165 |
3 | adamant | 163 |
4 | TheScrasse | 159 |
5 | maroonrk | 155 |
6 | nor | 154 |
7 | -is-this-fft- | 152 |
8 | Petr | 147 |
9 | orz | 146 |
10 | pajenegod | 145 |
Hi how to solve this question.
Name |
---|
Let X and Y is the beginning and the end of one of the longest paths in the tree. Longest possible path length from any vetex z is equal to maximal distance between z and x, and between z and y. To find distance between pairs of vertices you can find their LCA(Least Common Ancestor) in Log(n).
you have to find the longest path which is called as the diameter of the tree. Let us suppose U and V are the pair of vertices such that U->V is one diameter of the tree. Now it is gurantee that the longest path from any node X will be the maximum of the two paths
From X to U
From X to V
You can do 2 times DFS once from the vertex U and other from the vertex V , side by side maintaining distance from both vertices ... This way you can solve this problem without the knowledge of LCA and the time complexity of this solution is O(V+E)
Another way to solve this problem is straightforward DP on a tree.
First of all we have to find Down[i] — length of longest path starting from vertex i and going down. To find it you need to pick best value among sons of given vertex, this part can be implemented with a single DFS.
After that we can find Up[i] — length of longest path starting from vertex i and going up. Here you have 2 possibilities. Let's say that j is a parent of i. Then Up[i] may be either Up[j]+1, if we'll move up from j, or Down[q]+2, where q is some other son of j, if we'll choose to move down from j instead of moving up. This part of solution also can be implemented with a single DFS.
And now it is clear that answer for every vertex is max(Down[i],Up[i]).