P4551 最长异或路径

题目来自洛谷网站:

思路:

代码:

cpp 复制代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 100010;

int n;
//存树
typedef pair<int, int> PII;
vector<PII> t[N];
//记录这个点到根节点的异或和
int ls[N];
//01字典树
int ch[N*31][2], idx;

//找到每个点到起点这一段的异或和
void dfs(int u, int father){
    for(auto [v, w]: t[u]){
        //判断子节点是不是父亲节点
        if(v == father) continue;
        //该点到起点 异或和
        ls[v] = ls[u] ^ w;
        dfs(v, u);
    }
}


void insert(int x){
    int p = 0;
    for(int i = 30; i >= 0; i--){
        int j = x >> i & 1;
        if(!ch[p][j]) ch[p][j] = ++idx;
        p = ch[p][j];
    }
}

//在树中查找1个节点和另1个节点的异或最大值
//返回的结果
int query(int x){
    int res = 0, p =0;
    for(int i = 30; i >= 0; i--){
        int j = x >> i & 1;
        if(ch[p][!j]){
            res += 1 << i;
            p = ch[p][!j];
        }
        else p = ch[p][j];
    }
    return res;
}

signed main(){
    cin >> n;
    for(int i = 1; i < n; i++){
        int x, y, z; cin >> x >> y >> z;
        //无向边
        t[x].push_back({y,z});
        t[y].push_back({x,z});
    }
    //找到每个点到起点这一段的异或和
    //节点从1开始的
    dfs(1,0);
    
    //将各点到起点的异或和 存到01字典树中
    for(int i = 1;i <= n; i++) insert(ls[i]);
    
    //枚举一个节点,在找到这个节点和树中一个节点异或的最大值
    int ans = 0;
    for(int i = 1; i <= n; i++){
        ans = max(ans, query(ls[i]));
    }
    
    cout << ans << endl;
    return 0;
}
相关推荐
迈巴赫车主5 分钟前
蓝桥杯20560逃离高塔
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
泯仲13 分钟前
Ragent项目7种设计模式深度解析:从源码看设计模式落地实践
java·算法·设计模式·agent
dulu~dulu17 分钟前
算法---寻找和为K的子数组
笔记·python·算法·leetcode
moonsea020328 分钟前
【无标题】
算法
佑白雪乐1 小时前
<ACM进度212题>[2026-3-1,2026-3-26]
算法·leetcode
穿条秋裤到处跑1 小时前
每日一道leetcode(2026.03.26):等和矩阵分割 II
算法·leetcode·矩阵
平凡灵感码头1 小时前
C语言 printf 数据打印格式速查表
c语言·开发语言·算法
哔哔龙1 小时前
Android OpenCV 实战:图片轮廓提取与重叠轮廓合并处理
android·算法
hz_zhangrl1 小时前
CCF-GESP 等级考试 2026年3月认证C++三级真题解析
c++·算法·程序设计·gesp·gesp2026年3月·gesp c++三级
x_xbx1 小时前
LeetCode:1. 两数之和
数据结构·算法·leetcode