题目链接:
(https://codeforces.com/contest/1512/problem/C)
思路:
1.遍历字符串,将可以确定的‘?’给确定了,处理完之后剩下的‘?’必然对称
2.遍历字符串,每当遇到‘?’,可以用的1比较多那就换成1,否则换成0,时刻需要注意是否不符合题意,若不符合题意,直接输出-1
1A代码(还可以精简)
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
int cnt[2];
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
part:
while (t--) {
memset(cnt, 0, sizeof(cnt));
int w, e;
cin >> w >> e;
string a;
cin >> a;
a = "." + a;
int sz = a.size()-1;
for (int i = 1; i <= sz; i++)if (a[i] == '1')cnt[1]++; else if (a[i] == '0')cnt[0]++;
for (int i = 1; i <= sz / 2; i++) {
int pos = sz - i + 1;
if (a[i] != a[pos] ) {
if (a[i] != '?' && a[pos] != '?') { cout << -1 << '\n'; goto part; }
else if (a[i] == '?' && a[pos] != '?') { a[i] = a[pos]; cnt[a[pos] - '0']++; }
else if (a[i] != '?' && a[pos] == '?') { a[pos] = a[i]; cnt[a[i] - '0']++; }
}
}
int zero = w - cnt[0];
int one = e - cnt[1];
for (int i = 1; i <= sz; i++) {
if (zero < 0 || one < 0) { cout << -1 << '\n'; goto part; }
int pos = sz - i + 1;
if (a[i] == '?') {
if (zero > one) {
if (zero - 2 >= 0) {
a[i] = a[pos] = '0';
zero -= 2;
}
else {
if (pos == i&&zero>=1) {
a[i] = '0';
zero--;
}
else {
cout << -1 << '\n';
goto part;
}
}
}
else {
if (one - 2 >= 0) {
a[i] = a[pos] = '1';
one -= 2;
}
else {
if (pos == i && one >= 1) {
a[i] = '1';
one--;
}
else {
cout << -1 << '\n';
goto part;
}
}
}
}
}
for (int i = 1; i <= sz; i++)cout << a[i];
cout << '\n';
}
}