A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine whether you can make a k-balanced bitstring by replacing every ? characters in s with either 0 or 1.
A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤104). Description of the test cases follows.
The first line of each test case contains two integers n and k (2≤k≤n≤3⋅105, k is even) — the length of the string and the parameter for a balanced bitstring.
The next line contains the string s (|s|=n). It is given that s consists of only 0, 1, and ?.
It is guaranteed that the sum of n over all test cases does not exceed 3⋅105.
Output
For each test case, print YES if we can replace every ? in s with 0 or 1 such that the resulting bitstring is k-balanced, or NO if it is not possible.
Example
inputCopy
9
6 4
100110
3 2
1?1
3 2
1?0
4 4
???
7 4
1?0??1?
10 10
11??11??11
4 2
1??1
4 4
?0?0
6 2
???00
outputCopy
YES
YES
NO
YES
YES
NO
NO
YES
NO
题意:给你一个字符串长度和子串的长度k,其中字符串中的 ? ? ?可以代替0或1,(确定代替之后就不能更改了)输入一个字符串,请你判断该字符串的所有 k 长度的子串中的0和1数量是不是相等的。
题解:这题的关键在于所有相邻的长度为k的字串之间都是有关系的。比如s[0]-s[k-1] 以及 s[1]-s[k] ,会发现他们的区别只有 s[0]和s[k] ,其余都是相等的,但是如果要满足所有的子串中0和1的数量是相等的,则必须要满足 s[0]=s[k]。举个例子,若s[0]-s[k-1]=“1100” ,那么s[k]必须与s[0]相等,即取1 变为"1001" ,只有这样才成立,因此我们的第一步便是需要字符串s必须满足 s[i%k]=s[i]
(k<=i<s.length()),判断完这个之后只需再判断第一个字串是否满足1的个数和0的个数是否相等即可。
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int a[100005];
int main()
{
int t,n,k;
cin>>t;
string s;
while(t--)
{
cin>>n>>k;
cin>>s;
int flag=0,x=0,y=0;
//首先可以发现,s所有相邻的子串实际上只改变了一个字符 s[0]-s[k-1] -> s[1]-s[k] 即 s[0] 变成了 s[k],
//我们必须要满足s[0]=s[k] 不然必定不可能所有的子串 1的个数=0的个数,比如s[0]-s[k-1]="1100" 那么s[k]必须要为1,使得s[1]-s[k]="1001",否则不成立
for(int i=k;i<s.length();i++) //for循环满足 s[0]对应s[k], s[1]对应s[k+1]......
{
if(s[i]=='?' || s[i]==s[i%k])
continue;
if(s[i%k]=='?') //如果s[i%k]为'?',那就让他变成与s[i] 相等
s[i%k]=s[i];
else
{
flag=1; //不成立的话必定是"NO"
break;
}
}
for(int i=0;i<s.length()-(n-k);i++) //然后判断第一个字符串是否符合
{
if(s[i]=='1')
x++;
if(s[i]=='0')
y++;
}
if(x>k/2 || y>k/2)
flag=1;
if(flag==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}