C. Sonya and Problem Wihtout a Legend - Codeforces Round 371 (Div. 1)
Solutions Codeforces 动态规划 贪心
Lastmod: 2024-07-31 周三 22:10:04

https://codeforces.com/contest/713/problem/C

题目大意

给定 $n \le 3000$ 的数组 $a$。每次操作可以使数组中的某个位置的值 $+1$ 或 $-1$。 问最少得操作次数使得数组严格单调递增。

简要题解

重要的 trick:

$a_i < a_{i + 1} \iff a_i + 1 \le a_{i + 1} \iff a_i + 1 - i \le a_{i + 1} - i \iff a_i - i \le a_{i + 1} - (i + 1)$

这样一来我们可以把这个问题转化为一个更好解决的带等号的式子。

有等号的题目有一个显然的结论就是结果中的所有数字会是 $a$ 中出现的数字。 因此用 $dp[i][j]$ 表示到 $1~i$ 位置已经处理完,尾巴是 $a_j$ 的最好结果即可。

这里为了方便转移,我们可以用另一个数组 $b$ 把 $a$ 中的出现的数字排序,方便转移。

显然这个转移可以滚动数组优化。

复杂度

$T$:$O(n^2)$

$S$:$O(n)$

代码实现

#include <bits/stdc++.h>
using namespace std;

int io_=[](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();

using LL = long long;
using ULL = unsigned long long;
using LD = long double;
using PII = pair<int, int>;
using VI = vector<int>;
using MII = map<int, int>;

template<typename T> void cmin(T &x,const T &y) { if(y<x) x=y; }
template<typename T> void cmax(T &x,const T &y) { if(x<y) x=y; }
template<typename T> bool ckmin(T &x,const T &y) { 
    return y<x ? (x=y, true) : false; }
template<typename T> bool ckmax(T &x,const T &y) { 
    return x<y ? (x=y, true) : false; }
template<typename T> void cmin(T &x,T &y,const T &z) {// x<=y<=z 
    if(z<x) { y=x; x=z; } else if(z<y) y=z; }
template<typename T> void cmax(T &x,T &y,const T &z) {// x>=y>=z
    if(x<z) { y=x; x=z; } else if(y<z) y=z; }

// mt19937 rnd(chrono::system_clock::now().time_since_epoch().count());
// mt19937_64 rnd_64(chrono::system_clock::now().time_since_epoch().count());

/*
---------1---------2---------3---------4---------5---------6---------7---------
1234567890123456789012345678901234567890123456789012345678901234567890123456789
*/

const LL INF = 0x3f3f3f3f3f3f3f3f;

void solve() {
  int n; cin >> n;
  vector<int> a(n);
  for (int& i : a) cin >> i;

  for (int i = 0; i < n; i++) {
    a[i] -= i;
  }
  vector<int> b = a;
  sort(b.begin(), b.end());

  vector<LL> dp(n, INF);

  dp[0] = 0;

  for (int i = 0; i < n; i++) {
    LL bst = INF;
    for (int j = 0; j < n; j++) {
      cmin(bst, dp[j]);

      dp[j] = bst + abs(a[i] - b[j]);
    }
  }

  LL ans = INF;
  for (int i = 0; i < n; i++) {
    cmin(ans, dp[i]);
  }
  cout << ans << '\n';
}

int main() {
  int t = 1; 
  // cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}

Prev: B. Searching Rectangles - Codeforces Round 371 (Div. 1)
Next: D. Dense Subsequence - Intel Code Challenge Final Round