题意:给出一颗n个节点的边权树,求一条路径(u,v),使得路径上的边的权值异或值最大。
析:先从0开始遍历树,记录所有的点到0的路径的边权异或值,然后任意两点的路径的异或值就是dp[u]^dp[v],
然后再构造一棵二进制树,每次查询,注意长度要相同,最后求最大值即可。
代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 100000 + 50;
const LL mod = 2147483648;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}
struct Edge{
int to, w, next;
};
int head[maxn];
int cnt;
Edge a[maxn<<1];
int dp[maxn];
void add(int u, int v, int w){
a[cnt].to = v;
a[cnt].w = w;
a[cnt].next = head[u];
head[u] = cnt++;
}
bool vis[maxn];
void dfs(int u){
for(int i = head[u]; ~i; i = a[i].next){
int v = a[i].to;
if(vis[v]) continue;
vis[v] = 1;
dp[v] = dp[u] ^ a[i].w;
dfs(v);
}
}
const int maxnode = maxn * 64 + 10;
const int siga_size = 2;
struct Trie{
int ch[maxnode][siga_size];
int val[maxnode];
int sz;
void init(){
sz = 1;
memset(ch[0], 0, sizeof ch[0]);
}
void insert(int *s, int v, int len){
int u = 0;
for(int i = len; i >= 0; --i){
int c = s[i];
if(!ch[u][c]){
memset(ch[sz], 0, sizeof ch[sz]);
val[sz] = 0;
ch[u][c] = sz++;
}
u = ch[u][c];
}
val[u] = v;
}
int query(int *s, int len){
int u = 0;
for(int i = len; i >= 0; --i){
int c = s[i]^1;
if(!ch[u][c]) c ^= 1;
if(!ch[u][c]) return val[u];
u = ch[u][c];
}
return val[u];
}
};
Trie trie;
int main(){
while(scanf("%d", &n) == 1){
memset(head, -1, sizeof head);
cnt = 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);
}
memset(vis, 0, sizeof vis);
vis[0] = 1; dp[0] = 0;
dfs(0);
trie.init();
for(int i = 0; i < n; ++i){
int len = -1, x = dp[i];
int s[50];
while(x){
s[++len] = x % 2;
x /= 2;
}
while(len < 30) s[++len] = 0;
trie.insert(s, dp[i], len);
}
int ans = 0;
for(int i = 0; i < n; ++i){
int len = -1, x = dp[i];
int s[50];
while(x){
s[++len] = x % 2;
x /= 2;
}
while(len < 30) s[++len] = 0;
ans = max(ans, dp[i]^trie.query(s, len));
}
printf("%d
", ans);
}
return 0;
}