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;
}
相关推荐
晚枫~33 分钟前
图论基础:探索节点与关系的复杂网络
网络·数据结构·图论
liu****1 小时前
20.哈希
开发语言·数据结构·c++·算法·哈希算法
夏鹏今天学习了吗1 小时前
【LeetCode热题100(47/100)】路径总和 III
算法·leetcode·职场和发展
smj2302_796826522 小时前
解决leetcode第3721题最长平衡子数组II
python·算法·leetcode
m0_626535202 小时前
力扣题目练习 换水问题
python·算法·leetcode
第六五2 小时前
DPC和DPC-KNN算法
人工智能·算法·机器学习
一匹电信狗2 小时前
【LeetCode_160】相交链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
再卷也是菜3 小时前
C++篇(14)二叉树进阶算法题
c++·算法
小邓儿◑.◑3 小时前
贪心算法 | 每周8题(三)
算法·贪心算法
2401_841495643 小时前
【数据结构】最长的最短路径的求解
java·数据结构·c++·python·算法·最短路径·图搜索