Observe that f(H) is actually the maximum distance between two nodes in the given selection, because all weights are positive (can you solve it for negative weights too?)

So we can use the same technique used to find the diameter of a tree, double dfs, but instead of dfs, we change it a little.

First we pick any node from the selection, u. Then find another node in the selection, v such that distance(u, v) is maximum for all possible v's. Now we do the same thing for v, for all possible w find maximum distance(v, w), that is the diameter. You can use LCA to calculate distance fast. Final complexity is $O(\sum_{i=1}^{m}H_i \times \lg(n))$. The log factor can be removed if you use $O(1)$ lca queries.

Another possible solution would be to use a data structure called Virtual Tree/Auxilary Tree. But the TL for the problem was too strict for this. If not implemented efficiently, it will get TLE.

Statistics

78% Solution Ratio
EgorKulikovEarliest, Apr '20
EgorKulikovFastest, 0.1s
vipghn2003Lightest, 16 MB
kzvd4729Shortest, 1400B
Toph uses cookies. By continuing you agree to our Cookie Policy.