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;
}
相关推荐
Darkwanderor8 小时前
什么数据量适合用什么算法
c++·算法
zc.ovo8 小时前
河北师范大学2026校赛题解(A,E,I)
c++·算法
py有趣9 小时前
力扣热门100题之环形链表
算法·leetcode·链表
py有趣9 小时前
力扣热门100题之回文链表
算法·leetcode·链表
月落归舟10 小时前
帮你从算法的角度来认识二叉树---(二)
算法·二叉树
SilentSlot11 小时前
【数据结构】Hash
数据结构·算法·哈希算法
样例过了就是过了13 小时前
LeetCode热题100 柱状图中最大的矩形
数据结构·c++·算法·leetcode
wsoz13 小时前
Leetcode哈希-day1
算法·leetcode·哈希算法
阿Y加油吧13 小时前
LeetCode 二叉搜索树双神题通关!有序数组转平衡 BST + 验证 BST,小白递归一把梭
java·算法·leetcode