Editorial for Another Contest 2 Problem 3 - Poutine
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
This problem is very similar to the classic problem of, given a weighted tree, compute the distance between pairs of vertices efficiently. The solution to that problem is to root the tree and then construct a sparse table where, for each vertex , we know the vertex that is vertices above it as well as the distance to that vertex. We can compute the LCA in logarithmic time and also sum the lengths in the process of computing the LCA.
For this problem, we do the same thing, except we maintain the largest and second-largest edge weights along with the ancestor information.
Comments
Centroid Decomposition is also a valid solution. .