您的位置:首页 > 其它

BZOJ1954 Pku3764 The xor-longest Path

2014-12-20 23:00 281 查看
"trie的经典应用" -- by hzwer

我们把每个点到根的xor值记下来,然后找出两个xor值最大的即可(因为(a ^ c) ^ (b ^ c) = a ^ b)

于是用trie把每个数的二进制位记下来,每次query的时候利用贪心,试图走到另一个儿子即可。

/**************************************************************
Problem: 1954
User: rausen
Language: C++
Result: Accepted
Time:360 ms
Memory:27368 kb
****************************************************************/

#include <cstdio>
#include <algorithm>

using namespace std;
const int N = 100005;

struct edge {
int next, to, v;
edge() {}
edge(int _n, int _t, int _v) : next(_n), to(_t), v(_v) {}
} e[N << 1];

int first
, tot;

struct trie_node {
int son[2];
} t[3000005];

int cnt_trie = 1, root = 1;

int n, ans;
int v
, a[40];

inline int read() {
int x = 0, sgn = 1;
char ch = getchar();
while (ch < '0' || '9' < ch) {
if (ch == '-') sgn = -1;
ch = getchar();
}
while ('0' <= ch && ch <= '9') {
x = x * 10 + ch - '0';
ch = getchar();
}
return sgn * x;
}

void Add_Edges(int x, int y, int z) {
e[++tot] = edge(first[x], y, z), first[x] = tot;
e[++tot] = edge(first[y], x, z), first[y] = tot;
}

void dfs(int p, int fa) {
int x, y;
for (x = first[p]; x; x = e[x].next)
if ((y = e[x].to) != fa) {
v[y] = v[p] ^ e[x].v;
dfs(y, p);
}
}

void insert(int x) {
int now, i, cnt_a = 0;
for (i = 0; i <= 30; ++i)
a[i] = x & 1, x >>= 1;
reverse(a, a + 31);
now = root;
for (i = 0; i <= 30; ++i) {
if (!t[now].son[a[i]]) t[now].son[a[i]] = ++cnt_trie;
now = t[now].son[a[i]];
}
}

int query(int x) {
int now, i, cnt_a = 0, res = 0;
for (i = 0; i <= 30; ++i)
a[i] = x & 1, x >>= 1;
reverse(a, a + 31);
now = root;
for (i = 0; i <= 30; ++i) {
if (t[now].son[!a[i]]) now = t[now].son[!a[i]], res += (1 << 30 - i);
else now = t[now].son[a[i]];
}
return res;
}

int main() {
int i, x, y, z;
n = read();
for (i = 1; i < n; ++i) {
x = read(), y = read(), z = read();
Add_Edges(x, y, z);
}
dfs(1, 0);
for (i = 1; i <= n; ++i)
insert(v[i]);
for (i = 1; i <= n; ++i)
ans = max(ans, query(v[i]));
printf("%d\n", ans);
return 0;
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: