题目描述:
给定一段数字序列,有一种操作是让相邻的两个数都减1,可以操作无限次,还有一种超级操作:在普通操作前让交换两个相邻的数,超级操作可以有0次或者1次,问是否可以将数字序列全都变为0。
题解:
遇到这种问题,可以先想想分情况考虑。
- 考虑不使用超级操作的情况,令a为原数列,令b[0] = a[0], b[1] = a[1] - b[0], b[2] = a[2] - b[1], …, b[i] = a[i] - b[i - 1],若最终b[n - 1] = 0且b[i]都不小于0,则“YES”。(若从左向右“YES”,从右到左也一定“YES”,若从左到右“NO”,则从右到左也一定“NO”)。
- 考虑使用超级操作的情况,我们可以枚举每个交换的位置,但是每次枚举还要进行判断,如果暴力进行判断的话,每次花费为O(n),这显然不行。对于一个序列而言,先从前往后消去一部分,再从后往前消去另一部分,是否和只从前往后或只从后往前消除是等效的呢(能全部消掉或不能)?答案是肯定的,这也是本题的关键。我们可以想到,如果交换相邻的数字,即a[i]和a[i + 1]的话,对a[i]前面(从a[0]到a[i - 1])消去数字的过程没有任何影响,同理,对a[i + 1]后面(从a[n - 1]到a[i + 2])消去数字的过程也没有任何影响,因此,我们分别需要两个从前往后和从后往前类似于上述的数组b的预处理数组pre和suf,因此每次枚举的时候只需要判断pre[i - 1]、a[i + 1]、a[i]、sub[i + 2]是否能消为0即可,但要注意一个问题,就是若pre(或suf)在处理时出现了pre[i] > a[i + 1](或suf[i] > a[i - 1])时,此时a[i + 1] - pre[i] < 0,即pre[i + 1] < 0,此时要将其标志为-1,并且它后面的也失效,即在枚举时若发现有-1的存在,就不能采用。
AC Code:
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
//#include <unordered_set>
//#include <unordered_map>
#include <deque>
#include <list>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
//#pragma GCC optimize(2)
using namespace std;
typedef long long ll;
//cout << fixed << setprecision(2);
//cout << setw(2);
const int N = 2e5 + 6, M = 1e9 + 7, INF = 0x3f3f3f3f;
int main() {
//freopen("/Users/xumingfei/Desktop/ACM/test.txt", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while(t-- > 0) {
int n;
cin >> n;
vector<int> a(n), p(n), s(n);
for (int i = 0; i < n; i++) cin >> a[i];
p[0] = a[0], s[n - 1] = a[n - 1];
for (int i = 1; i < n; i++) {
if (p[i - 1] != -1 && a[i] >= p[i - 1]) {
p[i] = a[i] - p[i - 1];
} else {
p[i] = -1;
}
}
if (p[n - 1] == 0) {
cout << "YES" << '\n';
continue;
}
for (int i = n - 2; i >= 0; i--) {
if (s[i + 1] != -1 && a[i] >= s[i + 1]) {
s[i] = a[i] - s[i + 1];
} else {
s[i] = -1;
}
}
// if (s[0] == 0) {
// cout << "YES" << '\n';
// continue;
// }
int flag = 0;
for (int i = 0; i < n - 1; i++) {
int x = i - 1 >= 0 ? p[i - 1] : 0;
int y = i + 2 < n ? s[i + 2] : 0;
if ((x != -1 && y != -1 && a[i + 1] - x == a[i] - y && a[i + 1] - x >= 0)) {
flag = 1;
break;
}
}
if (flag == 1) {
cout << "YES" << '\n';
} else {
cout << "NO" << '\n';
}
}
return 0;
}