题意: 给定好子数组的概念:若子数组的元素之和等于元素个数,那么这个子数组就为好子数组。那么给你一个子数组序列字符串,判断该序列有多少个好子数组。
题解:首先子数组元素之和等于元素个数,那么这句话就等价于元素个数等与子数组元素的和(废话),这就意味着我们令每一个子数组元素减去1,就可以等价为子数组元素和为0的数组即为好子数组。(本来元素和是不确定的,现在变为了0,我们就可以开始胡搞了)。那么我们维护一个前缀和,如果当前前缀和为0,那么答案加一,同时我们记录前缀和同样为0的个数,那么这个前缀和减去前面这些前缀和为0的依然前缀和是0,则这些子数组也符合题意,则答案再加前面已有前缀和为0的子数组的个数就行了。
AC代码:
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
#include <vector>
#include <cmath>
#include <map>
#include <algorithm>
#define int long long
using namespace std;
const int maxn=1e6+5;
int a[maxn];
main() {
int t;
cin>>t;
while(t--) {
map<int,int>num;
int n;
string s;
cin>>n>>s;
int ans=0,sum=0;
for(int i=0;i<s.size();i++){
a[i]=s[i]-'0'-1;
sum+=a[i];
if(sum==0)ans++;
ans+=num[sum];
num[sum]++;
}
cout<<ans<<endl;
}
}