题目大意:
给定字符串长度(n)和子串长度(k),接下来给出字符串,该字符串由(0),(1)和(?)组成,其中(?)可以代替(0)或(1)(代替完不能再修改),要求判断该该字符串的长度为(k)的子串中(0)和(1)的数量是否相等。
思路:
首先推出一个性质。
如果第一个子串是([s_0, s_k-1]),第二个子串是([s_1, s_k]),如果该字符串满足题意的话,一定满足(s[0] == s[k]),推广一下可以得到(s[i] == s[i\%k])。
我们也可以通过区间和来验证这个性质。
[s[i]+s[i+1]+⋯+s[i+k−1]=frac{k}{2}
]
[s[i+1]+s[i+1]+dots+s[i+k]=frac{k}{2}
]
两式相减同样可以得到:
[s[i] == s[i + k]
]
推广即可得到:
[s[i] == s[i \% k]
]
换句话说,所有模(k)位置上的数一定相同。
所以我们从第(k)为上的字符((0-index))开始检测模(k)位置上的数是否相同。
最后再判断([0, k])位置上的(k-length)子串的(0)和(1)数量是否相同。
Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int T; cin >> T;
while (T--) {
int n, k; cin >> n >> k;
string s; cin >> s;
bool ok = 1;
for (int i = k; i < n; i++) {
if (s[i] == '?' || s[i] == s[i % k]) continue;
if (s[i % k] == '?') s[i % k] = s[i];
else { ok = 0; break; }
}
int cnt0 = 0, cnt1 = 0;
for (int i = 0; i < k; i++) {
if (s[i] == '0') cnt0++;
else if (s[i] == '1') cnt1++;
}
if (cnt0 > k / 2 || cnt1 > k / 2) ok = 0;
if (ok) cout << "YES" << endl;
else cout << "NO" << endl;
}
return 0;
}