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

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

洛谷传送门

题解

神奇的字典树咩呀qaq

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

指定一个根 r o o t root root,用 t r i e u v trieuv trieuv 表示 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 trieuv=trierootu\oplus trierootv trieuv=trierootu⊕trierootv,因为 LCA 以上的部分异或两次抵消了。

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

从 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;
}
相关推荐
我命由我123457 分钟前
方差(实例实操、与标准差的区别)
java·数据结构·算法·数据分析·java-ee·intellij-idea·idea
闲研随记8 分钟前
【文献阅读 ICML 2026】RL算法:Critique-GRPO
论文阅读·算法·llm·强化学习·rl·icml·grpo
民乐团扒谱机31 分钟前
【微实验】从迷雾中看清世界:卡尔曼滤波的数学诗意与MATLAB实践
人工智能·算法·matlab·卡尔曼滤波·kalman
什巳1 小时前
JAVA练习275-乘积最大子数组
java·开发语言·数据结构·算法
@踏雪寻梅1 小时前
27. 移除元素
算法
小牛不牛的程序员1 小时前
利用Claude Code构建自动化需求挖掘工具:从原理到实践
java·算法·自动化
Mr.HeBoYan1 小时前
DPDK为什么越来越少使用rte_ring?——从Lock-Free到Run-to-Completion,重新理解现代DPDK架构演进(上)
linux·网络·算法·性能优化·架构·dpdk
在书中成长1 小时前
HarmonyOS 小游戏《对战五子棋》开发第14篇 - 困难AI实现:Minimax算法原理详解
人工智能·算法·harmonyos
网络与设备以及操作系统学习使用者1 小时前
通信的物理与逻辑双维度解析
学习·深度优先
格子软件1 小时前
GEO系统深度实战:多引擎自适应算法与去中心化流控
人工智能·算法·去中心化·区块链