Description
给定一棵n个点的带权树,求树上最长的异或和路径
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.
Examples
Sample Input
4
1 2 3
2 3 4
2 4 6
Sample Output
7
Hint
The xor-longest path is 1->2->3, which has length 7 (=3 ⊕ 4)
注意:结点下标从1开始到N…
Source
鸣谢陶文博
Solution
先预处理出树上任意一点到根节点的路径异或值,所以树上任意两点的路径异或值 = (root,u) ^ (root.v)
最后用01 Trie 从根节点开始,贪心地选与这一位相反的值
Code
const int maxn = 1e5 + 7;
int ecnt,head[maxn<<1];
struct Edge{
int v,w,next;
}e[maxn<<1];
void add(int u,int v,int w){
e[++ecnt] = (Edge) {v,w,head[u]}, head[u] = ecnt;
e[++ecnt] = (Edge) {u,w,head[v]}, head[v] = ecnt;
}
int tot,trie[maxn*30][2];
void insert(int val){
int u = 0;
for(int i = (1<<30);i;i>>=1){
bool c = val & i;
if(!trie[u][c]) trie[u][c] = ++tot;
u = trie[u][c];
}
}
int search(int val){
int u = 0, res = 0;
for(int i = (1 << 30);i;i>>=1){
bool c = val & i;
if(trie[u][!c]) res += i, u = trie[u][!c];
else u = trie[u][c];
}
return res;
}
int val[maxn];
void dfs(int u,int fa){
for(int i = head[u];i;i = e[i].next){
int v = e[i].v;if(v == fa) continue;
val[v] = val[u] ^ e[i].w;
dfs(v,u);
}
}
int main(){
int n,res = 0;scanf("%d",&n);
for(int i = 1,u,v,w;i < n;++i){
scanf("%d%d%d",&u,&v,&w);add(u,v,w);
}
val[1] = 0;dfs(1,-1);
for(int i = 1;i <= n;++i) insert(val[i]);
for(int i = 1;i <= n;++i){
res = max(res,search(val[i]));
}
printf("%d\n", res);
return 0;
}