Good Subarrays【前缀和】

题目描述:原题链接

You are given an array a1,a2,…,an consisting of integers from 0 to 9. A subarray al,al+1,al+2,…,ar−1,ar is good if the sum of elements of this subarray is equal to the length of this subarray (∑i=lrai=r−l+1).

For example, if a=[1,2,0], then there are 3 good subarrays: a1…1=[1],a2…3=[2,0] and a1…3=[1,2,0].

Calculate the number of good subarrays of the array a.

Input
The first line contains one integer t (1≤t≤1000) — the number of test cases.

The first line of each test case contains one integer n (1≤n≤105) — the length of the array a.

The second line of each test case contains a string consisting of n decimal digits, where the i-th digit is equal to the value of ai.

It is guaranteed that the sum of n over all test cases does not exceed 105.

Output
For each test case print one integer — the number of good subarrays of the array a.

Example
input
3
3
120
5
11011
6
600005
output
3
6
1

思路:

首先求区间和想到前缀和,但是直接求复杂度O(n^2)会超时。我们可以发现,如果 b[i2] - i2 = b[i1] - i1 —> b[i2] - b[i1] = i2 - i1 ,也就是如果有两处前缀和减去前缀长度相等,说明它们之间的序列符合要求,有多个的话,每次取一段有(n-1)种,每次取两段有(n-2)种…取n-1段有1种,所以是等差数列求和。注意要把长度直接等于前缀和的加到答案中。

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <map>
#include <vector>
using namespace std;
typedef long long ll;
const int N=100010;
 
int b[N];
map<int,int> q;
int main()
{
    int T; scanf("%d",&T);
    while(T--)
    {
        int n; scanf("%d",&n);
        char s[N]; scanf("%s",s);
        memset(b,0,sizeof b);
        ll res=0,len=strlen(s);
        for(int i=1;i<=len;i++)
        {
            b[i]=b[i-1]+s[i-1]-'0';
            if(b[i]==i) res++;
        }
        q.clear();
        vector<int> k;
        for(int i=1;i<=n;i++)
        {
            q[b[i]-i]++;
            if(q[b[i]-i]==1) k.push_back(b[i]-i);
        }
        for(int x:k)
        {
            ll tmp=q[x];
            res+=tmp*(tmp-1)/2;
        }
        printf("%lld\n",res);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值