http://codeforces.com/problemset/problem/1295/B

http://codeforces.com/problemset/problem/1295/B
B. Infinite Prefixes
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Example
inputCopy
4
6 10
010010
5 3
10101
1 0
0
2 0
01
outputCopy
3
0
1
-1
Note
In the first test case, there are 3 good prefixes of t: with length 28, 30 and 32.

计算前缀和后,辨别前缀和是否为0,如果是0,只需要查看输入的x是否在前缀和数组里出现过,如果出现过,则这个序列就有无穷个,不然就0个;前缀和如果非0,那么对每一位,看x减去当前位置前缀和后是否是总前缀和的整数倍,切倍数大于等于0,成立则res++;

重点就在于前缀和非0,res计算,这个方法十分巧妙,对循环节的利用非常到位,以后再遇见类似的题可以想一想这个巧点。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=1e5+5; 
char str[maxn];
int pre[maxn];
int main() {
	int t;
	cin>>t;
	while(t--) {
		int n,m;
		cin>>n>>m;
		scanf("%s",str+1);
		pre[0]=0;
//		cout<<endl;
		for(int i=1;i<=n;i++) {
			if(str[i]=='0') pre[i]=pre[i-1]+1;
			else pre[i]=pre[i-1]-1;
//			cout<<i<<":"<<pre[i]<<endl;
		}
//		cout<<endl;
		if(pre[n]) {
			int res=0;
			if(!m) res++;
			for(int i=1;i<=n;i++) {
				if((m-pre[i])%pre[n]==0&&(m-pre[i])/pre[n]>=0) res++;
			}
			printf("%d\n",res);
		}
		else {
			int res=0;
			for(int i=1;i<=n;i++) {
				if(pre[i]==m) {
					res++;
				}
			}
			if(res) {
				printf("-1\n");
			} 
			else {
				printf("0\n");
			}
		}
	}
}
//6 353709959
//110000
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值