0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-12-24 03:11:58 +00:00

144. 最长异或值路径

https://www.acwing.com/problem/content/submission/code_detail/8019318/
This commit is contained in:
Baoshuo Ren 2021-10-03 11:13:48 +08:00 committed by Baoshuo Ren
parent a608ebd2c0
commit fdb7b7a070
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

68
AcWing/144/144.cpp Normal file
View File

@ -0,0 +1,68 @@
#include <bits/stdc++.h>
using namespace std;
int n, u, v, w, a[100005], ans;
vector<pair<int, int>> g[100005];
struct node {
int size;
node* next[2];
~node() {
for (auto& i : next) {
delete i;
}
}
};
void dfs(int u, int fa, int sum) {
a[u] = sum;
for (auto i : g[u]) {
if (i.first != fa) {
dfs(i.first, u, sum ^ i.second);
}
}
}
void insert(node* root, int x, int b) {
if (!x) {
root->size++;
return;
}
if (root->next[(x >> b) & 1] == nullptr) root->next[(x >> b) & 1] = new node();
insert(root->next[(x >> b) & 1], x - (((x >> b) & 1) << b), b - 1);
}
int query(node* root, int x) {
int res = 0;
for (int i = 31; i >= 0; i--) {
if (root == nullptr) break;
if (root->next[!((x >> i) & 1)] != nullptr) {
res += 1 << i;
root = root->next[!((x >> i) & 1)];
} else {
root = root->next[(x >> i) & 1];
}
}
return res;
}
int main() {
node* root = new node();
cin >> n;
for (int i = 1; i < n; i++) {
cin >> u >> v >> w;
g[u].push_back(make_pair(v, w));
g[v].push_back(make_pair(u, w));
}
dfs(0, -1, 0);
for (int i = 0; i < n; i++) {
insert(root, a[i], 31);
}
for (int i = 0; i < n; i++) {
ans = max(ans, query(root, a[i]));
}
cout << ans << endl;
return 0;
}