Infinite Prefixes

Infinite Prefixes

time limit per test 2 seconds

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,qis 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≤10^5, −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 10^5.

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.

Input

4
6 10
010010
5 3
10101
1 0
0

2 0
01

Output

3
0
1
-1

Note

In the first test
case, there are 3 good prefixes of t: with length 28, 30 and 32.

题解

让我们将长度为i的前缀表示为pref(i)。

我们可以注意到每个pref(i)=k⋅pref(n)+ pref(i mod n)

其中k =⌊in⌋,而+是串联。

则长度为i的前缀的bal(i)等于k⋅bal(n)+ bal(i mod n)。现在有两种情况:bal(n)等于或不等于0。

如果bal(n)= 0,则如果存在j(0≤j<n),则对于每一个k≥0bal(j + kn)= x,bal(j)= then,则答案为-1。

j不超过一个可能的k:因为方程j +k⋅bal(n)= x有零个或一个解。

当且仅当x−j≡0modbal(n)并且k = x-jbal(n)≥0时,该解才存在。

因此,仅需预先计算bal(n),并针对每个0≤j<n检查方程式。

#include<bits/stdc++.h>
using namespace std;
int main()
{
       long long T,n,x;
       string s;//用char数组慢 
       scanf("%lld",&T);
       while(T--)
       {
             cin>>n>>x>>s;
             int num0=0,num1=0;
             for(int i=0;i<n;i++)
             {
                    if(s[i]=='0')num0++; else num1++;
             }
             int k=num0-num1;
             if(k==0)
             {
                    int i;
                    for(i=0;i<n&&k!=x;i++)
                    {
                          if(s[i]=='0')k++; else k--;
                    }
                    if(k==x)printf("-1\n");
                    else   printf("0\n");
             }
             else
            {
                   int ans=0,j=0;
                   for(int i=0;i<n;i++)
                    {
                           if((x-j)%k==0&&(x-j)/k>=0)ans++;
                          if(s[i]=='0')j++; else j--;
                    }
                    printf("%d\n",ans);
             }
       }
}
发布了25 篇原创文章 · 获赞 24 · 访问量 588

猜你喜欢

转载自blog.csdn.net/rainbowsea_1/article/details/104499243
今日推荐