嘘~ 正在从服务器偷取页面 . . .

洛谷P4551 最长异或路径 题解


洛谷P4551 最长异或路径 题解

题目链接:P4551 最长异或路径

题意:给定一棵 \(n\) 个点的带权树,结点下标从 \(1\) 开始到 \(n\)。寻找树中找两个结点,求最长的异或路径。

异或路径指的是指两个结点之间唯一路径上的所有边权的异或。

\(1\le n \le 100000,~0 < u,v \le n,~0 \le w < 2^{31}\)

首先可以想到一个常用trick:前缀和处理边权异或和

然后对于每个异或和,我们都要找到一个和它异或值尽可能大的前缀和

直接枚举是不行的,考虑建01trie

01trie其实很简单,就是把每个数字的二进制形式看成字符串去建trie

贪心地选择高位,具体看代码就可以了,很简单

时间复杂度 \(O(n \log \max\{w_i\})\) ,其实就是 \(O(30 \times n)\)

代码:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iomanip>
using namespace std;
// #define int long long
#define INF 0x3f3f3f3f3f3f3f3f
#define N (int)(1e5+5)

struct Edge
{int u,v,w,next;}e[N<<1];
int n,pos=1,sum[N],head[N];
void addEdge(int u,int v,int w)
{
    e[++pos]={u,v,w,head[u]};
    head[u]=pos;
}
struct Trie
{
    int trie[N*30][2],tot;
    void insert(int x)
    {
        int u=0;
        for(int i=30; i>=0; i--)
        {
            bool c=x&(1<<i);
            if(!trie[u][c])trie[u][c]=++tot;
            u=trie[u][c];
        }
    }
    int query(int x)
    {
        int res=0,u=0;
        for(int i=30; i>=0; i--)
        {
            bool c=!(x&(1<<i));
            if(trie[u][c])
            {
                res+=(1<<i);
                u=trie[u][c];
            }else u=trie[u][!c];
        }
        return res;
    }
}tr;
void dfs(int u,int f)
{
    for(int i=head[u]; i; i=e[i].next)
    {
        int v=e[i].v,w=e[i].w;
        if(v==f)continue;
        sum[v]=sum[u]^w; dfs(v,u);
    }
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    // freopen("check.in","r",stdin);
    // freopen("check.out","w",stdout);
    cin >> n;
    for(int i=1,u,v,w; i<n; i++)
    {
        cin >> u >> v >> w;
        addEdge(u,v,w); addEdge(v,u,w);
    }
    dfs(1,1);
    for(int i=1; i<=n; i++)
        tr.insert(sum[i]);
    int res=0;
    for(int i=1; i<=n; i++)
        res=max(res,tr.query(sum[i]));
    cout << res << '\n';
    return 0;
}

文章作者: q779
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 q779 !
评论
  目录