题解:CF1031B Curiosity Has No Limits
CuteGielHina
·
·
题解
题目传送门
Problem
给定两个长度为 n−1 的序列 a 和 b(元素范围 0 \le a_i,b_i \le 3),要求判断是否存在长度为 n 的序列 t(元素范围 0 \le t_i \le 3),使得对每个 1 \le i \le n−1 满足:
$t_i \land t_i + 1 = b_i$(按位与)
若存在,输出任意一个满足条件的序列;否则输出 `NO`。
# Solution
虽然这题的 $n$ 可以干到 $1 \times 10 ^ 5$,但是它的 $0 \le t_i \le 3$,因此可以用暴力点的办法来算。
显然对于任意两个整数 $x$ 和 $y$,有以下两个性质:
1. 必要前置条件(与题目有关):$b_i$ 的二进制位必须是 $a_i$ 的子集,即 $(a_i \land b_i) = b_i$。若某一位置不满足此条件,直接判定无解(因为按位与的结果的二进制位只能是按位或结果的子集)。
2. 和的等价关系:$x + y = (x \mid y) + (x \land y)$。证明:按位分析,若某一位上 $x$ 和 $y$ 都为 $1$,则或为 $1$、与为 $1$,和为 $2$;若仅有一个为 $1$,则或为 $1$、与为 $0$,和为 $1$;若都为 $0$,则或和与都为 $0$,和为 $0$。两种方式计算的和完全等价。
据此,可以思考出解题步骤:
1. 先检查所有 $i$ 是否满足 $(a_i \land b_i) = b_i$,不满足则直接输出 `NO`。
2. 枚举 $t_1$ 的所有可能值($0、1、2、3$):
对于每个 $t_1$,依次推导 $t_2,t_3,...,t_n$:
根据性质 $2$,$t_i+1=(a_i+b_i) − t_i$。
验证 $t_i+1$ 是否满足:$0\le t_i+1 \le 3$,且 $t_i \mid t_i+1=a_i$、$t_i \land t_i+1=b_i$。
若验证通过,继续推导;否则该初始值 $t_1$ 无效,换下一个。
3. 若某一初始值能推导出完整的序列,则输出 `YES` 和该序列。
若所有初始值都尝试失败,输出 `NO`。
这个做法复杂度大概是 $O(n)$ 的(实际会慢一点),对于 $n \le 1 \times 10 ^ 5$ 的数据完全够了。
代码
```cpp
#include <bits/stdc++.h>
#define ll long long
#define kg putchar(' ')
#define hh putchar('\n')
#define fr(i,a,b) for(int i = a;i <= b;++i)
#define fo(i,a,b) for(int i = a;i >= b;--i)
#define ls(x) x << 1
#define rs(x) x << 1 | 1
#define lowbit(x) x & -x
using namespace std;
const int N = 2e5+5;
inline int read(){
int k = 0,f = 1;
char c = getchar();
while(c < '0' || c > '9'){
if(c == '-') f = -1;
c = getchar();
}
while(c >= '0'&& c <= '9') k = k * 10 + c - '0',c = getchar();
return k * f;
}
inline void write(int x){
if(x < 0) putchar('-'),x = -x;
if(x < 10) putchar(x + '0');
else write(x / 10),putchar(x % 10 + '0');
}
int a[N],b[N],n;
vector<int> slv(int x){
vector<int> t;
int y,z,sum;
t.push_back(x);
fr(i,0,n-2){
y = t.back();
sum = a[i] + b[i];
z = sum - y;
if (z > 3 || z < 0) return {};
if ((y | z) != a[i] || (y & z) != b[i]) return {};
t.push_back(z);
}
return t;
}
int main(){
n = read();
fr(i,0,n-2) a[i] = read();
fr(i,0,n-2) b[i] = read();
fr(i,0,n-2){
if ((a[i] & b[i]) != b[i]) {
cout << "NO\n";
return 0;
}
}
fr(i,0,3) {
vector<int> r = slv(i);
if (!r.empty()) {
cout << "YES",hh;
for (int num : r) {
cout << num,kg;
}
hh;
return 0;
}
}
cout << "NO",hh;
return 0;
}
```