BZOJ2115: [Wc2011] Xor(线性基)

Time Limit: 10 Sec  Memory Limit: 259 MB
Submit: 4848  Solved: 2030
[Submit][Status][Discuss]

Description

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

Source

感觉std的思路比较套路

首先我们求出任意一条路径的xor值

然后我们假设有另外一条路径的xor值比当前优,我们考虑如何把当前路径一步步替换为最优路径

有两种情况

1:当前路径和最优路径不存在交集,那么这两条路径构成一个环

2:当前路径和最优路径存在交集,那么这两条路径的并 中会出现一些环,我们只需要把当前路径在环上的部分替换掉就好

因此,不论哪种情况,我们都需要找到异或和最大的环

然后dfs一边找出所有环,扔到线性基里求最大值就好了。。

// luogu-judger-enable-o2
#include<cstdio>
#include<cstring>
#include<algorithm>
#define int long long 
using namespace std;
const int MAXN = 2 * 1e5 + 10,  B = 62;
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N, M;
struct Edge {
    int u, v, w, nxt;
}E[MAXN];
int head[MAXN], num = 1;
inline void AddEdge(int x, int y, int z) {
    E[num] = (Edge) {x, y, z, head[x]};
    head[x] = num++;
}
int vis[MAXN], P[MAXN], dis[MAXN];
void Insert(int x) {
    for(int i = B; i >= 0; i--) {
        if((x >> i) & 1) {
            if(!P[i]) {P[i] = x; return ;}
            x = x ^ P[i];
        }
    }
}
void FindQuan(int x, int fa) {
    vis[x] = 1;
    for(int i = head[x], v; i != -1; i = E[i].nxt) {
        if((v = E[i].v) == fa) continue;
        if(vis[v]) {Insert(dis[x] ^ dis[v] ^ E[i].w); continue;}
        dis[v] = dis[x] ^ E[i].w;
        FindQuan(v, x);
    }
}
main() { 
#ifdef WIN32
    freopen("a.in", "r", stdin);
#endif
    memset(head, -1, sizeof(head));
    N = read(); M = read();
    for(int i = 1; i <= M; i++) {
        int x = read(), y = read(), z = read();
        AddEdge(x, y, z); AddEdge(y, x, z);
    }
    FindQuan(1, 0);
    int ans = dis[N];
    for(int i = B; i >= 0; i--)
        if((ans ^ P[i]) > ans)
            ans = ans ^ P[i];
    printf("%lld", ans);
}

猜你喜欢

转载自www.cnblogs.com/zwfymqz/p/9193642.html