The xor-longest Path POJ - 3764(Tire&&dfs&&贪心)

The xor-longest Path POJ - 3764

题意:

本题是求异或路径的最大。

思路:

  1. 关于求n个数里,异或最大的思路。传送门
  2. 先把每个点到根的异或路径算出来d【i】。
  3. 那么u和v两两之间的异或路径。就可以转换成d【u】^d【v】。
  4. 之后问题就转换成:n个数里,异或最大

反思:

本题要用到快读。(不然会TLE。当然scanf也可。)

AC

#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <algorithm>
#define fzhead EDGE(int _to, int _next, int _val)
#define fzbody to(_to), next(_next), val(_val)
#define mst(x,a) memset(x,a,sizeof(x))
#define For(i,x,y) for(int i=(x); i<=(y); i++)
using namespace std;
inline int read(){
    int ans=0;
    char r=getchar();bool neg=false;
    while(r<'0'||r>'9'){if(r=='-')neg=true;r=getchar();}
    while(r>='0'&&r<='9'){ans=ans*10+r-'0';r=getchar();}
    return (neg)?-ans:ans;
}
void write(int x){
    if(x<0){putchar('-');x=-x;}
    if(x>9)write(x/10);
    putchar(x%10+'0');
}
typedef long long ll;
const int maxnode=4e6+10;
int ch[maxnode][2];
int sz=2;
void clear(){sz=2;mst(ch[1],0);}
void insert(ll str){
    int u=1;
    for(int i=32; i>=0; i--){
        ll k=(str>>i)&1;
        if(!ch[u][k]){
            mst(ch[sz],0);
            ch[u][k]=sz++;
        }
        u=ch[u][k];
    }
    return;
}
ll find(ll str){
    ll res=0,u=1;
    for(int i=32; i>=0; i--){
        ll k=(str>>i)&1;
        if(ch[u][k^1]){
            u=ch[u][k^1];
            res+= (1<<i);
        }else u=ch[u][k];
    }
    return res;
}
const int maxn=1e5+10;
const int maxm=2e5+10;
struct EDGE{
    int to,next,val;
    EDGE(){}
    fzhead:fzbody{}
}e[maxm];
int cnt,head[maxn],n;
int d[maxn];
void init(){
    clear();
    cnt=0;
    mst(head,-1);
    mst(d,0);
}
void add(int bg, int to, int val){
    e[cnt]=EDGE(to,head[bg],val);
    head[bg]=cnt++;
}
void dfs(int u, int fa){
   // cout<<u<<' '<<fa<<endl;
    for(int i=head[u]; i!=-1; i=e[i].next){
        int v=e[i].to;
        if(v==fa)continue;
        d[v]=d[u]^e[i].val;
        dfs(v,u);
    }
}
int main()
{
    //ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    while(cin>>n){
        init();
        int u,v,w;
        For(i,1,n-1){
           u=read();v=read();w=read();// scanf("%d%d%d",&u,&v,&w);//cin>>u>>v>>w;
            add(u,v,w);add(v,u,w);
        }
        dfs(0,-1);
        ll ans=0;
       // cout<<"OK"<<endl;
        for(int i=0; i<n; i++){
            insert(d[i]);
            ans=max(ans,find(d[i]));
        }
        cout<<ans<<endl;
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值