题解:CF2112B Shrinking Array

· · 题解

题目大意

你得到了一个长度为 n 的数组,你要按以下方法使得这个数组长度至少为 2 且有两个相邻的数的差小于 2:

我们发现如果有三个相邻的数 x,y,z,满足 x<y,y>z 或 x>y,y<z 则可以通过一次操作删掉 y 并把 x,z 中的一个数变为与另一个相等的数。

反之如果不满足这一个条件,原数组为一个递减或递增的数组,则不能满足要求。所以按上面判断,如果有输出 1 否则输出 -1。

题目代码

#include <bits/stdc++.h>
#define int long long

using namespace std;

const int kMaxN = 1010;

int a[kMaxN], t, n, ans;

signed main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  for (cin >> t; t--;) {
    cin >> n, ans = -1;
    for (int i = 1; i <= n; i++) {
      cin >> a[i];
    }
    for (int i = 1; i < n; i++) {
      ans = (abs(a[i] - a[i + 1]) <= 1 ? 0 : ans);
    }
    for (int i = 2; i < n; i++) {
      ans &= (a[i - 1] < a[i] && a[i] > a[i + 1]) || (a[i - 1] > a[i] && a[i] < a[i + 1]) ? 1 : -1;
    }
    cout << ans << '\n';
  }
  return 0;
}