How do I calculate the length of the path to the farthest node for all nodes in a weighted tree?
Thanks in advance. :)
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 160 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 151 |
Name |
---|
Let's make some vertex a root of the tree. Let dx, y be the length of the edge between verteces x and y.
Let fv be the maximal distance from vertex v to the vertex in its subtree. We will calcutate this value for all verteces using dfs:
(or 0 if v is leaf).
Let gv be the maximal distance from vertex v to the vertex that is not in its subtree. We will calcutate this value for all verteces using dfs:
(or 0 if v is root).
Then we will calculate ansv — answer to the problem. We will calcutate this value for all verteces:
.
It's a bit unclear what you are asking. Are you asking about the longest path from the root to any of the nodes, or are you asking about the longest path between any two vertices? Also, are any of the weights negative?
I was asking about the length of the path to the farthest vertex reachable for every node. And all weights are non negative.
Extremely sorry for the inconvenience.
No worries, I actually think I should have read it more carefully. In that case, you can use the fact that for all vertices, the farthest vertex will be the endpoint of a diameter of the tree. Thus, you can find the diameter with two DFS' in O(n) time, and calculate the distance from each endpoint of the diameter with another extra DFS.
Imagine you found a diameter of your tree. Let the endpoints be u and v.
Then we can prove that answer(x) = max(dist(u, x), dist(v, x)), where dist(a, b) is the distance between vertices a and b.
Then we simply need to find the diameter (2x DFS) and then find find the distances from u and v to all other vertices, which results in .