[WC 2011]Xor

时间:2023-03-09 22:23:54
[WC 2011]Xor

Description

[WC 2011]Xor

Input

第一行包含两个整数N和 M, 表示该无向图中点的数目与边的数目。 接下来M 行描述 M 条边,每行三个整数Si,Ti ,Di,表示 Si 与Ti之间存在 一条权值为 Di的无向边。 图中可能有重边或自环。

Output

仅包含一个整数,表示最大的XOR和(十进制结果),注意输出后加换行回车。

Sample Input

5 7
1 2 2
1 3 2
2 4 1
2 5 1
4 5 3
5 3 4
4 3 2

Sample Output

6

HINT

[WC 2011]Xor

题解

我们考虑如何得到答案,首先所有的环都是可以经过的。这是为什么呢?

假设我们从$1$号点开始走,走到一个环的起点,然后我们经过这个环以后回到了环的起点,这时我们可以直接回到起点。这样,除了环上的路径,其他的路径都被抵消了。那么我们就只选了了这个环,也就是说,任意一个环都是可以选的。

然后我们先把所有的环都选出来,选入线性基中,再选出任意一条从$1$到$n$的路径,作为初始$ans$。初始$ans$异或线性基的最大值就是我们求的答案。为什么任意选一条路径也是可行的呢?

我们选了一条路径以后,如果存在一条更优的路径,那么这两条路径肯定是构成一个环的,会被选入线性基中。那么我们再用初始的$ans$异或一下这个环,我们就会发现,初始的$ans$被抵消了,二更优的那条路径留了下来。所以,我们选一个任意的初始$ans$是可行的。

于是这道题的实现就很明显了。先找出所有环,构成线性基,然后找出初始$ans$。这两步显然是可以$dfs$一遍一起搞的。然后用$ans$去异或线性基。从高位开始往低位异或。如果当前$ans$异或这一位的数能使$ans$变大,那么就异或。最终得到的$ans$就是我们要求的答案。

补充谈谈对取出环的异或值的理解:

我们记$d[u]$为从根节点,到$u$节点这条路径上的$xor$和,那么假设我们$dfs$拓展路径的时候,我们找到了以前一个访问过的点$v$,

那么这里就构成了一个环,且由于是$dfs$实现的,很容易知道$d[u]=d[v]⊕w_1⊕w_2⊕...$,$w$为边权。

我们记我们插入线性基的元素(环上的$xor$和)为$x$,$x=w_1⊕w_2⊕...⊕w_i$,

因为我们知道$a⊕a=0$,那么$x=d[u]⊕d[u]⊕w_1⊕w_2⊕...⊕w_i$$=d[u]⊕d[v]⊕w_i$($w_i$为$u->v$的边权)

 //It is made by Awson on 2017.9.21
#include <set>
#include <map>
#include <cmath>
#include <ctime>
#include <queue>
#include <stack>
#include <string>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Max(a, b) ((a) > (b) ? (a) : (b))
#define LL long long
using namespace std;
const int N = ;
const int M = ;
LL st[]; int n, m, u, v;
LL c;
struct tt {
int to, next;
LL cost;
}edge[*M+];
int path[N+], top;
LL d[N+];
LL p[];
bool vis[N+]; LL getmax(LL x) {
for (int i = ; i >= ; i--)
if ((x^p[i]) > x)
x ^= p[i];
return x;
}
void insert(LL x) {
for (int i = ; i >= ; i--)
if (x&st[i]) {
if (!p[i]) {
p[i] = x;
break;
}
x ^= p[i];
}
}
void add(int u, int v, LL c) {
edge[++top].to = v;
edge[top].cost = c;
edge[top].next = path[u];
path[u] = top;
}
void dfs(int u) {
vis[u] = ;
for (int i = path[u]; i; i = edge[i].next) {
if (vis[edge[i].to]) insert(d[u]^d[edge[i].to]^edge[i].cost);
else {
d[edge[i].to] = d[u]^edge[i].cost;
dfs(edge[i].to);
}
}
}
void work() {
st[] = ;
for (int i = ; i < ; i++) st[i] = st[i-]<<;
for (int i = ; i <= m; i++) {
scanf("%d%d%lld", &u, &v, &c);
add(u, v, c); add(v, u, c);
}
dfs();
LL ans = getmax(d[n]);
printf("%lld\n", ans);
}
int main() {
while (~scanf("%d%d", &n, &m))
work();
return ;
}