最长异或值路径 trie

题目链接

https://www.acwing.com/problem/content/146/

给定一个树,树上的边都具有权值。

树中一条路径的异或长度被定义为路径上所有边的权值的异或和:

formula.png

⊕ 为异或符号。

给定上述的具有n个节点的树,你能找到异或长度最大的路径吗?

输入格式

第一行包含整数n,表示树的节点数目。

接下来n-1行,每行包括三个整数u,v,w,表示节点u和节点v之间有一条边权重为w。

输出格式

输出一个整数,表示异或长度最大的路径的最大异或和。

数据范围

1≤n≤100000
0≤u,v<n
0≤w<2^31

输入样例:

4
0 1 3
1 2 4
1 3 6

输出样例:

7

样例解释

样例中最长异或值路径应为0->1->2,值为7 (=3 ⊕ 4)

题解

数组a[i]存储几点i到0所有边权的异或和,那么任意两个点i,j之间的边权异或和为a[i]^a[j];

先dfs预处理一下数组a;

那么这个问题就转化成从数组a中取出两个数异或,求最大值,然后就可以用字典树做。

代码

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
int a[maxn];
int son[maxn*30][2],tot;
int head[maxn],to[maxn*2],c[maxn*2],nex[maxn*2],cnt;
void add(int u,int v,int w){
    to[cnt]=v;c[cnt]=w;nex[cnt]=head[u],head[u]=cnt++;
}
void dfs(int x,int f,int sum){
    a[x]=sum;
    for(int i=head[x];~i;i=nex[i]){
        int y=to[i];
        if(y==f) continue;
        dfs(y,x,sum^c[i]);
    }
}
void insert(int x){
    int p=0;
    for(int i=30;i>=0;i--){
        int &s=son[p][x>>i&1];
        if(s==0) s=++tot;
        p=s;
    }
}
int search(int x){
   int ans=0;
   int p=0;
   for(int i=30;i>=0;i--){
        int s=x>>i&1;
        if(son[p][!s]){
            ans+=1<<i;
            p=son[p][!s];
        }else{
            p=son[p][s];
        }
   }
   return ans;
}
int main(){
    int n;
    cin>>n;
    memset(head,-1,sizeof(head));
    for(int i=0;i<n-1;i++){
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        add(u,v,w);
        add(v,u,w);

    }
    dfs(0,-1,0);
    for(int i=0;i<n;i++) insert(a[i]);
    int ans=0;
    for(int i=0;i<n;i++){
        ans=max(ans,search(a[i]));
    }
    cout<<ans<<endl;
    return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值