码迷,mamicode.com
首页 > 其他好文 > 详细

POJ3764 The xor-longest Path

时间:2020-01-22 20:12:45      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:size   dfs   algorithm   for   scan   简单的   前向星   while   ems   

题意:

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

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

  • \(0\oplus a = a, a\oplus 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\n", ans);
    }
}

POJ3764 The xor-longest Path

标签:size   dfs   algorithm   for   scan   简单的   前向星   while   ems   

原文地址:https://www.cnblogs.com/ACMerszl/p/12229182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!