POJ 3764 The xor-longest Path 01字典树 邻接表

本文介绍了一种解决树上路径边异或和最大值问题的方法,通过使用前缀树来寻找最大异或值,并针对POJ平台的内存限制进行了优化。

题目链接:http://poj.org/problem?id=3764

题意: 求树上路径边异或和最大值

思路和上一篇一样
只是这个POJ 超内存一直wa也不提示
后来把vector改成 数组模拟之后就过了

代码:

#include <cstdio>
#include <iostream>
#include <queue>
#include <cstring>
#define sf scanf
#define pf printf
using namespace std;

using namespace std;
const int maxn = 100000 + 500;
typedef int LL;
int ch[32 * maxn][2];
LL value[32 * maxn];
int node_cnt;

inline void init(){
    node_cnt = 1;
    memset(ch[0],0,sizeof(ch));
}

inline void Insert(LL x){
    int cur = 0;
    for(int i = 32;i >= 0;--i){
        int idx = (x >> i) & 1;
        if(!ch[cur][idx]){
            memset(ch[node_cnt],0,sizeof(ch[node_cnt]));
            ch[cur][idx] = node_cnt;
            value[node_cnt++] = 0;
        }
        cur = ch[cur][idx];
    }
    value[cur] = x;
}

inline LL Query(LL x){
    int cur = 0;
    for(int i = 32;i >= 0;--i){
        int idx = (x >> i) & 1;
        if(ch[cur][idx ^ 1]) cur = ch[cur][idx ^ 1];
        else cur = ch[cur][idx];
    }
    return value[cur];
}

struct Edge{
    int v,next,c;
}edge[maxn * 2];
int head[maxn];
int tot;
void Add_Edge(int u,int v,int w){
    edge[tot].v = v;
    edge[tot].c = w;
    edge[tot].next = head[u];
    head[u] = tot++;
}

void init_Adj(){
    tot = 0;
    memset(head,-1,sizeof(head));
}
int ans;
void DFS(int cur,int cur_xor,int _fa){
    ans = max(ans,cur_xor ^ Query(cur_xor));
    Insert(cur_xor);
    for(int i = head[cur];~i;i = edge[i].next){

        if(edge[i].v != _fa){
            DFS(edge[i].v,cur_xor ^ edge[i].c,cur);
        }
    }
}
int main(){
//    freopen("read.txt","r",stdin);
    int n,u,v,w;
    while(~sf("%d",&n)){
        init_Adj();
        for(int i = 0;i < n - 1;++i){
            sf("%d%d%d",&u,&v,&w);
            Add_Edge(u,v,w);
            Add_Edge(v,u,w);
        }
        init();
        ans = 0;
        DFS(0,0,-1);
        pf("%d\n",ans);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值