codeforces1221D DP

文章目录[x]
  1. 1:链接
  2. 2:题意
  3. 3:思路
  4. 4:参考代码

csdn博客链接:https://blog.csdn.net/nuoyanli/article/details/105107542


链接

https://codeforces.com/problemset/problem/1221/D

题意

你有一个长度为n的序列,每次你可以令的值加,但需要消耗的代价。现在,你希望花费尽可能少的代价修改你的序列,使序列中任意相邻两项不相等。

思路

不难想到,对于一个数来说,它要么不变,要么加,要么加,所以可以

  • 表示不变符合条件的最小代价
  • 表示+1符合条件的最小代价
  • 表示+2符合条件的最小代价

状态转移不难想,详细见代码:

参考代码

#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false), cin.tie(0)
#define endl '\n'
#define PB push_back
#define FI first
#define SE second
#define m_p(a, b) make_pair(a, b)
const double pi = acos(-1.0);
const double eps = 1e-9;
typedef long long LL;
const int N = 1e6 + 10;
const int M = 1e5 + 10;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const double f = 2.32349;
LL dp[N][4], a[N], b[N];
LL min3(LL a, LL b, LL c) { return min(min(a, b), c); }
void solve() {
  IOS;
  int t, n;
  cin >> t;
  while (t--) {
    cin >> n;
    for (int i = 1; i <= n; i++) {
      cin >> a[i] >> b[i];
      dp[i][0] = dp[i][1] = dp[i][2] = 0;
    }
    for (int i = 1; i <= n; i++) {
      if (a[i - 1] == a[i]) {
        dp[i][0] = min(dp[i - 1][1], dp[i - 1][2]);
        dp[i][1] = min(dp[i - 1][0], dp[i - 1][2]) + b[i];
        dp[i][2] = min(dp[i - 1][0], dp[i - 1][1]) + 2 * b[i];
      } else if (a[i - 1] + 1 == a[i]) {
        dp[i][0] = min(dp[i - 1][0], dp[i - 1][2]);
        dp[i][1] = min(dp[i - 1][1], dp[i - 1][0]) + b[i];
        dp[i][2] = min3(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2]) + 2 * b[i];
      } else if (a[i - 1] - 1 == a[i]) {
        dp[i][0] = min3(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2]);
        dp[i][1] = min(dp[i - 1][1], dp[i - 1][2]) + b[i];
        dp[i][2] = min(dp[i - 1][0], dp[i - 1][2]) + 2 * b[i];
      } else if (a[i - 1] + 2 == a[i]) {
        dp[i][0] = min(dp[i - 1][0], dp[i - 1][1]);
        dp[i][1] = min3(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2]) + b[i];
        dp[i][2] = min3(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2]) + 2 * b[i];
      } else {
        dp[i][0] = min3(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2]);
        dp[i][1] = min3(dp[i - 1][0], dp[i - 1][1], dp[i - 1][2]) + b[i];
        dp[i][2] = min(dp[i - 1][1], dp[i - 1][2]) + 2 * b[i];
      }
    }
    cout << min3(dp[n][0], dp[n][1], dp[n][2]) << endl;
  }
}
signed main() {
  solve();
  return 0;
}

 


点赞

发表评论

昵称和uid可以选填一个,填邮箱必填(留言回复后将会发邮件给你)
tips:输入uid可以快速获得你的昵称和头像