思路(来自题解):
众所周知树上两个点xy的距离是deep[x]+deep[y]-deep[lca(x,y)]*2
然后我们把这个加减法换成异或,我们就会发现,deep[lca(x,y)]被消掉了
所以题目就简化成w是每个点的前缀异或和,只要找到一对最大的(x,y)让w[x]^w[y]最大就行了,这个经典问题用字典树就能解决了。
代码:
#include<set>
#include<map>
#include<stack>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
typedef long long ll;
const int maxn = 1e5 + ;
const int seed = ;
const ll MOD = 1e9 + ;
const ll INF = 1e17;
using namespace std; int tol, node[ * maxn][];
ll val[ * maxn], w[maxn];
void Insert(ll x){
int root = ;
for(int i = ; i >= ; i--){
int u = (x >> i) & ;
if(node[root][u] == ){
memset(node[tol], , sizeof(node[tol]));
node[root][u] = tol++;
}
root = node[root][u];
}
val[root] = x;
}
ll query(ll x){
int root = ;
for(int i = ; i >= ; i--){
int u = (x >> i) & ;
if(node[root][!u])
root = node[root][!u];
else root = node[root][u];
}
return x ^ val[root];
}
int main(){
int T, n, a;
ll x;
scanf("%d", &T);
while(T--){
memset(node[], , sizeof(node[]));
tol = ;
w[] = ;
scanf("%d", &n);
for(int i = ; i <= n; i++){
scanf("%d%lld", &a, &x);
w[i] = x ^ w[a];
Insert(w[i]);
}
ll ans = ;
for(int i = ; i <= n; i++){
ans = max(ans, query(w[i]));
}
printf("%lld\n", ans);
}
return ;
}