[bzoj2115][Wc2011] Xor

给定一张n个点m条边的无向图,你要求一条路径,使得路径上的边的权值的异或和最大。

n<=50000,m<=100000 w<=10^18

题解:先把图上的环全部找出来,用异或和更新线性基,然后任选一条从1到n的路径,求一个最大异或和就好了。

因为来回走异或值为0,所以就算这条路径不是最优的也没关系,我们可以看作它和最优路径形成了一个环,在处理这个环时候就把它换成了最优的。同理就算一个环离路径很远也是可以滴。

#include<iostream>
#include<cstdio>
#define MK 62
#define MM 200000
#define MN 50000
#define ll long long 
using namespace std;
inline ll read()
{
    ll x = 0 , f = 1; char ch = getchar();
    while(ch < '0' || ch > '9'){ if(ch == '-') f = -1;  ch = getchar();}
    while(ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}
    return x * f;
}

ll p[MK+5],w[MN+5];
bool inq[MN+5];
int n,m,head[MN+5],cnt=0;
struct edge{int to,next;ll w;}e[MM+5];

void ins(int f,int t,ll w)
{
    e[++cnt]=(edge){t,head[f],w};head[f]=cnt;
}

void ins(ll x)
{
//    cout<<"INS"<<x<<endl;
    for(int j=MK;j>=0;j--)
        if((x&(1LL<<j))>0)
        {
            if(!p[j])
                {p[j]=x;return;}
            else 
                x^=p[j];
        }
}

void dfs(int x)
{
//    cout<<"dfs"<<x<<" "<<w[x]<<endl;
    inq[x]=1;
    for(int i=head[x];i;i=e[i].next)
        if(inq[e[i].to])
            ins(w[x]^w[e[i].to]^e[i].w);
        else
            w[e[i].to]=w[x]^e[i].w,dfs(e[i].to);
}

int main()
{
    n=read();m=read();
    for(int i=1;i<=m;i++)
    {
        int u=read(),v=read();ll w=read();
        ins(u,v,w);ins(v,u,w);
    }
    dfs(1);
    ll ans=w[n];
//    for(int j=MK;j>=0;j--)
//        printf("%d %d\n",j,w[j]);
    for(int j=MK;j>=0;j--)
        ans=max(ans,ans^p[j]);
    cout<<ans;
    return 0;
}

 

posted @ 2017-03-24 19:11  FallDream  阅读(183)  评论(0编辑  收藏  举报