2021-08-12 CodeForce C - Balanced Bitstring

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.

题目大意:一个字符串任意一个长度为k 的子串其中的0,1个数相等,那么这个字符串就是k-balance 给一个仅有,0,1,?的字符串,其中?可以代表任何值 ,这个字符串是否是k-balance

题解:对于任意两个相邻的子串l->r,l + 1 -> r + 1,它们惟一的区别就是str[l] 和str[r + 1],如果第一个子串满足,那么第二个子串满足的条件就是str[l] == str[r + 1] (这点很容易想到,但是应该再深一步),
即为str[i] == str[i%k]

AC代码:

#include<bits/stdc++.h>
#define rep(i, a, b) for(int i = a; i <= b; i ++)
using namespace std;
typedef long long ll;
int a[300005];
int b[300005];
int main()
{
	int t = 1;
	cin >> t;
	while(t--){
		int n, k;
		string str;
		cin >> n >> k;
		cin >> str;
		int cnt0 = 0, cnt1 = 0;
		int p = 0;
		bool flag = 1;
		
		rep(i, 0, n - 1){
			if(str[i] == '?' || str[i] == str[i%k]){
				continue;
			}
			if(str[i%k] == '?'){
				str[i%k] = str[i];
			} else {
				flag = 0;
				break;
			}
		}
		
		//判断第一个字符串是否满足题意 
		rep(i, 0, k - 1){
			if(str[i] == '0'){
				cnt0++;
			}else if(str[i] == '1')cnt1 ++;
		}
		if(cnt1 > k/2 || cnt0 > k/2){
			flag = 0;
		}
		
		if(flag) cout <<"YES" <<endl;
		else cout << "NO\n";
	}
}

有几个坑:
1. 如果第一个子串里面有问号,那用后面子串没有问好的部分赋值,既可以保证所有的子串都满足这个递推关系。
2. 检验第一个子串必须要在赋值之后才可以进行。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值