codeforces 1221D DP

个人博客链接:https://blog.nuoyanli.com/2020/03/25/cf1221d/

链接

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

题意

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

思路

不难想到,对于一个数来说,它要么不变,要么加 1 1 1,要么加 2 2 2,所以可以 d p [ n ] [ 3 ] : dp[n][3]: dp[n][3]:

  • d p [ n ] [ 0 ] dp[n][0] dp[n][0]表示 a i a_i ai不变符合条件的最小代价
  • d p [ n ] [ 1 ] dp[n][1] dp[n][1]表示 a i a_i ai+1符合条件的最小代价
  • d p [ n ] [ 2 ] dp[n][2] dp[n][2]表示 a i a_i ai+2符合条件的最小代价

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

参考代码

#include 
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;
}

你可能感兴趣的:(ACM,#,DP,#,codeforces)