Editorial
List the vertices in DFS preorder as , where . In preorder, the subtree of every vertex forms one contiguous interval.
Let be the size of the subtree rooted at , and define the position immediately after that subtree as
It is possible that .
If a --force patch is applied to a vertex, no additional operation inside its subtree is necessary. Removing all such redundant operations keeps every vulnerability fixed and never increases the cost or the number of --force patches.
Let be the minimum cost to fix all vulnerabilities among using at most patches.
When , only normal patches may be used, so
For , there are two choices at .
- Do not use
--forceat . The cost is .
Therefore,
Since , for each the states can be evaluated in the order . Vertex cannot be patched, so the answer is .
To compute the current layer , we only need from the same layer and from the previous layer. Thus only two arrays of length are needed.
The preorder and subtree sizes take time. The DP takes time and memory.
Solution written by GPT5.6