How do I calculate the length of the path to the farthest node for all nodes in a weighted tree?

Thanks in advance. :)

Before contest

Codeforces Round #522 (Div. 1, based on Technocup 2019 Elimination Round 3)

04:45:55

Register now »

Codeforces Round #522 (Div. 1, based on Technocup 2019 Elimination Round 3)

04:45:55

Register now »

*has extra registration

Before contest

Codeforces Round #522 (Div. 2, based on Technocup 2019 Elimination Round 3)

04:45:56

Register now »

Codeforces Round #522 (Div. 2, based on Technocup 2019 Elimination Round 3)

04:45:56

Register now »

*has extra registration

# | User | Rating |
---|---|---|

1 | tourist | 3372 |

2 | mnbvmar | 3345 |

3 | OO0OOO00O0OOO0O0…O | 3264 |

4 | Radewoosh | 3230 |

5 | scott_wu | 3189 |

6 | Benq | 3187 |

7 | LHiC | 3171 |

8 | Um_nik | 3155 |

9 | V--o_o--V | 3152 |

10 | Petr | 3139 |

# | User | Contrib. |
---|---|---|

1 | Radewoosh | 191 |

2 | Errichto | 172 |

3 | rng_58 | 158 |

4 | neal | 156 |

5 | Um_nik | 154 |

5 | tourist | 154 |

7 | Ashishgup | 152 |

8 | Petr | 151 |

9 | PikMike | 150 |

9 | 300iq | 150 |

Codeforces (c) Copyright 2010-2018 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Nov/18/2018 14:19:06 (d1).

Desktop version, switch to mobile version.

Supported by

User lists

Name |
---|

Let's make some vertex a root of the tree. Let

d_{x, y}be the length of the edge between vertecesxandy.Let

f_{v}be the maximal distance from vertexvto the vertex in its subtree. We will calcutate this value for all verteces using dfs:(or 0 if

vis leaf).Let

g_{v}be the maximal distance from vertexvto the vertex that is not in its subtree. We will calcutate this value for all verteces using dfs:(or 0 if

vis root).Then we will calculate

ans_{v}— 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

uandv.Then we can prove that

answer(x) =max(dist(u,x),dist(v,x)), wheredist(a,b) is the distance between verticesaandb.Then we simply need to find the diameter (2x DFS) and then find find the distances from

uandvto all other vertices, which results in .