Editorial for COCI '08 Contest 1 #6 Krtica
Submitting an official solution before solving the problem yourself is a bannable offence.
Since the number of edges that a mole can remove is one, it is possible to iterate through all the edges to calculate which edge needs to be added if we remove that edge.
Suppose we remove edge  and that doing so separates the tree into subtrees 
 and 
. Now we need to create a new edge 
 where vertex 
 is in subtree 
 and vertex 
 is in subtree 
. There are many ways to do this to check them all.
Notice that the diameter of the new tree will be the largest of:
- The diameter of subtree 
, of length
;
 - The diameter of subtree 
, of length
;
 - The length of the longest path in subtree 
rooted in
plus the length of the longest path in subtree
rooted in
plus one (for
).
 
The first two of these depend only on edge , the last on edge 
. For this path to be as short as possible, we choose 
 to be the halfway point on the diameter of subtree 
 and 
 to be the halfway point on the diameter of subtree 
.
The length of the new path is then:
For each choice of edge , we can calculate the shortest diameter we can achieve if we remove that edge, and it is exactly:
So we need to calculate the diameters of both subtrees. The total number of subtrees we need to do this for is , so we cannot afford a linear search for every subtree.
If we root the tree in any vertex, then subtrees isolated by removing edges from the tree can be divided into two groups – those not containing the root (call these subtrees "hanging") and those containing the root (call these "trimmed").
We can use dynamic programming to calculate the diameters of hanging subtrees. Let  and 
 be the two longest paths from vertex 
 to leafs in the tree. Then the diameter 
 of the subtree rooted at 
 is easily calculated as:
The diameters of trimmed trees can also be found using dynamic programming. This time the recursive relation is more complex and calculated in the opposite order – from root to leaves.
Once we have calculated the diameters we can easily find which edge to remove. After this, we can find the halfway points on the diameters of subtrees to find which edge to add.
The overall complexity of the solution is .
Comments