hdu5606 tree (并查集)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu5606 tree (并查集)相关的知识,希望对你有一定的参考价值。

tree

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 823    Accepted Submission(s): 394


Problem Description
There is a tree(the tree is a connected graph which contains n points and n1 edges),the points are labeled from 1 to n,which edge has a weight from 0 to 1,for every point i[1,n],you should find the number of the points which are closest to it,the clostest points can contain i itself.
 

 

Input
the first line contains a number T,means T test cases.

for each test case,the first line is a nubmer n,means the number of the points,next n-1 lines,each line contains three numbers u,v,w,which shows an edge and its weight.

T50,n105,u,v[1,n],w[0,1]
 

 

Output
for each test case,you need to print the answer to each point.

in consideration of the large output,imagine ansi is the answer to point i,you only need to output,ans1 xor ans2 xor ans3.. ansn.
 

 

Sample Input
1 3 1 2 0 2 3 1
 

 

Sample Output
1 in the sample. $ans_1=2$ $ans_2=2$ $ans_3=1$ $2~xor~2~xor~1=1$,so you need to output 1.
 题意:n个节点的树,有的边权是1有的是0,是0表示距离近,而且比如1和2是0,1和3也是0,那么2和3之间也是0,转化为并查集,顺便路径压缩;
AC代码:
#include <iostream>
#include <cstdio>
#include <map>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1e6+5;
int flag[N],p[N];
int findset(int x)
{
    if(x!=p[x])return p[x]=findset(p[x]);
    return x;
}
int main()
{
    int T,n,u,v,w;
    scanf("%d",&T);
    while(T--)
    {
       scanf("%d",&n);
       for(int i=1;i<=n;i++)
       {
           flag[i]=0;
           p[i]=i;
       }
       for(int i=0;i<n-1;i++)
       {
           scanf("%d%d%d",&u,&v,&w);
           if(w==0)
           {
               int a=findset(u);
               int b=findset(v);
               p[a]=b;
           }
       }
       for(int i=1;i<=n;i++)
       {
           flag[findset(i)]++;
       }
       int ans=flag[findset(1)];
       for(int i=2;i<=n;i++)
       {
           ans=(ans^flag[findset(i)]);
       }
       printf("%d\n",ans);
    }
    return 0;
}

以上是关于hdu5606 tree (并查集)的主要内容,如果未能解决你的问题,请参考以下文章

hdu 5606 tree(并查集)

HDU-1325-Is It A Tree?(并查集)

HDU 1325 POJ 1308 Is It A Tree? (并查集)

HDU-1325&&POJ-1308 Is It A Tree?(基础并查集)

并查集 HDU-4424

hdu 1213 How Many Tables(并查集)