BZOJ 1954 The xor-longest Path (01 Trie + 贪心)

Description
给定一棵n个点的带权树,求树上最长的异或和路径

Input
The input contains several test cases. The first line of each test case contains an integer n(1<=n<=100000), The following n-1 lines each contains three integers u(0 <= u < n),v(0 <= v < n),w(0 <= w < 2^31), which means there is an edge between node u and v of length w.

Output
For each test case output the xor-length of the xor-longest path.

Examples
Sample Input
4
1 2 3
2 3 4
2 4 6
Sample Output
7

Hint
The xor-longest path is 1->2->3, which has length 7 (=3 ⊕ 4)
注意:结点下标从1开始到N…
Source
鸣谢陶文博

Solution
先预处理出树上任意一点到根节点的路径异或值,所以树上任意两点的路径异或值 = (root,u) ^ (root.v)
最后用01 Trie 从根节点开始,贪心地选与这一位相反的值

Code

const int maxn = 1e5 + 7;
int ecnt,head[maxn<<1];
struct Edge{
    int v,w,next;
}e[maxn<<1];
void add(int u,int v,int w){
    e[++ecnt] = (Edge) {v,w,head[u]}, head[u] = ecnt;
    e[++ecnt] = (Edge) {u,w,head[v]}, head[v] = ecnt;
}
int tot,trie[maxn*30][2];
void insert(int val){
    int u = 0;
    for(int i = (1<<30);i;i>>=1){
        bool c = val & i;
        if(!trie[u][c]) trie[u][c] = ++tot;
        u = trie[u][c];
    }
}

int search(int val){
    int u = 0, res = 0;
    for(int i = (1 << 30);i;i>>=1){
        bool c = val & i;
        if(trie[u][!c]) res += i, u = trie[u][!c];
        else u = trie[u][c];
    }
    return res;
}

int val[maxn];
void dfs(int u,int fa){
    for(int i = head[u];i;i = e[i].next){
        int v = e[i].v;if(v == fa) continue;
        val[v] = val[u] ^ e[i].w;
        dfs(v,u);
    }
}


int main(){
    int n,res = 0;scanf("%d",&n);
    for(int i = 1,u,v,w;i < n;++i){
        scanf("%d%d%d",&u,&v,&w);add(u,v,w);
    }
    val[1] = 0;dfs(1,-1);
    for(int i = 1;i <= n;++i) insert(val[i]);
    for(int i = 1;i <= n;++i){
        res = max(res,search(val[i]));
    }
    printf("%d\n", res);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值