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
- 当 w[i-x] 存在 且 w[i-x] ==‘1’ 时 s[i] = ‘1’;
- 当 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;
}