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) = 顶点uv之间的最短路。

(2)   xor-distance(u, v) = epath(u,v)length(e), ⊕代表异或操作。

请计算出有多少对点的xor-distance的值等于K0 <= K <= 500000)。(v != u 并且 pair(u,v) = pair(v,u))。

Input

第一行是一个整数T,表示有T组测试数据。

接下来T组测试数据,每组测试数据开始为两个正整数NK,接下来N-1行每行包含三个整数u,v,L(0 <= u,v <= N-1),代表树中存在一条顶点为uv,边长为L的边。

Output

每组一行,输出点对的个数。

Sample Input

2

4 1

0 1 1

1 2 3

2 3 2

3 0

0 1 7

0 2 7


Sample Output

2

1


Source2016级新生程序设计全国邀请赛

思路:


①思考我们求树上两点间距离的方式是: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);        }    }}








原创粉丝点击