POJ3764 The xor-longest Path

Posted acmerszl

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ3764 The xor-longest Path相关的知识,希望对你有一定的参考价值。

题意:

找出树上异或和最大的一条路径(p)
[ _{xor}length(p)=oplus_{ein_p}w(e) ]

01字典树。同样用到了简单的异或性质

  • (0oplus a = a, aoplus a = 0)

定义(f(u,v))(u)(v)的路径异或和。那么(f(u,v) = f(1,u)oplus f(1,v))

所以我们可以(dfs)跑出(f(1,i)),然后插入字典树,再跑一边在字典树查询即可。

注意建图用前向星建图。

#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
using namespace std;
const int N = 100010;
const int inf = 0X3f3f3f3f;
const long long INF = 0x3f3f3f3f3f3f3f3f;
const double eps = 1e-6;
const double pi = acos(-1.0);
const int mod = 1000000007;
typedef long long ll;

struct Edge{
    int to, next, w;
}e[2 * N];

int n;
int head[2 * N];
int tot, cnt;
int val[N], vall[32 * N];
int tri[32 * N][2];
bool vis[N];

void add(int u, int v, int w) {
    e[tot].to = v; e[tot].next = head[u]; e[tot].w = w; head[u] = tot++;
    e[tot].to = u; e[tot].next = head[v]; e[tot].w = w; head[v] = tot++;
}

void init() {
    tot = cnt = 0;
    memset(tri, 0, sizeof(tri));
    memset(val, 0, sizeof(val));
    memset(head, -1, sizeof(head));
    memset(vall, 0, sizeof(vall));
    for (int i = 1; i <= N; i++) vis[i] = false;
}

void dfs(int id, int x) {
    val[id] = x;
    vis[id] = true;
    for (int i = head[id]; ~i; i = e[i].next) {
        int v = e[i].to;
        val[v] = x ^ e[i].w;
        if (!vis[v])
            dfs(v, val[v]);
    }
}

void Insert(int x) {
    int u = 0;
    for (int i = 31; i >= 0; i--) {
        int bit = (x & (1 << i)) ? 1 : 0;
        if (!tri[u][bit])
            tri[u][bit] = tot++;
        u = tri[u][bit];
    }
    vall[u] = x;
}

int Query(int x) {
    int u = 0;
    for (int i = 31; i >= 0; i--) {
        int bit = (x & (1 << i)) ? 1 : 0;
        if (tri[u][bit ^ 1])
            u = tri[u][bit ^ 1];
        else
            u = tri[u][bit];
    }
    return x ^ vall[u];
}

int main() {
    while (~scanf("%d", &n)) {
        init();
        for (int i = 1; i < n; i++) {
            int u, v, w;
            scanf("%d %d %d", &u, &v, &w);
            u++; v++;
            add(u, v, w);
        }
        dfs(1, 0);
        for (int i = 1; i <= n; i++) {
            Insert(val[i]);
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            ans = max(ans, Query(val[i]));
        }
        printf("%d
", ans);
    }
}

以上是关于POJ3764 The xor-longest Path的主要内容,如果未能解决你的问题,请参考以下文章

POJ3764 The xor-longest Path

POJ3764 The xor-longest Path

POJ 3764 The xor-longest Path

POJ 3764 The xor-longest path

[POJ3764]The xor-longest PatTrie

poj3764 The xor-longest Path