Editorial for COCI '16 Contest 1 #4 Mag
Submitting an official solution before solving the problem yourself is a bannable offence.
If the amount of magic in the node with the minimal magic is
If there are nodes of magic
- a path consisting of
one-magic nodes, for some - a path consisting of
nodes where only the central node is of magic , all the rest are one-magic nodes.
The proof reduces to breaking down the assumed minimal optimal path to two suitably selected parts. Then one of the parts must also be optimal, except in the specified cases, which contradicts the fact that it is minimal.
In solving this task, we will use the weaker claim: the optimal path consists of at most one node that is not a one-magic node. Let's call a path through node
In order to do this, we will use dynamic programming in two DFS traversals over the tree. Let's root the tree and, in the first DFS traversal, for each node
- the longest
-good path that starts in and is contained in a subtree of , - the same thing for each truncated subtree of
that consists of subtrees of a prefix of its children, - the same thing for each truncated subtree of
that consists of subtrees of a suffix of its children.
Now, using dynamic programming for prefixes and suffixes of children, we can determine the longest
The previous dynamic programming approach is used in the second DFS traversal. When we're in node
When we have the longest
Comments