AcWing 144. 最长异或值路径 (树上路径转化)

🚧 🚧 🚧
在这里插入图片描述拿出了以前的链式向前星板子,所以整个代码变得很丑。。

#define int ll
int a[MAXN],tot,son[MAXN*32][2];
void build(int x)
{
    int p=0;
    for(int k=32;k>=0;--k)
    {
        int tmp=((x&(1ll<<k))==0?0:1);
        if(son[p][tmp]==0) son[p][tmp]=++tot;
        p=son[p][tmp];
    }
}
int solve(int x)
{
    int p=0,ans=0;
    for(int k=32;k>=0;--k)
    {
        int tmp=((x&(1ll<<k))==0?0:1);
        if(son[p][!tmp]) ans|=(1ll<<k),p=son[p][!tmp];
        else p=son[p][tmp];
        if(p==0) break;
    }
    return ans;
}
class Graph
{
    public:
        int tot,head[MAXN];
        struct IN{int v,next,w;}edge[MAXN<<1];

        void init(){memset(head,0,sizeof(head));tot=1;}
        void addedge(int u,int v,int w)
        {
            edge[tot].v=v;edge[tot].w=w;
            edge[tot].next=head[u];
            head[u]=tot++;
        }
        int Start(int u){return head[u];}
        int To(int i){return edge[i].v;}
        int Val(int i){return edge[i].w;}
        int Next(int i){return edge[i].next;}
}G;
int n,m;
void input()
{
    cin>>n;m=n-1;
    G.init();
    for(int i=0;i<m;i++)
    {
        int u,v,w;cin>>u>>v>>w;
        G.addedge(u,v,w);
        G.addedge(v,u,w);
    }
}
int sum=0;
void dfs(int x,int fa)
{
    a[x]=sum;
    for(int i=G.Start(x);i!=0;i=G.Next(i))
    {
        int v=G.To(i);
        if(v==fa) continue;
        sum^=G.Val(i);
        dfs(v,x);
        sum^=G.Val(i);
    }
}
signed main()
{
    fast;
    input();
    dfs(0,-1);
    rep(i,n) build(a[i]);
    int ans=0;
    rep(i,n)   ans=max(ans,solve(a[i]));
    cout<<ans<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值