最长异或值路径(dfs + Trie树)

题目链接:最长异或路径

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

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

给定上述的具有n个节点的树,输出异或长度最大的路径。

Input

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

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

Output

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

Example

Input

4
0 1 3
1 2 4
1 3 6

Output

7

Note

样例中最长异或值路径应为0->1->2,值为3^4=7 1≤n≤105,0≤u,v<n,0≤w<231


思路:

题目要求最大异或和路径,首先便是想到Trie树求最大异或和。

我们只需要dfs将所有节点到根节点的异或和加入到一个数组内,然后对这个数组内的所有异或和数通过Trie树求最大异或和即可。

因为任何节点都有可能是根节点,所以要建无向图。

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
#include <string>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
const int N = 1e5 + 7, M = 1e5 + 7, mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
int n, e[2 * N], ne[2 * N], w[2 * N], h[N], idx, son[N * 31][2];
vector<int> v;
// 邻接表存储树
void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
bool st[N];//避免dfs的时候重复
void dfs(int u, int val)//u表示当前节点,val表示当前节点与上一节点间的权值
{
    st[u] = true;
    v.push_back(val);
    for (int i = h[u]; i != -1; i = ne[i])
    {
        int j = e[i];
        if (!st[j])
        {
            dfs(j, val ^ w[i]);
        }
    }
}
//Trie树插入操作
void insert(int x)
{
    int p = 0;
    for (int i = 30; i >= 0; i --)
    {
        int u = x >> i & 1;
        if (!son[p][u]) son[p][u] = ++ idx;
        p = son[p][u];
    }
}
//Trie树查询操作
int query(int x)
{
    int p = 0, res = 0;
    for (int i = 30; i >= 0; i -- )
    {
        int u = x >> i & 1;
        if (son[p][!u])
        {
            p = son[p][!u];
            res = (res << 1) + 1;
        }
        else
        {
            p = son[p][u];
            res = res << 1;
        }
    }
    return res;
}
int main()
{
    memset(h, -1, sizeof h);
    scanf("%d", &n);
    for (int i = 0; i < n - 1; i ++ )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        add(a, b, c), add(b, a, c);
    }
    st[0] = true;
    for (int i = h[0]; i != -1; i = ne[i])
        dfs(e[i], w[i]);
    int res = 0;
    for (auto item : v)
    {
        insert(item);
        //因为v数组内的数值已经是异或和路径了,所以要先求一下最大值
        res = max(res, item);
        res = max(res, query(item));
    }
    printf("%d", res);
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值