题解:P9566 [SDCPC 2023] Difficult Constructive Problem
zhang_kevin · · 题解
首先分析
显然,当
因此如果
注意如果两个位置都是问号,则需要都尝试一遍。
下面考虑在 check 函数。
我们先贪心地把问号全改成
设
如果 100...01 的东西变成 111...11,使得
如果 000 的东西变成 010,使得
为了保证字典序最小,上述操作应该倒序考虑。
特别的,
参考代码:
#include<bits/stdc++.h>
using namespace std;
int n, k; string t;
inline bool check(string s){
int cnt = 0; t = s;
for(int i = 0; i < n; i++) if(s[i] == '?') t[i] = '0';
for(int i = 1; i < n; i++) if(t[i - 1] != t[i]) cnt++;
if(cnt > k){
int lst = -1;
for(int i = n - 1; i >= 0; i--){
if(s[i] != '?'){
if(lst == -1){lst = i; continue;}
if(s[i] == '1' && s[lst] == '1'){
if(lst > i + 1 && cnt > k){
for(int j = i + 1; j < lst; j++) t[j] = '1';
cnt -= 2;
}
}
lst = i;
}
}
}
if(cnt < k){
for(int i = n - 2; i >= 1; i--){
if(s[i] == '?'){
if(t[i + 1] == '0' && t[i - 1] == '0'){
if(cnt < k){
t[i] = '1', cnt += 2;
}
}
}
}
}
return cnt == k;
}
#define chk(s) if(check(s)){cout << t << '\n'; continue;}
signed main(){
// freopen("memory.in", "r", stdin);
// freopen("memory.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
int T; cin >> T;
while(T--){
string s; cin >> n >> k >> s;
if(s[0] == '?' && s[n - 1] == '?'){
s[0] = '0', s[n - 1] = s[0] ^ (k & 1); chk(s);
s[0] = '1', s[n - 1] = s[0] ^ (k & 1); chk(s);
}
else if(s[0] == '?'){s[0] = s[n - 1] ^ (k & 1); chk(s);}
else if(s[n - 1] == '?'){s[n - 1] = s[0] ^ (k & 1); chk(s);}
else chk(s);
cout << "Impossible" << '\n';
}
return 0;
}