2021 - 8 - 12 Codeforces C. Binary String Reconstruction

Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows:

if the character wi−x exists and is equal to 1, then si is 1 (formally, if i>x and wi−x= 1, then si= 1);
if the character wi+x exists and is equal to 1, then si is 1 (formally, if i+x≤n and wi+x= 1, then si= 1);
if both of the aforementioned conditions are false, then si is 0.
You are given the integer x and the resulting string s. Reconstruct the original string w.

Input
The first line contains one integer t (1≤t≤1000) — the number of test cases.

Each test case consists of two lines. The first line contains the resulting string s (2≤|s|≤105, each character of s is either 0 or 1). The second line contains one integer x (1≤x≤|s|−1).

The total length of all strings s in the input does not exceed 105.

Output
For each test case, print the answer on a separate line as follows:

if no string w can produce the string s at the end of the process, print −1;
otherwise, print the binary string w consisting of |s| characters. If there are multiple answers, print any of them.

题目大意:给一个二进制字符串w 和 正整数x 可以通过一下规则构造出字符串s

  1. 当 w[i-x] 存在 且 w[i-x] ==‘1’ 时 s[i] = ‘1’;
  2. 当 w[i+x]存在 且 w[i+x] ==‘1’ 时 s[i] = ‘1’;
    现在给出字符串 s 需要重构w

题解:对于s[i] == ‘0’ ,如果w[i - x] 存在则 w[i - x] 必须为0,如果w[i + x] 存在,则w[i + x]必须为0。将w置位1,先判断0,再判断1

AC代码:

#include<iostream>
#include<string.h>
#include<cstring>
#define rep(i, a, b) for(int i = a; i < b; i ++)
typedef long long ll;
using namespace std;
int main()
{
	int t;
	cin >> t;
	while(t--){
		int x;
		string s, w;
		cin >> s >> x;
		int len = s.length();
		rep(i, 0, len){
			w += '1';
		}
		rep(i, 0, len){
			if(s[i] == '0'){
				if(i >= x){
					w[i - x] = '0';
				} 
				if(i + x < len){
					w[i + x] = '0'; 
				}
			} 
		}
		bool flag = 1;
		rep(i, 0, len){
			if(s[i] == '1'){
				if(i >= x && w[i - x] == '1'){
					continue;
				} else if(i + x < len && w[i + x] == '1'){
					continue;
				} else flag = 0;
				
			}
		}
		if(flag) cout << w << endl;
		else cout << -1 << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值