zoukankan      html  css  js  c++  java
  • 【bzoj1954】Pku3764 The xor-longest Path Trie树

    题目描述

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

    输入

    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.

    输出

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

    样例输入

    4
    1 2 3
    2 3 4
    2 4 6

    样例输出

    7


    题解

    Trie树

    由于x^x=0,所以树上x和y之间路径的异或和 = x到根路径的异或和 xor y到根路径的异或和。

    所以我们先对整棵树进行dfs,求出每个节点到根的路径异或和dis,并加入到Trie树。

    然后枚举树上的节点,在Trie树中贪心查询与它异或和最大的数,并加到答案中即可。

    #include <cstdio>
    #include <algorithm>
    #define N 100010
    using namespace std;
    int head[N] , to[N << 1] , len[N << 1] , next[N << 1] , cnt , v[N] , c[N * 30][2] , tot;
    void add(int x , int y , int z)
    {
    	to[++cnt] = y , len[cnt] = z , next[cnt] = head[x] , head[x] = cnt;
    }
    void dfs(int x , int fa)
    {
    	int i;
    	for(i = head[x] ; i ; i = next[i])
    		if(to[i] != fa)
    			v[to[i]] = v[x] ^ len[i] , dfs(to[i] , x);
    }
    void insert(int x)
    {
    	int i , p = 0;
    	bool t;
    	for(i = 1 << 30 ; i ; i >>= 1)
    	{
    		t = x & i;
    		if(!c[p][t]) c[p][t] = ++tot;
    		p = c[p][t];
    	}
    }
    int query(int x)
    {
    	int i , p = 0 , ans = 0;
    	bool t;
    	for(i = 1 << 30 ; i ; i >>= 1)
    	{
    		t = x & i;
    		if(c[p][t ^ 1]) ans += i , p = c[p][t ^ 1];
    		else p = c[p][t];
    	}
    	return ans;
    }
    int main()
    {
    	int n , i , x , y , z , ans = 0;
    	scanf("%d" , &n);
    	for(i = 1 ; i < n ; i ++ ) scanf("%d%d%d" , &x , &y , &z) , add(x , y , z) , add(y , x , z);
    	dfs(1 , 0);
    	for(i = 1 ; i <= n ; i ++ ) insert(v[i]);
    	for(i = 1 ; i <= n ; i ++ ) ans = max(ans , query(v[i]));
    	printf("%d
    " , ans);
    	return 0;
    }
    

     

  • 相关阅读:
    【转】nginx(一) nginx详解
    美好生活需要全方位的保障
    Oracle私网mtu滚动修改实施方案
    小知识:后台执行Oracle创建索引免受会话中断影响
    小知识:Oracle RAC添加服务名实现单节点访问
    Windows平台安装Oracle11.2.0.4客户端报错INS-30131
    小知识:如何赋予用户查看所有存储过程和触发器的权限
    小知识:如何判定crontab任务的执行频度
    小知识:解决EXP-00003的报错
    Oracle删除索引规范
  • 原文地址:https://www.cnblogs.com/GXZlegend/p/7072616.html
Copyright © 2011-2022 走看看