跳到正文

题解

题解:P14526 [BYOI R1] 心之所愿

zhangxiaoyu008约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年12月30日
收录
2025年12月30日
更新
2026年11月11日
篇幅
约 5 分钟
获赞
2
题目
P14526

版本

  1. v2当前
  2. v1

题目中

当且仅当 ∣P∩Si∣\lvert P \cap S_i \rvert 是 奇数 时,他才认为愿望 ii 是被实现的。

由此我们想到对一些数异或的时候,当且仅当某一位有 奇数 个 11 时,结果上对应位为 11。

所以,原问题转化为,有 mm 个 nn 位二进制数,要使所选的数的异或 尽可能大,并且求出方案数。

发现这就是线性基的模板,再次不做赘述。

但是如果直接用数组模拟是 O(n2m)\Omicron(n^2m) 的,所以使用 bitset 优化,变为 O(n2mω)\displaystyle\Omicron(\frac{n^2m}{\omega}),可过。

哦,在求最大异或值时需要比较,但是 bitset 好像没有比较运算符,那么可以手写 bitset。

什么,你不会手写 bitset?

这里讲一下如何手写 bitset,如果你会,可直接跳到代码。

首先提一下原理:里面存 int/long long 类型数组,每一位对应压位后的一个 int/long long 的二进制位。因此在进行操作时,若操作 nn 位二进制,相当于是对 nω\displaystyle\frac{n}{\omega} 个数操作,故复杂度可以看作是 O(nω)\Omicron(\displaystyle\frac{n}{\omega})。

然后来看一些常用操作:

把第 idx 位设置为 11:

C++
data[idx >> 5] |= 1 << (idx & 31);

把第 idx 位设置为 00:

C++
data[idx >> 5] &= ~(1 << (idx & 31));

把第 idx 位设置为 val:

C++
(data[idx >> 5] &= ~(1 << (idx & 31))) |= (val << (idx & 31));

得到第 idx 位的值:

C++
(data[idx >> 5] >> (idx & 31)) & 1

按位与:

C++
for(int i = 0; i < S; i ++) data[i] &= W.data[i];

按位或:

C++
for(int i = 0; i < S; i ++) data[i] |= W.data[i];

按位取反:

C++
for(int i = 0; i < S; i ++) data[i] = ~data[i];

按位异或:

C++
for(int i = 0; i < S; i ++) data[i] ^= W.data[i];

比较大小:

C++
bool operator< (const Bitset &W)const{
	for(int i = S - 1; ~i; i --)
		if(data[i] != W.data[i])
			return data[i] < W.data[i];
	return false;
}
Code\large{\mathbf{Code}}
C++
#include <bits/stdc++.h>
using namespace std;
const int N = 4000, S = N / 32;
struct Bitset{
	unsigned data[S];
	void set(int idx) { data[idx >> 5] |= 1 << (idx & 31); }
    bool operator[] (int idx) { return (data[idx >> 5] >> (idx & 31)) & 1; }
	Bitset& operator ^= (const Bitset &W) {
		for(int i = 0; i < S; i ++) data[i] ^= W.data[i];
		return *this;
	}
	bool operator< (const Bitset &W)const{
		for(int i = S - 1; ~i; i --)
			if(data[i] != W.data[i])
				return data[i] < W.data[i];
		return false;
	}
}f[N], d[N], res, now;
int m, n, cnt = 1;
bool st[N];
char s[N + 5];
void insert(int p) {
	for(int i = n - 1; ~i; i --)
		if(f[p][i]) {
			if(st[i]) f[p] ^= d[i];
			else {
				d[i] = f[p], st[i] = true;
				return;
			}
		}
	(cnt *= 2) %= 998244353;
}
int main()
{
	scanf("%d%d", &m, &n);
	for(int i = 0; i < n; i ++) {
		scanf("%s", s);
		for(int j = 0; j < m; j ++)
			if(s[j] == '1')
				f[j].set(n - i - 1);
	}
	for(int i = 0; i < m; i ++) insert(i);
	for(int i = n - 1; ~i; i --) {
		res ^= d[i];
		if(res < now) res = now;
		else now = res;
	}
	for(int i = 0; i < n; i ++) puts(res[n - i - 1] ? "Yes" : "No");
	printf("%d\n", cnt);
	return 0;
}
原文