Infinite Prefixes
You are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t=ssss… For example, if s= 10010, then t= 100101001010010…
Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal to cnt0,q−cnt1,q, where cnt0,q is the number of occurrences of 0 in q, and cnt1,q is the number of occurrences of 1 in q. The number of such prefixes can be infinite; if it is so, you must say that.
A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string “abcd” has 5 prefixes: empty string, “a”, “ab”, “abc” and “abcd”.
Input
The first line contains the single integer T (1≤T≤100) — the number of test cases.
Next 2T lines contain descriptions of test cases — two lines per test case. The first line contains two integers n and x (1≤n≤105, −109≤x≤109) — the length of string s and the desired balance, respectively.
The second line contains the binary string s (|s|=n, si∈{0,1}).
It’s guaranteed that the total sum of n doesn’t exceed 105.
Output
Print T integers — one per test case. For each test case print the number of prefixes or −1 if there is an infinite number of such prefixes.
思维题
记录字符串s每个位置的前缀,也就是01之差的前缀和,只要枚举每个位置是否可以做为答案就行,有点巧妙;
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
//ios::sync_with_stdio(false);
#define inf 0x3f3f3f3f
using namespace std;
const int N=100100;
const int M=1000100;
const LL mod=20010905;
int sum[N],sum1[N],sum2[N];//正负
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
memset(sum1,0,sizeof(sum1));
memset(sum2,0,sizeof(sum2));
int n,x;
string s;
cin>>n>>x;
cin>>s;
int y=0;
for(int i=0;i<n;i++){
if(s[i]=='0') y++;
if(s[i]=='1') y--;
if(y>=0) sum1[y]++;
else sum2[-y]++;
sum[i]=y;
}
if(!y){
if(x>100000||x<-100000) cout<<0<<endl;
else if(x>=0){
if(sum1[x]) cout<<-1<<endl;
else cout<<0<<endl;
}
else if(x<0){
if(sum2[-x]) cout<<-1<<endl;
else cout<<0<<endl;
}
}
else{
int ans=0;
if(x==0) ans++;
for(int i=0;i<n;i++){
if((x-sum[i])/y>=0&&!((x-sum[i])%y)) ans++;
}
cout<<ans<<endl;
}
}
return 0;
}