P4151 [WC2011]最大XOR和路径
思路
如果单纯的只是树形图,那么答案显然易见只有一种,也就是从头到尾的路径从头到尾的异或值,但是这里不同的就是有可能在道路上有许多的环。
题目有一个重点提示的一句话
理解这句话之后那么我们可以显然的从1这个位置到达任何一个环,然后回到一号位置,这里面得到的假值将会是所有我们走过的环的异或值,所以我们只要走一条链,然后通过贪心地选择环,最后即可得到我们想要的最大值。
至于如何贪心,这里就要用到线性基了,通常地在线性基地内部求解最大值我们只设置初始ans=1ans = 1ans=1,但是在这里我们应该初始设置ans=dis[n]ans = dis[n]ans=dis[n],然后再跑一遍线性基最大值,即可求得最终的答案。
代码
/*Author : lifehappy
*/
#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>#define mp make_pair
#define pb push_back
#define endl '\n'
#define mid (l + r >> 1)
#define lson rt << 1, l, mid
#define rson rt << 1 | 1, mid + 1, r
#define ls rt << 1
#define rs rt << 1 | 1using namespace std;typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;const double pi = acos(-1.0);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;inline ll read() {ll f = 1, x = 0;char c = getchar();while(c < '0' || c > '9') {if(c == '-') f = -1;c = getchar();}while(c >= '0' && c <= '9') {x = (x << 1) + (x << 3) + (c ^ 48);c = getchar();}return f * x;
}const int N = 5e4 + 10;int head[N], to[N << 2], nex[N << 2], cnt = 1;ll value[N << 2], dis[N << 2];int visit[N], n, m;struct linearbasis {ll base[64], flag, cnt;void add(ll x) {for(int i = 62; ~i; i--) {if(x >> i & 1) {if(!base[i]) {base[i] = x;return ;}x ^= base[i];}}flag = 1;}ll query_max() {ll ans = dis[n];for(int i = 62; ~i; i--) {if((ans ^ base[i]) > ans) {ans ^= base[i];}}return ans;}ll query_min() {for(int i = 0; i <= 62; i++) {if(base[i]) {return base[i];}}}void rebuild() {cnt = 0;for(int i = 62; i >= 0; i--) {for(int j = i - 1; j >= 0; j--) {if(base[i] >> j & 1) {base[i] ^= base[j];}}}for(int i = 0; i <= 62; i++) {if(base[i]) {ll temp = base[i];base[i] = 0;base[cnt++] = temp;}}}ll query_k(ll k) {k -= flag;if(k == 0) return 0;if(k >= 1ll << cnt) return -1;ll ans = 0;for(int i = 62; ~i; i--) {if(k >> i & 1) {ans ^= base[i];}}return ans;}void init() {memset(base, 0, sizeof base), flag = cnt = 0;}
}a;void add(int x, int y, ll w) {to[cnt] = y;nex[cnt] = head[x];value[cnt] = w;head[x] = cnt++;
}void dfs(int rt, ll w) {dis[rt] = w, visit[rt] = 1;for(int i = head[rt]; i; i = nex[i]) {if(visit[to[i]]) a.add(w ^ dis[to[i]] ^ value[i]);else dfs(to[i], w ^ value[i]);}
}int main() {// freopen("in.txt", "r", stdin);// freopen("out.txt", "w", stdout);// ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);n = read(), m = read();for(int i = 1; i <= m; i++) {int x = read(), y = read(); ll w = read();add(x, y, w);add(y, x, w);}dfs(1, 0);printf("%lld\n", a.query_max());return 0;
}