题解:AT_agc045_a [AGC045A] Xor Battle
Philia093_SR
·
·
题解
考虑 DP。
初始:$dp_{n+1,0}=1$,其他 $dp_{n+1,j}=0$。
转移:
$$
\left\{\begin{matrix}
dp_{i,j}=dp_{i+1,j\oplus a_i}~\&~dp_{i+1,j},&(s_i=0)\\
dp_{i.j}=dp_{i+1,j\oplus a_i}~\mid~dp_{i+1,j},&(s_i=1)
\end{matrix}\right.
$$
答案:$dp_{1,0}$。
复杂度太高,考虑优化。
为真的 dp 构成一个集合。具体地,$S_i=\{j\mid dp_{i,j}=1\}$。
初始: $S_{n+1}=\{0\}$。
转移:
$$
\left\{\begin{matrix}
S_i=S_{i+1}\cup (S_{i+1}\oplus a_i),&s_i=0\\
S_i=S_{i+1}\cap (S_{i+1}\oplus a_i),&s_i=1
\end{matrix}\right.
$$
(其中 $S\oplus a=\{x\oplus a\mid x\in S\}$)
上述可用线性基维护。
详细地,令 $S=V\oplus c$,$V$ 是线性子空间(异或封闭),$c$ 是偏移量。
当 $s_i=0$,即 $S_i=S_{i+1}\cup (S_{i+1}\oplus a_i)$,讨论 $2$ 种情况:
- $A\in V$,有 $S\oplus A=S$,集合不变。
- $A\notin V$,并集为 $\text{span}(V,A)\oplus c$。$\text{span}$ 表示合并 $V$ 和 $A$ 后的新空间。
代码上,相当于将 $A$ 插入线性基,偏移量不变。
当 $s_i=1$,即 $S_i=S_{i+1}\cap (S_{i+1}\oplus a_i)$,同样 $2$ 种:
- $A\in V$,同理,集合不变。
- $A\notin V$,则 $A$ 与 $S$ 无交集,即 $\varnothing$。
如此之后任意操作集合保持 $\varnothing$ 不变,dp 全为 $0$。
观察到偏移量 $c$ 不变,恒为 $0$。
最终检查 $0\in S_1$。因为只要不为空集合一定包含 $0$(初始为 $\{0\}$),则等价于检查 $S_1\ne\varnothing$。
代码:
```cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 202;
int n;
long long a[N];
string s;
struct linear_basis { // 线性基
long long base[60];
linear_basis() {
memset(base, 0, sizeof(base));
}
bool insert(long long x) {
for (int i = 59; i >= 0; --i) {
if ((x >> i) & 1) {
if (!base[i]) {
base[i] = x;
return 1;
}
x ^= base[i];
}
}
return 0;
}
bool contains(long long x) {
for (int i = 59; i >= 0; --i) {
if ((x >> i) & 1) {
if (!base[i]) {
return 0;
}
x ^= base[i];
}
}
return 1;
}
};
bool solve() {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
cin >> s;
linear_basis lb;
for (int i = n - 1; i >= 0; --i) {
if (s[i] == '0') {
lb.insert(a[i]); // 插入
} else {
if (!lb.contains(a[i])) { // 检查存在性
return 1; // 不存在,那么空集,后续 dp 恒为 0,答案为 1
}
}
}
return 0; // 说明不是空集,答案为 0
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while (t--) {
cout << solve() << '\n';
}
return 0;
}
```