Editorial for COCI '20 Contest 2 #4 Sjekira
Submitting an official solution before solving the problem yourself is a bannable offence.
To solve the first subtask, since , it will be possible to try all permutations of connection cutting and determine each permutation price using DFS or a disjoint set union structure.
The main caveat to solving other subtasks is that it will always be optimal to cut the connections around the maximum node in the tree first. Proof sketch: on the path between the hardest node of value and the second hardest node of value , we have to cut some connection at some point, and pay . If the connection is closer to , the cut is more cost-effective because more nodes will be in the subtree whose maximum is .
So, there will always be a solution that finds the maximum in the tree, cuts all the connections around it, finds maxima in newly formed trees, and recursively descends into them. It only remains to implement finding the maximum efficiently.
The second subtask, in which the graph is a chain, can be efficiently solved using the segment tree structure, which allows you to quickly search for the maximum at an interval (or subtree) with time complexity .
In the third subtask , it is enough to search for the maximum using DFS, with time complexity . Now we solve the main subtask.
Claim: The solution is equal to
Proof: Induct on . Base case is clear. When we cut a connection — around the maximum vertex , we add , where is the maximum vertex in the subtree of . Now adding up the formulas for the subtrees finishes the induction step.
Comments