Problem author: | Taras Derkach |
Prepared by: | Taras Derkach |
Editorial: | Taras Derkach |
Solution
Fix a vertex that we choose as the central vertex.
After that, all vertices at distance exactly from are removed.
Let us see which connected components remain.
The first component always contains the vertex itself and all its neighbors. Denote its sum by center_v:
Other components can appear only behind the vertices that were removed.
Let be a neighbor of vertex , and let be a neighbor of vertex , where x \ne v.
Then vertex is at distance exactly from , so it is removed. After removing , some components may remain behind its other neighbors.
So we need to quickly know the following value:
if there is an edge , what is the sum of the component lying on the side of vertex after removing this edge.
Denote this sum by side(x,y).
If we root the tree at vertex , then side(x,y) can be easily computed using subtree sums:
if is a child of , then side(x,y) = subtree_y;
otherwise, side(x,y) = total - subtree_x.
For each vertex , we store the two smallest and two largest values among all side(x,y) over all neighbors .
Why two? Because sometimes we need to take the best value while forbidding one specific direction. For example, when we look at a removed vertex , we cannot take the direction back to , because we came to from there.
Next, for each vertex , we store the smallest and largest sums of components that may appear after removing one of the neighbors of vertex .
In other words, for each neighbor of vertex , we take the best component behind , but not in the direction back to .
After this preprocessing, the answer for a fixed central vertex can be found quickly.
First, we have the component with sum center_v.
Then, for each neighbor of vertex , we take the smallest and largest possible component among the vertices located behind . At the same time, we must forbid the direction back to .
Among all found components, we find the minimum and maximum sum. The contrast for vertex is equal to:
The answer is the maximum of this value over all vertices .
Example
In the first example, it is optimal to choose vertex v = 4.
Then vertex is at distance exactly from it, so it is removed.
After the removal, two connected components remain:
with sum ;
\{3,4,5\} with sum 3 + 4 + 5 = 12.
Therefore, the contrast is equal to:
Complexity
We calculate subtree sums once, and then for each vertex we look through its neighbors.
Each edge is processed only a constant number of times.
Therefore, the complexity of the solution is .