poj 3764 字典树
Posted LuZhiyuan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 3764 字典树相关的知识,希望对你有一定的参考价值。
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7332 | Accepted: 1555 |
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:
⊕ 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
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)
Source
题意:
给出一棵树,求这棵树中的最大的异或路径。
代码:
//预处理出来每个点到根的异或值sxor,然后u,v之间的异或路径值就是sxor[u]^sxor[v],lca就消去了。然后把每个点的sxor值插入字典 //树(二进制字典树),枚举每个点贪心的找他的最大异或路径。 #include<iostream> #include<cstdio> #include<cstring> using namespace std; const int MAXN=200000; int head[MAXN*2+9],tot,sxor[MAXN*2+9],sz,nod[MAXN*2+9][2],ans; struct Edge { int to,w,next; }edge[MAXN*4+9]; void init() { memset(sxor,0,sizeof(sxor)); memset(head,-1,sizeof(head)); nod[0][0]=nod[0][1]=0; tot=0; sz=0;ans=0; } void add(int x,int y,int z) { edge[tot].to=y; edge[tot].w=z; edge[tot].next=head[x]; head[x]=tot++; edge[tot].to=x; edge[tot].w=z; edge[tot].next=head[y]; head[y]=tot++; } void insert(int x) { int rt=0; for(int i=30;i>=0;i--){ int id=(x>>i)&1; if(nod[rt][id]==0){ nod[rt][id]=++sz; nod[sz][0]=nod[sz][1]=0; } rt=nod[rt][id]; } } void dfs(int x,int fa,int sum) { for(int i=head[x];i!=-1;i=edge[i].next){ int y=edge[i].to; if(y==fa) continue; sxor[y]=(sum^edge[i].w); dfs(y,x,sum^edge[i].w); } } void solve(int x) { int sum=0,rt=0; for(int i=30;i>=0;i--){ int id=(x>>i)&1; if(nod[rt][!id]){ sum|=(1<<i); rt=nod[rt][!id]; }else if(nod[rt][id]) rt=nod[rt][id]; else break; } ans=max(ans,sum); } int main() { int n; while(scanf("%d",&n)==1){ int x,y,z; init(); for(int i=1;i<n;i++){ scanf("%d%d%d",&x,&y,&z); add(x,y,z); } dfs(0,-1,0); for(int i=0;i<n;i++){ solve(sxor[i]); insert(sxor[i]); } printf("%d\n",ans); } return 0; }
以上是关于poj 3764 字典树的主要内容,如果未能解决你的问题,请参考以下文章
POJ 3764 The xor-longest Path (字典树)
POJ 3764 - The xor-longest Path - [DFS+字典树变形]
POJ 3764 The xor-longest Path ( 字典树求异或最值 && 异或自反性质 && 好题好思想)