poj 3764 字典樹
阿新 • • 發佈:2017-09-28
plus sample class bsp edge include source 處理 ostream The xor-longest Path
For each test case output the xor-length of the xor-longest path.
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 字典樹