C. Good Subarrays Educational Codeforces Round 93 (Rated for Div. 2)

C. Good Subarrays

time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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

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

Calculate the number of good subarrays of the array a�.

Input

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

The first line of each test case contains one integer n� (1≤n≤1051≤�≤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 105105.

Output

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

Example

input

Copy

3
3
120
5
11011
6
600005

output

Copy

3
6
1

Note

The first test case is considered in the statement.

In the second test case, there are 66 good subarrays: a1…1�1…1, a2…2�2…2, a1…2�1…2, a4…4�4…4, a5…5�5…5 and a4…5�4…5.

In the third test case there is only one good subarray: a2…6�2…6.

题目大致意思:以string型给每个位置的数值,求区间的和与区间长度相等的区间有多少个。

理解题目意思后可以用前缀和求所有的位置的值为多少,用前缀和来算v[i]和i的差值,当一样的差值出现时,就是多了这个差值的个数的区间,此差值++。

不好理解?上图!

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl "\n"

const ll N = 1e5+7;
ll n;
ll v[N];//前缀和 
string s;

void solve(){
	cin >> n >> s;
	s=" "+s;
	unordered_map<ll, ll>mp;//记录差值出现的次数 
	v[0]=0;mp[0]=1;//当第一次出现v[i]==i时,就可以取0~i这个区间 
	ll sum=0;
	for(ll i = 1 ; i <= n ;  i++){
		v[i] = v[i-1] + s[i]-'0';//前缀和 
		sum+=mp[v[i]-i];//加上当前这个差值出现的次数 
		mp[v[i]-i]++;//差值出现的次数++ 
	}
	cout << sum << endl;
	return;
}

int main(){
	ll t=1;cin >> t;
	while(t--)solve();
	return 0;
}

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值