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 #512 (Div. 1, based on Technocup 2019 Elimination Round 1)

15:18:30

Register now »

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

15:18:30

Register now »

*has extra registration

Before contest

Codeforces Round #512 (Div. 2, based on Technocup 2019 Elimination Round 1)

15:18:30

Register now »

Codeforces Round #512 (Div. 2, based on Technocup 2019 Elimination Round 1)

15:18:30

Register now »

*has extra registration

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

1 | tourist | 3509 |

2 | OO0OOO00O0OOO0O0…O | 3327 |

3 | Syloviaely | 3274 |

4 | Um_nik | 3237 |

5 | Petr | 3161 |

6 | ko_osaga | 3154 |

7 | LHiC | 3135 |

8 | Benq | 3130 |

9 | Swistakk | 3089 |

10 | dotorya | 3060 |

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

1 | Radewoosh | 185 |

2 | rng_58 | 161 |

3 | tourist | 158 |

4 | Petr | 152 |

5 | Vovuh | 150 |

5 | Swistakk | 150 |

7 | PikMike | 147 |

8 | csacademy | 146 |

9 | Errichto | 145 |

9 | Um_nik | 145 |

Codeforces (c) Copyright 2010-2018 Mike Mirzayanov

The only programming contests Web 2.0 platform

Server time: Sep/23/2018 00:46:30 (d2).

Desktop version, switch to mobile version.

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 .