Explanation
Naive Solution
We observe that any operation will only affect nodes of the same depth. Thus, instead of solving for all depths at once, we can take the sum of the minimum cost to fill in each depth.
Consider the set of nodes at depth relative to the root. Define as the minimum cost to fill in all vertices of depth in the subtree of , only considering operations selecting vertices at or lower.
- If is of depth (relative to the root), then we must fill it in with cost
- Otherwise, we can either select to incur a cost of by operating on , or not operate on and instead solve for each subtree:
Our answer will be the sum of for each value of , yielding a solution in time.
Virtual Tree Optimization
One observation we can make is for a long chain ending at , we can process it quickly by taking
We will aim to leverage this fact. Define as the set of vertices at depth , and take to be the virtual tree of .
We continue in a similar fashion to previously, but we only compute dynamic programming values for nodes in . The range minimum query can be answered using data structures in logarithmic or linear time.
Implementation
Time Complexity:
#include <bits/stdc++.h>using namespace std;using ll = long long;constexpr int MAX_N = 1e5 + 1;constexpr int LG = 17;int tin[MAX_N], tout[MAX_N], d[MAX_N], lift[MAX_N][LG], timer;ll dp[MAX_N];
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!