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;
}
相关推荐
Reart16 分钟前
Leetcode 213.打家劫舍2(内含闲谈,打劫真是技术活,好题,716)
后端·算法
Reart1 小时前
Leetcode 198.打家劫舍(716)
后端·算法
Jerry1 小时前
LeetCode 110. 平衡二叉树
算法
玖玥拾2 小时前
C++ 数据结构 八大基础排序算法专题
数据结构·c++·算法·排序算法
Tim_102 小时前
【C++】017、new/delete与malloc/free的区别
java·数据结构·算法
从零开始的代码生活_2 小时前
C++ list 原理与实践:双向链表、迭代器与简化实现
开发语言·c++·后端·学习·算法·链表·list
ttod_qzstudio3 小时前
【软考算法】软件设计师下午第四题之动态规划:0-1 背包与最长公共子序列的“填表艺术“
算法·动态规划·软考
柒和远方4 小时前
LeetCode 139. 单词拆分 —— 从暴力回溯到 DP 完全背包
javascript·python·算法
从零开始的代码生活_4 小时前
C++ stack、queue 与 priority_queue:容器适配器原理与实战
开发语言·c++·后端·学习·算法
晚笙coding4 小时前
LeetCode 226. 翻转二叉树(Invert Binary Tree)
算法·leetcode·职场和发展