Linear yl bzoj 2115

Topic Link
title intended
for a n vertices and m edges undirected weighted graph, find a path from 1 to n and the maximum exclusive or.
Ideas
from the path 1 to n, there is no requirement of different points, different side, so that the idea according to the greedy, if it rings, on the path from a vertex on the 1 to n, and back through the loop the vertices may make XOR value becomes large, so that these rings traversal, if the exclusive-oR value can increase the left, and finally can obtain the maximum value of the exclusive oR. Here is formed a set minimum value or the maximum linear exclusive group requirements.

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 7;
typedef long long ll;
int head[maxn], to[maxn<<1], nex[maxn<<1], cnt;
ll edge[maxn<<1];
int n, m, tot;
ll a[maxn*3], b[65], d[maxn];
void init() {
    memset(head, -1, sizeof(head)); cnt = 0;
}
void add(int x, int y, ll val) {
    to[cnt] = y;
    edge[cnt] = val;
    nex[cnt] = head[x];
    head[x] = cnt++;
}
bool vis[maxn];
void dfs(int u, int fx) {
    vis[u] = true;
    for (int i = head[u]; ~i; i = nex[i]) {
        int v = to[i];
        if(v != fx) {
            if(!vis[v]) {
                d[v] = d[u] ^ edge[i];
                dfs(v, u);
            }
            else a[tot++] = d[u] ^ d[v] ^ edge[i];
        }
    }
}
void prepare() {
    memset(b, 0, sizeof(b));
    for (int i = 0; i < tot; i++) {
        for (int j = 62; j >= 0; j--) {
            if((a[i]>>j)&1) {
                if(b[j]) a[i] ^= b[j];
                else {
                    b[j] = a[i]; cnt++;
                    for (int k = j - 1; k >= 0; k--)
                        if(b[k] && ((b[j] >>k)&1)) b[j] ^= b[k];
                    for (int k = j + 1; k <= 62; k++)
                        if((b[k]>>j)&1) b[k] ^= b[j];
                    break;
                }
            }
        }
    }
}
int main()
{
    init();
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++) {
        ll z; int x, y;
        scanf("%d%d%lld", &x, &y, &z);
        add(x, y, z); add(y, x, z);
    }
    dfs(1, 1);
    prepare();
    ll ans = d[n];
    for (int i = 62; i >= 0; i--)
        if(ans < (ans ^ b[i])) ans ^= b[i];
    printf("%lld\n", ans);
    return 0;
}

Published 26 original articles · won praise 2 · Views 407

Guess you like

Origin blog.csdn.net/D_Bamboo_/article/details/103616999