This solution is which is faster than the official editorial's but not required since .
Explanation
Let be the the minimum number of changes that must be made to the first entries so that there are breakouts among the first entries.
There are three cases when we calculate the current value of :
If the log was tampered with and the cows would NOT breakout:
- Compared to the previous day, the breakout number won't change. However, we need one more change of the log, so we transfer from .
If the log was tampered with and the cows would breakout (Notice that ):
- Compared to the previous day the breakout number increases by 1. We also need one more change of the log, so we transfer from .
If the log was NOT tampered with:
- Then the -th breakout would be on the -th day, so we transfer from .
represents the minimum cost to replace the range with .
Thus, our final DP relation is
Note that if the indices are out of bounds, the value is not considered.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {freopen("taming.in", "r", stdin);freopen("taming.out", "w", stdout);int n;cin >> n;vector<int> entry(n);
Python
with open("taming.in", "r") as read:n = int(read.readline().strip())entry = list(map(int, read.readline().strip().split()))range_ans = [[0] * n for _ in range(n)]for i in range(n):for j in range(i, n):if j > 0:range_ans[i][j] = range_ans[i][j - 1] + (0 if entry[j] == j - i else 1)else:
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!