该题加深了我对前缀和的理解。既然我们只能改变值为0的数,那就不妨把两个值为0之间的看作是一段,到第一个0之前的一段比较特殊,需要单独列出。求出前缀和,如果特殊的那一段有几个0,那么最后结果就该加几分,剩下的就找出每一段之间前缀和出现次数最多的那个值。可能你会疑惑,如果前面的0改变了,那么后面的前缀和不也该跟着改变吗?为什么我依旧用原来的前缀和值进行运算?其实除了前面特殊的一段,后面的前缀和数与其数本身的大小其实没有什么太大的关系了,既然要求出最多的得分,我们就要找出出现次数最多的前缀和数。
代码如下:
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<map>
#include<string.h>
#include<queue>
#include<unordered_map>
using namespace std;
typedef long long ll;
ll b[200005];
ll c[200005];
map<ll, ll>hh;
int main() {
ios::sync_with_stdio(false);
cin.tie();
cout.tie();
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int an = 0;
for (int i = 1; i <= n; i++) {
cin >> b[i];
if (b[i] == 0)c[++an] = i;
b[i] = b[i - 1] + b[i];
}
c[++an] = n + 1;
ll ans = 0;
for (int i = 1; i < c[1]; i++) {
if (b[i] == 0)ans++;
}
for (int i = 1; i < an; i++) {
ll bn = 0;
hh.clear();
for (int j = c[i]; j < c[i + 1]; j++) {
hh[b[j]]++;
bn = max(hh[b[j]], bn);
}
ans += bn;
}
cout << ans << "\n";
}
}