洛谷P4551 最长异或路径

洛谷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 = 1cnt = 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;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值