POJ 3764 The xor-longest Path 01字典树+dfs

题目链接

http://poj.org/problem?id=3764

题意

给定一颗树,要求找出一条路径,其边的权值异或和最大。

思路

求出各节点到根的异或和,假设两结点u,v到根的异或和为a[u],a[v] 那么u到v的异或和为a[u]^a[v] ,u,v的lca到根因为重复被去掉了。插入字典树中查询就行了。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<string>
#include<queue>
#include<stack>
#include<set>
#include<map>
#define ll long long
using namespace std;
const int INF = ( 2e9 ) + 2;
const ll maxn = 1e5+100;
struct edge
{
    int v,w,next;
}e[maxn*3];
int head[maxn];
int tot,tot1,ans;
int t[maxn*33][2];
void add(int u,int v,int w)
{
    e[tot].v=v;
    e[tot].w=w;
    e[tot].next=head[u];
    head[u]=tot++;
}
void init()
{
    memset(head,-1,sizeof(head));
    tot=tot1=0;
    t[0][0]=t[0][1]=0;
    ans=0;
}
void insert(int rt,int st,int a)
{
    if(st==-1)return;
    int cur=(a>>st)&1;
    if(!t[rt][cur])t[rt][cur]=++tot1,t[tot1][1]=0,t[tot1][0]=0;
    insert(t[rt][cur],st-1,a);
}
int find(int rt,int st,int a)
{
    if(st==-1)return 0;
    int cur=(a>>st)&1;
    if(t[rt][cur^1])return (1<<st) + find(t[rt][cur^1],st-1,a);
    else return find(t[rt][cur],st-1,a);
}
void dfs(int u,int fa,int a)
{
    insert(0,31,a);
    for(int i=head[u];i!=-1;i=e[i].next)
    {
        int v=e[i].v,w=e[i].w;
        if(v==fa)continue;
        ans=max(ans,find(0,31,a^w));
        dfs(v,u,a^w);
    }
}
int main()
{
    int n,u,v,w;
    while(~scanf("%d",&n))
    {
        init();
        for(int i=1;i<=n-1;i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            add(u,v,w);
            add(v,u,w);
        }
        dfs(1,-1,0);
        printf("%d\n",ans);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值