1398C 1600的题
题意:给你一列字符串,其中的字母在0~9之间,选择其中一个区间【l, r】,使得这个区间内的和等于r-l+1,问最多有多少个这样的区间。
思路:这题主要是思路比较新把,或者说我很少碰到这样的题目,就是把求有多少个区间和等于r-l+1, 转化为有多少个区间和为零,那么如何转化呢,就是把之前的该数组所有的数都减去1即可,之后的实现就比较简单了,用一个map就可以,用数组存储是不行的,因为存储不下来,而且ans要开ll,因为最多的区间为(1+1e5)*1e5/2,显然爆了int的范围,血的教训
代码如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 1e5+10;
#define int ll
inline int read(){
int x=0,f=1;char ch=getchar();
while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;
}
char str[maxn];
int a[maxn];
inline void cf(){
int t;
t = read();
while(t--){
int n = read();
scanf("%s", str);
for(int i = 0; i < n; i++){
a[i] = str[i]-'0'-1;
if(i) a[i] += a[i-1];
}
unordered_map<int, int> m;
int ans = 0;
for(int i = 0; i < n; i++){
if(a[i]==0) ans++;
if(!m[a[i]]){
m[a[i]]++;
}else {
ans += m[a[i]];
m[a[i]]++;
}
}
printf("%lld\n", ans);
}
return ;
}
signed main(){
cf();
return 0;
}