codeforces 1400 C. Binary String Reconstruction

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

题目链接: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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值