topic:
# 10056. "One through 2.3 Exercise 5" The XOR-longest Path
Resolution:
Finished # 10051 after not very difficult
to continue to take advantage of the exclusive nature or have \ (dis (u, v)
= dis (1, u) \ oplus dis (1, v) \) to put on the right side of the point, then Dictionary XOR tree seeking maximum value
Code
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int n, m, num, cnt, tot, ans;
int id[N], a[N], head[N], sum[N];
bool vis[N];
struct node {
int v, nx, w;
} e[N];
struct trie {
int nx[2];
} E[N];
inline void add(int u, int v, int w) {
e[++num].nx = head[u], e[num].v = v, e[num].w = w, head[u] = num;
}
inline void insert(int x) {
bitset<35>b(x);
int rt = 0;
for (int i = 30; i >= 0; --i) {
int v = (int)b[i];
if (!E[rt].nx[v]) E[rt].nx[v] = ++cnt;
rt = E[rt].nx[v];
}
}
inline int query(int x) {
bitset<35>b(x);
int rt = 0, ret = 0;
for (int i = 30; i >= 0; --i) {
int v = (int)b[i];
if (E[rt].nx[v ^ 1]) ret = ret << 1 | 1, rt = E[rt].nx[v ^ 1];
else ret <<= 1, rt = E[rt].nx[v];
}
return ret;
}
void dfs(int u, int w) {
vis[u] = 1, a[u] = w;
for (int i = head[u]; ~i; i = e[i].nx) {
int v = e[i].v;
if (!vis[v]) dfs(v, e[i].w ^ w);
}
}
int main() {
ios::sync_with_stdio(false);
memset(head, -1, sizeof head);
cin >> n;
for (int i = 1, x, y, z; i < n; ++i) {
cin >> x >> y >> z;
add(x, y, z), add(y, x, z);
}
dfs(1, 0);
for (int i = 1; i <= n; ++i) {
ans = max(ans, query(a[i]));
insert(a[i]);
}
cout << ans;
}
return 0;