【洛谷】P4551 最长异或路径 的题解

【洛谷】P4551 最长异或路径 的题解

洛谷传送门

题解

神奇的字典树咩呀qaq

看到异或,我们首先很容易想到 trie 树 还有 线性基。但是这题明显是字典树。

指定一个根 r o o t root root,用 t r i e [ u ] [ v ] trie[u][v] trie[u][v] 表示 u u u 和 v v v 之间的路径的边权异或和,那么 t r i e [ u ] [ v ] = t r i e [ r o o t ] [ u ] ⊕ t r i e [ r o o t ] [ v ] trie[u][v]=trie[root][u]\oplus trie[root][v] trie[u][v]=trie[root][u]⊕trie[root][v],因为 LCA 以上的部分异或两次抵消了。

那么,如果将所有 t r i e [ r o o t ] [ u ] trie[root][u] trie[root][u] 插入到一棵 trie 中,就可以对每个 t r i e [ r o o t ] [ u ] trie[root][u] trie[root][u] 快速求出和它异或和最大的 t r i e [ r o o t ] [ v ] trie[root][v] trie[root][v]:

从 trie 的根开始,如果能向和 T ( r o o t , u ) T(root, u) T(root,u) 的当前位不同的子树走,就向那边走,否则没有选择。

对于每一位进行贪心,如果这一位有一个与它不同的,即异或后是 1 1 1,那我们就顺着这条路往下走;否则就顺着原路往下走。

贪心的正确性:如果这么走,这一位为 1 1 1;如果不这么走,这一位就会为 0 0 0。而高位是需要优先尽量大的。由于高位大决定一切,所以我们贪心是对的。

代码

cpp 复制代码
#include <bits/stdc++.h>
#define re register
#define lowbit(x) x & (-x)
#define endl "\n"
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
namespace fastIO {
	inline int read() {
		register int x = 0, f = 1;
		register char c = getchar();
		while (c < '0' || c > '9') {
			if(c == '-') f = -1;
			c = getchar();
		}
		while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
		return x * f;
	}
	inline void write(int x) {
		if(x < 0) putchar('-'), x = -x;
		if(x > 9) write(x / 10);
		putchar(x % 10 + '0');
		return;
	}
}
using namespace fastIO;
int head[100005], nxt[100005 << 1], to[100005 << 1], weight[100005 << 1], cnt;
int n, dis[100005], ch[100005 << 5][2], tot = 1, ans;
void insert(int x) {
	for(int i = 30, u = 1; i >= 0; i --) {
		int c = ((x >> i) & 1);
		if(!ch[u][c]) ch[u][c] = ++ tot;
		u = ch[u][c];
	}
}
void get(int x) {
	int res = 0;
	for(int i = 30, u = 1; i >= 0; i --) {
		int c = ((x >> i) & 1);
		if(ch[u][c ^ 1]) {
			u = ch[u][c ^ 1];
			res |= (1 << i);
		} 
		else
			u = ch[u][c];
	}
	ans = max(ans, res);
}
void add(int u, int v, int w) {
	nxt[++ cnt] = head[u];
	head[u] = cnt;
	to[cnt] = v;
	weight[cnt] = w;
}
void dfs(int u, int fa) {
	insert(dis[u]);
	get(dis[u]);
	for(int i = head[u]; i; i = nxt[i]) {
		int v = to[i];
		if(v == fa) continue;
		dis[v] = dis[u] ^ weight[i];
		dfs(v, u);
	}
}
int main() {
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	n = read();
	for(int i = 1; i < n; i ++) {
		int u, v, w;
		u = read(), v = read(), w = read();
		add(u, v, w); 
		add(v, u, w);
	}
	dfs(1, 0);
	write(ans), putchar('\n');
	return 0;
}
相关推荐
计信猫1 小时前
从零开学C++:二叉搜索树
数据结构·c++·算法
循环渐进Forward1 小时前
【C++笔试强训】如何成为算法糕手Day1
数据结构·c++·算法·力扣·笔试·牛客
软行1 小时前
LeetCode 每日一题 最佳观光组合
c语言·数据结构·算法·leetcode
抓哇能手1 小时前
王道408考研数据结构-串-第四章
数据结构·考研·算法·408·王道408
Gu Gu Study1 小时前
【用Java学习数据结构系列】对象的比较(Priority Queue实现的前提)
数据结构·算法·排序算法
会有黎明吗1 小时前
Leetcode 162.寻找峰值
数据结构·算法·leetcode
激昂~逐流1 小时前
尊享面试100题
数据结构·算法·面试
Navigator_Z1 小时前
LeetCode //C - 386. Lexicographical Numbers
c语言·算法·leetcode
AutoAutoJack2 小时前
C#的属性(Property)应用说明(一)
开发语言·数据结构·算法·c#
kaneki_lh2 小时前
数据结构 - 查找算法
数据结构·算法