[洛谷P3812]【模板】线性基

题目大意:给定$n$个数,选取任意个数,使得他们的异或和最大。

题解:线性基,原理贪心看不懂。

对于每一个数,设它的最高位的$1$在第$i$位,如果此时$P_i$为空,就将这个数加入线性基,否则异或上$P_i$继续找。最后贪心看$ans$异或上线性基的这一位会不会变大,若变大就转移

卡点:

C++ Code:

#include <cstdio>
int n;
long long x, p[55], ans;
int main() {
	scanf("%d", &n);
	while (n --> 0) {
		scanf("%lld", &x);
		for (int i = 50; ~i; i--) {
			if (x & 1ll << i) {
				if (p[i]) x ^= p[i];
				else {p[i] = x; break;}
			}
		}
	}
	for (int i = 50; ~i; i--) if (ans < (ans ^ p[i])) ans = ans ^ p[i];
	printf("%lld
", ans);
	return 0;
}

  

原文地址:https://www.cnblogs.com/Memory-of-winter/p/9681681.html