题目大意
你得到了一个长度为 的数组,你要按以下方法使得这个数组长度至少为 且有两个相邻的数的差小于 :
- 选择一个数 ,删掉 和 ,在原来的位置上添加一个比 大,比 小的数。
题目思路
我们可以先判断原数组是否是满足要求,如果是答案为 。
我们发现如果有三个相邻的数 ,满足 或 则可以通过一次操作删掉 并把 中的一个数变为与另一个相等的数。
反之如果不满足这一个条件,原数组为一个递减或递增的数组,则不能满足要求。所以按上面判断,如果有输出 否则输出 。
题目代码
#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;
}