Hrbust 2302 Another Tree【思维+Dfs】
来源:互联网 发布:手机淘宝怎样发送链接 编辑:程序博客网 时间:2024/06/05 10:43
Another TreeTime Limit: 1000 MSMemory Limit: 32768 KTotal Submit: 46(17 users)Total Accepted: 17(15 users)Rating: Special Judge: NoDescription
给出一棵有N个节点(2 <= N <= 500000)和N-1条边的树,每条边拥有一个长度L(1 <= L <= 500000)。
定义:
(1) path(u, v) = 顶点u和v之间的最短路。
(2) xor-distance(u, v) = ⊕e∈path(u,v)length(e), ⊕代表异或操作。
请计算出有多少对点的xor-distance的值等于K(0 <= K <= 500000)。(v != u 并且 pair(u,v) = pair(v,u))。
Input第一行是一个整数T,表示有T组测试数据。
接下来T组测试数据,每组测试数据开始为两个正整数N,K,接下来N-1行每行包含三个整数u,v,L(0 <= u,v <= N-1),代表树中存在一条顶点为u,v,边长为L的边。
Output每组一行,输出点对的个数。
Sample Input2
4 1
0 1 1
1 2 3
2 3 2
3 0
0 1 7
0 2 7
2
1
思路:
①思考我们求树上两点间距离的方式是:Dist(root,x)+Dist(root,y)-2*Dist(root,Lca(x,y));
②从而递推出当前问题亦或的距离:Dist(root,x)^Dist(root,y)^Dist(root,Lca(x,y))^Dist(root,Lca(x,y));从而化简为:Dist(root,x)^Dist(root,y)
③那么问题就是在寻找点对,使得其亦或和为K,那么我们随便定义一个点为根即可,去Dfs一遍树,记录vis【i】表示从根到点路径上的亦或和为i的点的个数。
那么对于统计答案的时候枚举一下即可。
Ac代码:
#include<stdio.h>#include<string.h>using namespace std;struct node{ int from,to,w,next;}e[1000050];int cont;int head[1050000];int vis[1050000];void add(int from,int to,int w){ e[cont].to=to; e[cont].w=w; e[cont].next=head[from]; head[from]=cont++;}void Dfs(int u,int from,int val){ if(from!=-1)vis[val]++; for(int i=head[u];i!=-1;i=e[i].next) { int v=e[i].to; int w=e[i].w; if(v==from)continue; Dfs(v,u,val^w); }}int main(){ int t;scanf("%d",&t); while(t--) { cont=0; memset(vis,0,sizeof(vis)); memset(head,-1,sizeof(head)); int n,k;scanf("%d%d",&n,&k); for(int i=1;i<=n-1;i++) { int x,y,w;scanf("%d%d%d",&x,&y,&w); x++,y++; add(x,y,w);add(y,x,w); } Dfs(1,-1,0); if(k==0) { long long int output=0; for(int i=0;i<=1000000;i++) { output+=(long long int )vis[i]*(vis[i]-1)/2; } printf("%lld\n",output); } else { long long int output=0; for(int i=0;i<=1000000;i++) { output+=vis[i]*vis[i^k]; } printf("%lld\n",output); } }}
阅读全文
0 0
- Hrbust 2302 Another Tree【思维+Dfs】
- Codeforces 430C Xor-tree【Dfs+思维】
- CF758E:Broken Tree(DFS & 思维)
- leetcode 572. Subtree of Another Tree 深度优先遍历DFS
- Hrbust 1535 相爱【思维】
- Hrbust 1290 放球球【Dfs】
- hrbust 1143泉水DFS
- bfs\dfs hrbust 1143
- Poj 3013 /hrbust 1419 Big Christmas Tree/昂贵的假花【SPFA+思维】
- POJ 2255/hrbust 2022 Tree Recovery【dfs、二叉树的层次遍历】
- Codeforces 618D Hamiltonian Spanning Tree【思维+Dfs】
- hrbust 1040 Mining【SPFA+思维】
- hrbust 1759 Lawnmower【思维题】
- hrbust 1602 换座位【思维】
- Hrbust 1456 Matryoshka Dolls【思维】
- hrbust 2309 Another Josephus 约瑟夫环
- another DFS problem POJ3009
- HRBUST 1564 螺旋矩阵 DFS
- 基于数组的列表实现
- Spring 松耦合实例
- G
- Linux学习掌握(三):CentOS中安装(卸载)Mysql以及数据库的导入导出
- Scikit-learn使用总结
- Hrbust 2302 Another Tree【思维+Dfs】
- 一个理解装饰器很好的例子
- java实现https请求
- Httpclient多线程连接池封装
- MySQL 5.6 for Windows 解压缩版配置安装(win 10 64位亲测)附安装包下载链接
- 网贷信息强制披露又升级,零逾期率造假平台无所遁形!!
- 机器学习实战笔记(3.2)-朴素贝叶斯算法(贝努力模型代码实现)
- 对磁盘扇区数据的访问
- 几个常用的命令