1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include <iostream> #include <cstdio> #include <set> #include <cstring> #define maxn 5010 #define maxm 1000010 #define INF 1000000000 #define ll long long using namespace std;
int n, a[maxn], pre[maxn], suf[maxn];
int f[maxn][maxn]; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
cin >> n; for (int i = 1; i <= n; ++i) cin >> a[i], a[i] = min(a[i], n + 1); fill(f[0], f[0] + maxn * maxn, INF); f[0][0] = 0; for (int i = 0; i < n; ++i) { fill(pre, pre + maxn, INF); fill(suf, suf + maxn, INF); int v = a[i + 1]; for (int j = 0; j <= n; ++j) { if (f[i][j] == INF) continue; if (v < j) pre[v] = min(pre[v], f[i][j]); else if (v == j) { f[i + 1][v] = min(f[i + 1][v], f[i][j]); pre[v - 1] = min(pre[v - 1], f[i][j] + 1); } else { f[i + 1][v] = min(f[i + 1][v], f[i][j] + v - j); pre[j] = min(pre[j], f[i][j] + 1); suf[j] = min(suf[j], f[i][j] + 1); } } int w = INF; for (int j = v; ~j; --j) { w = min(w, pre[j]); f[i + 1][j] = min(f[i + 1][j], w); } w = INF; for (int j = 0; j <= v; ++j) { w = min(w + 1, suf[j]); f[i + 1][j] = min(f[i + 1][j], w); } } int ans = INF; for (int i = 0; i <= n; ++i) ans = min(ans, f[n][i]); cout << ans << "\n"; return 0; }
|