跳到正文

题解

题解:AT_abc249_g [ABC249G] Xor Cards

喵仔牛奶约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年2月28日
更新
2026年2月28日
篇幅
约 4 分钟

版本

  1. v1当前

Solution

将 (xi,yi)(x_i,y_i) 作为 yi×230+xiy_i\times2^{30}+x_i 插入线性基,线性基里的 O(log⁡V)\mathcal{O}(\log V) 个数可以表示出原序列任意的数,只保留这些数答案不变(如果异或出了 00 也要保留)。将这些数还原回 (xi,yi)(x_i,y_i),得到了新的序列。

于是我们花费了 O(nlog⁡V)\mathcal{O}(n\log V) 的时间,将 nn 缩小到了 O(log⁡V)\mathcal{O}(\log V)。

可以发现,yiy_i 最高位互不相同。将 (xi,yi)(x_i,y_i) 按 yiy_i 从大到小排序,每次贪心判断能否取。具体地,维护当前 xi,yix_i,y_i 的异或和 sm,rssm,rs,处理出 [i+1,n][i+1,n] 的线性基 BB:

  • smsm 在 BB 中异或最终不可以 ≤k\le k,那么取;
  • 如果 rs⊕yi>rsrs\oplus y_i>rs 且 sm⊕xism\oplus x_i 在 BB 中异或最终可以 ≤k\le k,那么取;
  • 否则不取。

注意判无解:强制取一个数 ii,然后判断它在 [i+1,n][i+1,n] 的线性基 BB 中最终是否可以 ≤k\le k。如果存在这样的 ii,那么有解。

处理出后缀线性基,复杂度 O(nlog⁡V+log⁡2V)\mathcal{O}(n\log V+\log^2V)。

Code

C++
#include <bits/stdc++.h>
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
using namespace std;
namespace Milkcat {
	typedef long long LL;
	typedef pair<LL, LL> pii;
	const int N = 1e6 + 5, P = 60;
	struct LBase {
		LL b[P + 3]; Linear() { mems(b, 0); }
		int ins(LL x) { DEP(i, P, 0) if (x >> i & 1) if (b[i]) x ^= b[i]; else return b[i] = x, i; return 0; }
		LL askmx(LL x) { DEP(i, P, 0) x = max(x, x ^ b[i]); return x; }
		LL askmn(LL x) { DEP(i, P, 0) x = min(x, x ^ b[i]); return x; }
	} C, B[P + 5];
	LL n, m, k, x, ck, a[N], b[N];
	vector<pii> s;
	bool chk(int t, LL v) { return (B[t].askmn(v) <= k); }
	int main() {
		cin >> n >> k;
		REP(i, 1, n) {
			cin >> a[i] >> b[i];
			int x = C.ins(b[i] << 30 | a[i]);
			if (!x && !SZ(s)) s.pb(0, 0);
		}
		REP(i, 0, P) {
			LL x = C.b[i];
			if (x > 0) s.pb(x >> 30, x & ((1 << 30) - 1));
		}
		sort(ALL(s), greater<pii>()), m = SZ(s) - 1;
		DEP(i, m, 0) B[i] = B[i + 1], B[i].ins(s[i].se);
		REP(i, 0, m) ck |= chk(i + 1, s[i].se);
		if (!ck) { cout << "-1\n"; return 0; }
		LL rs = 0, sm = 0;
		REP(i, 0, m) {
			auto [x, y] = s[i];
			int c1 = chk(i + 1, sm ^ y), c2 = chk(i + 1, sm);
			if ((c1 && (rs ^ x) > rs) || !c2) rs ^= x, sm ^= y;
		}
		cout << rs << '\n';
		return 0;
	}
}
int main() {
	ios::sync_with_stdio(0);
	cin.tie(0), cout.tie(0);
	int T = 1;
	while (T --) Milkcat::main();
	return 0;
}
原文