poj 3764 字典树求异或最大值

来源:互联网 发布:天空表白墙源码v4.1 编辑:程序博客网 时间:2024/05/18 17:40
The xor-longest Path
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 4290 Accepted: 952

Description

In an edge-weighted tree, the xor-length of a path p is defined as the xor sum of the weights of edges onp:

_{xor}length(p)=\oplus_{e \in p}w(e)

⊕ is the xor operator.

We say a path the xor-longest path if it has the largest xor-length. Given an edge-weighted tree with n nodes, can you find the xor-longest path?  

Input

The input contains several test cases. The first line of each test case contains an integern(1<=n<=100000), The following n-1 lines each contains three integersu(0 <= u < n),v(0 <= v < n),w(0 <=w < 2^31), which means there is an edge between node u and v of length w.

Output

For each test case output the xor-length of the xor-longest path.

Sample Input

40 1 31 2 41 3 6

Sample Output

7

Hint

The xor-longest path is 0->1->2, which has length 7 (=3 ⊕ 4)

Source

#include <iostream>#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;const int maxn=200000+200;const int maxm=100000*32+200;int n;int sz;int pre[maxn];struct node{    int v;    int w;    int next;}edge[maxn*2];struct trie{    int next[2];    void init()    {        memset(next,0,sizeof(next));    }}trie[maxm];int val[maxn];int cnt;void init(){    sz=0;    cnt=1;    memset(pre,-1,sizeof(pre));    memset(val,0,sizeof(val));}void adde(int u,int v,int w){    edge[cnt].v=v;    edge[cnt].w=w;    edge[cnt].next=pre[u];    pre[u]=cnt++;}void dfs(int u,int x,int fa){    val[u]=x;    for(int i=pre[u];i!=-1;i=edge[i].next)    {        int v=edge[i].v;        if(v==fa) continue;        int w=edge[i].w;        dfs(v,x ^ w,u);    }}void insert(int x){    int u=0,ind;    for(int i=30;i>=0;i--)    {        if(x&(1<<i))        {            ind=1;        }else ind=0;        if(!trie[u].next[ind])        {            trie[u].next[ind]=++sz;            trie[sz].init();        }        u=trie[u].next[ind];    }}int com(int x){   int u=0,ind,num=0;   for(int i=30;i>=0;i--)   {       if(x&(1<<i)) ind=0;       else ind=1;       if(trie[u].next[ind])       {           num|=(1<<i);           u=trie[u].next[ind];       }       else u=trie[u].next[!ind];   }   return num;}int main(){   // freopen("in.txt","r",stdin);    while(~scanf("%d",&n))    {        int u,v,w;        init();        for(int i=1;i<n;i++)        {            scanf("%d%d%d",&u,&v,&w);            u++;v++;            adde(u,v,w);            adde(v,u,w);        }        trie[0].init();        dfs(1,0,-1);        int ans=-1;        for(int i=1;i<=n;i++)        {            insert(val[i]);             ans=max(ans,com(val[i]));        }        printf("%d\n",ans);    }}


0 0
原创粉丝点击