The xor-longest Path题解

题目链接
题目大意:给出一颗树,求树上任意两点之间所有边的权值异或起来最大值是多少。
题目分析:很好的一道题,首先对于异或来讲满足交换律和结合律,所以求任意两点的异或和就是任意两个点到根节点的异或和异或起来(中间相同的部分异或相消为0,异或0相当于没异或),dfs求出所有点到根节点的异或和,然后问题就转化为从一个数列中任选两点,异或起来的最大值是多少,字典树问题。
注意:这个题有多组测试点,用vector做邻接表的话可能要超时,所以还是采用朴素邻接表(记得nex, vex, edge要开双倍)。读入的话要用scanf。
代码如下:

# include<iostream>
# include<cstdio>
# include<cmath>
# include <algorithm>
# include <cstring>

using namespace std;
const int N = 1e5 + 5; 

int n, ans, tol, head[N], nex[N * 2], vex[N * 2], edge[N * 2], a[N], tot, trie[31 * N][2];

void add(int x, int y, int z) {
	vex[++tol] = y;
	edge[tol] = z;
	nex[tol] = head[x];
	head[x] = tol;
}

void dfs(int cur, int fa, int sum) {
	a[cur] = sum;
	for (int i = head[cur]; i; i = nex[i])
		if (vex[i] != fa)
			dfs(vex[i], cur, sum ^ edge[i]);
}

void insert(int x) {
	int p = 1;
	for (int i = 30; i >= 0; i--) {
		int tmp = x >> i & 1;
		if (!trie[p][tmp]) trie[p][tmp] = ++tot;
		p = trie[p][tmp];
	}
}

int search(int x) {
	int res = 0;
	int p = 1;
	for (int i = 30; i >= 0; i--) {
		int tmp = x >> i & 1;
		if (trie[p][!tmp]) {
			res += 1 << i;
			p = trie[p][!tmp];
		}
		else p = trie[p][tmp];
	}
	return res;
}

int main() {
	while (~scanf("%d", &n)) {
		ans = 0;
		memset(head, 0, sizeof(head));
		memset(nex, 0, sizeof(nex));
		memset(vex, 0, sizeof(vex));
		memset(edge, 0, sizeof(edge));
		for (int i = 1; i <= tot; i++)
			trie[i][0] = trie[i][1] = 0;
		tot = 1;
		tol = 0;
		for (int i = 1; i < n; i++) {
			int u, v, w;
			scanf("%d %d %d", &u, &v, &w);
			add(u, v, w);
			add(v, u, w);
		}
		dfs(0, -1, 0);
		for (int i = 0; i < n; i++)
			insert(a[i]);
		for (int i = 0; i < n; i++)
			ans = max(ans, search(a[i]));
		printf("%d\n", ans);		
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值