【题解】The XOR-longest Path

The XOR-longest Path

https://ac.nowcoder.com/acm/problem/50349

前置知识:01trie树
分析:

  • 01trie树提供给我们的功能为我们塞进去一些数,然后我们可以logn内查询与其最大的异或和值。
  • 那不刚好可以满足我们o(n^2)暴力吗。。
#include<bits/stdc++.h>
typedef long double ld;
#define INF (1ll<<60)-1
const int M=1e6+6;
#define MP make_pair
#define pb push_back
using namespace std;
const int N=1e5+5;
int num[M],cnt=1;
int d[M][2];
int tot,ans;
vector< pair<int,int> >g[N];
void update(int x){
    int p=1;
    for(int i=31;i>=0;i--){
        if(d[p][(x>>i)&1]==0) d[p][(x>>i)&1]=++cnt;
        p=d[p][(x>>i)&1];
        num[p]++;
    }
}

int query(int x){
    int res=0;
    int p=1;
    for(int i=31;i>=0;i--){
        int t=(x>>i)&1;
        if(num[d[p][1^t]]) p=d[p][1^t],res+=(1<<i);
        else p=d[p][t];
    }
    return res;
}
void dfs(int u,int fa,int dis){
    update(dis);
    for(auto it:g[u]){
        int v=it.first,w=it.second;
        if(v!=fa)
            dfs(v,u,dis^w);
    }
}
void dfs2(int u,int fa,int dis){
    ans=max(ans,max(query(dis),dis));
    for(auto it:g[u]){
        int v=it.first,w=it.second;
        if(v!=fa)
            dfs2(v,u,dis^w);
    }
}
int main(){
    int n;
    scanf("%d",&n);
    for(int u,v,w,i=1;i<n;i++){
        scanf("%d%d%d",&u,&v,&w);
        g[u].pb(MP(v,w));
        g[v].pb(MP(u,w));
    }
    dfs(1,0,0);
    dfs2(1,0,0);

    printf("%d\n",ans);
    return 0;
}
全部评论

相关推荐

神哥了不得:放平心态,再找找看吧,主要现在计算机也变卷了,然后就比较看学历了,之前高中毕业你技术强,都能找到工作的
点赞 评论 收藏
分享
神哥不得了:首先我就是在成都,成都的互联网格外的卷,如果是凭现在的简历的话很难找到大厂,建议再添加一个高质量的项目上去,另外专业技能的话最好是超过每一条的一半
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务