洛谷P4551 最长异或路径
设d[x]
为从x到根的路径上各边权的异或和,根据定义易知
d[x] = d[father(x)] ^ weight(father(x), x)
d[x]
可通过dfs求得
那么从x到y的路径异或和就是d[x] ^ d[y]
因为根据xor的运算性质(x ^ x = 0
),lca(x, y)
到根的路径正好被抵消
那么题目就转化为求d[x](1 <= x <= n)中两数的最大异或和
于是就变成了AcWing143 最大异或对(思路可以看看my blog qwq)
做最大异或对的时候没有发现的问题今天卡了我一个小时T^T
一般都是 cnt = p = 1
,cnt = p = 0
也可以
但就是不能 cnt = 0, p = 1
然后我就炸了QAQ
#include <iostream>
#include <cstdio>
const int N = 100005;
int tot = 0, cnt = 1;//cnt 必须 >= p 的初值 不然会倒回去
int head[N], next[N<<1], to[N<<1], e[N<<1];
int d[N], vis[N];
int trie[N<<5][2];
int max(int a, int b)
{
return a > b ? a : b;
}
void adde(int u, int v, int w)
{
tot++;
next[tot] = head[u];
head[u] = tot;
to[tot] = v;
e[tot] = w;
}
void dfs(int x, int l)
{
vis[x] = 1;
d[x] = l;
for(int i = head[x]; i; i = next[i])
{
int y = to[i], z = e[i];
if(vis[y]) continue;
dfs(y, l ^ z);
}
}
void insert(int x)
{
int p = 1;
for(int i = 30; i >= 0; i--)
{
int next = (x >> i) & 1;
if(!trie[p][next]) trie[p][next] = ++cnt;
p = trie[p][next];
}
}
int search(int x)
{
int p = 1;
int ans = 0;
for(int i = 30; i >= 0; i--)
{
int ch = (x >> i) & 1;
if(trie[p][ch ^ 1])
{
p = trie[p][ch ^ 1];
ans |= 1 << i;
}
else
p = trie[p][ch];
}
return ans;
}
int main(){
int n;
int u, v, w;
scanf("%d", &n);
for(int i = 1; i < n; ++i)
{
scanf("%d%d%d", &u, &v, &w);
adde(u, v, w);
adde(v, u, w);
}
dfs(1, 0);
int ans = 0;
for(int i = 1; i <= n; ++i)
{
ans = max(ans, search(d[i]));
//printf("%d %d\n", d[i], search(d[i]));
insert(d[i]);
}
printf("%d\n", ans);
return 0;
}