zoukankan      html  css  js  c++  java
  • 【BZOJ】1954: Pku3764 The xor-longest Path

    【算法】trie树+xor路径

    【题解】

    套路1:统计从根到每个点的xor路径和,由于xor的自反性,两个点到根的xor路径和异或起来就得到两点间路径和。

    然后问题就是找到n个值中异或值最大的两个值,考虑枚举每个数字,对于一个数找到与其异或和最大的数。

    套路2:对所有数值二进制建01-trie,对于一个已知数字在trie上每一层尽量往另一端走,O(log n)得到与其异或和最大的数。

    复杂度O(n log n)。

    另一种做法,用两个指针从根往下,尽量分叉走,查询总复杂度O(log n),但是建树仍然需要O(n log n)。

    #include<cstdio>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    const int maxn=100010;
    struct edge{int v,w,from;}e[maxn*2];
    int t[maxn*33][2],dfsnum=0,cnt=0,tot=0,p[maxn*2],first[maxn],n;
    bool val[maxn*33];
    void insert(int u,int v,int w)
    {tot++;e[tot].v=v;e[tot].w=w;e[tot].from=first[u];first[u]=tot;}
    void push(int x){
        int u=0;
        for(int i=30;i>=0;i--){
            bool c=x&(1<<i);
            if(!t[u][c])t[u][c]=++dfsnum;
            u=t[u][c];
        }
        val[u]=1;
    }
    int find(int x){
        int u=0,ans=0;
        for(int i=30;i>=0;i--){
            bool c=x&(1<<i);
            if(!t[u][!c])u=t[u][c];
            else{u=t[u][!c];ans|=(1<<i);}
        }
        return ans;
    }        
    void dfs(int x,int fa,int num){
        push(p[++cnt]=num);
        for(int i=first[x];i;i=e[i].from)if(e[i].v!=fa){
            dfs(e[i].v,x,num^e[i].w);
        }
    }
    int main(){
        scanf("%d",&n);
        int u,v,w;
        for(int i=1;i<n;i++){
            scanf("%d%d%d",&u,&v,&w);
            insert(u,v,w);
            insert(v,u,w);
        }
        dfs(1,-1,0);
        int ans=0;
        for(int i=1;i<=cnt;i++){
            ans=max(ans,find(p[i]));
        }
        printf("%d",ans);
        return 0;
    }
    View Code
  • 相关阅读:
    **没有规则可以创建“XXX”需要的目标“XXX”问题的解决方案
    牛逼博主
    tiny4412 busybox制作根文件系统rootfs nfs 挂载 ubuntu 14.04
    解决 mounting /dev/block/mmcblk0p1 on /sdcard failed
    如何在虚拟机上配置hadoop集群
    数据结构线性表
    a伪类,关于图片
    脱离标准文档流(2)---定位
    脱离标准文档流(1)---浮动
    初窥css---盒子以及盒子扩展
  • 原文地址:https://www.cnblogs.com/onioncyc/p/7327281.html
Copyright © 2011-2022 走看看