bzoj1594 Pku3764 The xor-longest Path

题目链接

先求每个点到根的异或和

然后就要找出两个点,使dis[a]^dis[b]最大

注意异或的性质,我们可以用trie树,沿着与当前数字每位的相反方向走

 1 #include<algorithm>
 2 #include<iostream>
 3 #include<cstdlib>
 4 #include<cstring>
 5 #include<cstdio>
 6 #include<string>
 7 #include<cmath>
 8 #include<ctime>
 9 #include<queue>
10 #include<stack>
11 #include<map>
12 #include<set>
13 #define rre(i,r,l) for(int i=(r);i>=(l);i--)
14 #define re(i,l,r) for(int i=(l);i<=(r);i++)
15 #define Clear(a,b) memset(a,b,sizeof(a))
16 #define inout(x) printf("%d",(x))
17 #define douin(x) scanf("%lf",&x)
18 #define strin(x) scanf("%s",(x))
19 #define LLin(x) scanf("%lld",&x)
20 #define op operator
21 #define CSC main
22 typedef unsigned long long ULL;
23 typedef const int cint;
24 typedef long long LL;
25 using namespace std;
26 void inin(int &ret)
27 {
28     ret=0;int f=0;char ch=getchar();
29     while(ch<'0'||ch>'9'){if(ch=='-')f=1;ch=getchar();}
30     while(ch>='0'&&ch<='9')ret*=10,ret+=ch-'0',ch=getchar();
31     ret=f?-ret:ret;
32 }
33 int n,head[100010],next[200020],zhi[200020],w[200020],ed,dis[100010];
34 int ch[3300030][2],eed,po[33];
35 void add(int a,int b,int c)
36 {
37     next[++ed]=head[a],head[a]=ed,zhi[ed]=b,w[ed]=c;
38     next[++ed]=head[b],head[b]=ed,zhi[ed]=a,w[ed]=c;
39 }
40 void dfs(int x,int fa)
41 {
42     for(int i=head[x];i;i=next[i])
43         if(zhi[i]!=fa)
44         {
45             dis[zhi[i]]=dis[x]^w[i];
46             dfs(zhi[i],x);
47         }
48 }
49 void add(int x)
50 {
51     int now=0;
52     rre(i,30,0)
53     {
54         int temp=x&po[i];
55         if(temp)temp=1;
56         if(!ch[now][temp])ch[now][temp]=++eed;
57         now=ch[now][temp];
58     }
59 }
60 int ans=0;
61 void query(int x)
62 {
63     int now=0,xx=0;
64     rre(i,30,0)
65     {
66         int temp=x&po[i];
67         if(temp)temp=1;
68         if(ch[now][temp^1])now=ch[now][temp^1],xx|=po[i];
69         else now=ch[now][temp];
70     }
71     ans=max(ans,xx);
72 }
73 int CSC()
74 {
75     inin(n);po[0]=1;re(i,1,30)po[i]=po[i-1]<<1;
76     re(i,2,n)
77     {
78         int q,w,e;
79         inin(q),inin(w),inin(e);
80         add(q,w,e);
81     }
82     dfs(1,0);
83     re(i,1,n)
84         add(dis[i]);
85     re(i,1,n)query(dis[i]);
86     printf("%d",ans);
87     return 0;
88 }

 

posted @ 2016-02-26 08:26  HugeGun  阅读(170)  评论(0编辑  收藏  举报