Poj 3764 The xor-longest Path(Trie树+xor+贪心)

来源:互联网 发布:mac添加pdf虚拟打印机 编辑:程序博客网 时间:2024/04/29 03:09

The xor-longest Path
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 6455 Accepted: 1392
Description
In an edge-weighted tree, the xor-length of a path p is defined as the xor sum of the weights of edges on p:
{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 integer n(1<=n<=100000), The following n-1 lines each contains three integers u(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
4
0 1 3
1 2 4
1 3 6
Sample Output
7
Hint
The xor-longest path is 0->1->2, which has length 7 (=3 ⊕ 4)

/*Trie树+异或+贪心.异或性质 a^b=(a^c)^(b^c).首先dfs出根节点到每个节点的xor.然后a^b=(a^root)^(b^root).拆成二进制挂在Trie树上跑.从高位到低位存贪心此位为1则看0是否存在正确性显然. */#include<iostream>#include<cstdio>#include<cstring>#define MAXN 100001using namespace std;int n,m,dis[MAXN],fa[MAXN],ans,cut,tot,head[MAXN],s[MAXN];struct edge{int v,next,x;}e[MAXN*2];struct data{int next[2];}tree[MAXN*16];inline int read(){    int 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-48,ch=getchar();    return x*f;}void add(int u,int v,int x){    e[++cut].v=v;    e[cut].x=x;    e[cut].next=head[u];    head[u]=cut;}void add(int x){    int now=0,xx;    for(int i=30;i>=0;i--)    {        if(x&(1<<i)) xx=1;        else xx=0;        if(!tree[now].next[xx]) tot++,tree[now].next[xx]=tot;        now=tree[now].next[xx];    }}int query(int x){    int now=0,xx,num=0;    for(int i=30;i>=0;i--)    {        if(x&(1<<i)) xx=0;        else xx=1;        if(tree[now].next[xx])        {            num|=(1<<i);            now=tree[now].next[xx];        }        else now=tree[now].next[!xx];    }    return num;}void dfs(int u,int f,int xo){    fa[u]=f;s[u]=xo;    for(int i=head[u];i;i=e[i].next)    {        int v=e[i].v;        if(!fa[v]&&v!=f) dfs(v,u,xo^e[i].x);    }}int main(){    int x,y,z;    while(~scanf("%d",&n))    {        ans=0;cut=0;tot=0;        memset(head,0,sizeof head);        memset(fa,0,sizeof fa);        memset(tree,0,sizeof tree);        for(int i=1;i<=n-1;i++)        {            x=read(),y=read(),z=read();            x++,y++;            add(x,y,z),add(y,x,z);        }        dfs(1,1,0);        for(int i=1;i<=n;i++) add(s[i]);        for(int i=1;i<=n;i++) ans=max(ans,query(s[i]));        printf("%d\n",ans);    }    return 0;}
0 0
原创粉丝点击