B. 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.

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.

题意:
给你一个包含01字符的字符串s,t是字符串s的无限延伸,给你一个x求出t串前缀种0的个数-1的个数有多少个?

解析:
首先我们把01字符串变成1,-1字符串,求每个位置的前缀和。假如当前位置前缀和为3说明1的个数比-1多3个。
我们需要分类讨论如果s串遍历完的最后一个前缀和为0的话,那说明我不管怎么延伸,最后一个前缀和永远是0,所以我要是有一个x和s串中任意位置的前缀和相等,那一定存在无限个输出-1.如果没有输出0

现在讨论不为0的情况下,如何去判断等于x的位置

举个例子
字符串s:010010
字符串t:010010   010010  010010
前缀和: 101212   323434  545656

我们发现一个规律:当前在i的位置上,前缀和为sum[i],那么出现在下一个延伸中位置i所对应的前缀和为 sum[i]+ksum[n]。
所以我们只需要判断 sum[i]+k
sum[n]==x 即可。
再化简得到(x-sum[i])%sum[n]==0 .
我们还要保证(x - sum[i])和sum[n]同号,因为我们需要x - sum[i] == k * sum[n]
不要忘了还有空串的可能。

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10000;
int sum[N];
int t,n,x;
string s;
int main()
{
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %d",&n,&x);
		cin>>s;
		int m=s.size();
		for(int i=0;i<m;i++)
		{
			if(s[i]=='0') sum[i]=sum[i-1]+1;
			else sum[i]=sum[i-1]-1;
		}
		if(sum[m-1]==0)
		{
			int f=0;
			for(int i=0;i<m;i++)
			{
				if(sum[i]==x)
				{
					f=1;
					cout<<-1<<endl;
					break;
				}
			}
			if(f==0) cout<<0<<endl;
		}
		else
		{
			int res=0;
			if(x==0) ++res;//空串的情况
			for(int i=0;i<m;i++)
			{
				if((x-sum[i])%sum[m-1]==0&&(x-sum[i])/sum[m-1]>=0) res++;
			 } 
			 cout<<res<<endl;
		}
	}
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值