C 不平衡数组

题目地址:

https://ac.nowcoder.com/acm/contest/5881/C

基本思路:

因为每一位只能加一次,所以比较容易想到,用表示当前位置不加一,表示当前位置加一,那么我们每次只要关心前后两位在加一或不加的状态下会不会冲突就行了,不冲突我们就能递推了,具体转移方程如下:

    if (a[i] != a[i - 1]) dp[i][0] = min(dp[i][0], dp[i - 1][0]);
    if (a[i] != (a[i - 1] + 1)) dp[i][0] = min(dp[i][0], dp[i - 1][1]);
    if ((a[i] + 1) != a[i - 1]) dp[i][1] = min(dp[i][1], dp[i - 1][0] + b[i]);
    if ((a[i] + 1) != (a[i - 1] + 1)) dp[i][1] = min(dp[i][1], dp[i - 1][1] + b[i]);

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define ll long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF (int)1e18

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

const int maxn = 2e5 + 10;
int n,a[maxn],b[maxn];
ll dp[maxn][2]; // 0 不+1, 1 加一;
signed main() {
  IO;
  n = read();
  for(int i = 1 ; i <= n ; ++i){
    a[i] = read(),b[i] = read();
    dp[i][0] = dp[i][1] = INF;
  }
  dp[1][0] = 0; dp[1][1] = b[1];
  for(int i = 2; i <= n ; ++i) {
    if (a[i] != a[i - 1]) dp[i][0] = min(dp[i][0], dp[i - 1][0]);
    if (a[i] != (a[i - 1] + 1)) dp[i][0] = min(dp[i][0], dp[i - 1][1]);
    if ((a[i] + 1) != a[i - 1]) dp[i][1] = min(dp[i][1], dp[i - 1][0] + b[i]);
    if ((a[i] + 1) != (a[i - 1] + 1)) dp[i][1] = min(dp[i][1], dp[i - 1][1] + b[i]);
  }
  ll ans = min(dp[n][0],dp[n][1]);
  cout << ans << '\n';
  return 0;
}