题目链接:codeforces 1400 C. Binary String Reconstruction
题意:
给一个二进制字符串 w ,一个变量 x ,规则为
- if the character wi−x exists and is equal to 1, then sisi is 1 (formally, if i>x and wi−x= 1, then si=si= 1);
- if the character wi+x exists and is equal to 1, then sisi is 1 (formally, if i+x≤n and wi+x= 1, then si=si= 1);
- if both of the aforementioned conditions are false, then sisi is 0.
给你一个结果字符串,要求你找出原来的字符串,若没有,则输出-1。
解题思路:
直接进行构造,如果出现冲突,直接返回-1
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200005;
int a[maxn], b[maxn];
int main(){
int t;
cin >> t;
while(t--) {
string s;
cin >> s;
int x, n, f = 0;
cin >> x;
n = s.size();
char ans[n];
for(int i = 0; i < n; i++) { // 初始化为 x
ans[i] = 'x';
}
for(int i = 0; i < n; i++) {
if(s[i] == '0') {
if(i >= x && ans[i-x] == '1') { // 如果i>x但是它已经被赋值为1,冲突
f = 1; break;
}
if(i + x < n && ans[i+x] == '1') { // 如果i+x<n但是它被赋值为1,冲突
f = 2; break;
}
if(i >= x) ans[i-x] = '0';
if(i + x < n) ans[i+x] = '0';
}
else {
if(i >= x && ans[i-x] != '0') { // 只要不为0,就可以赋值1,这里是必须要为1
ans[i-x] = '1';
}
else if(i + x < n && ans[i+x] != '0') {
ans[i+x] = '1';
}
else {
f = 3; break;
}
}
}
if(f) {
cout << -1;
} else {
for(int i = 0; i < n; i++) {
if(ans[i] == 'x') { // 如果为x,就给他赋值为0,因为1只需满足一个,防止冲突,默认赋值为0
cout << 0;
} else {
cout << ans[i];
}
}
}
cout << endl;
}
return 0;
}

本文详细解析了Codeforces平台上的题目1400C BinaryStringReconstruction,介绍了题目的规则和要求,给出了具体的解题思路和C++代码实现,通过直接构造方法解决二进制字符串重建问题。

1067

被折叠的 条评论
为什么被折叠?



