hdu 5606 tree(并查集)

时间:2020-12-06 21:27:30
Problem Description
There is a tree(the tree is a connected graph which contains n points and n−1 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.
T≤50,n≤105,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.

 

hdu 5606 tree(并查集)

 #pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<queue>
#include<set>
#include<bitset>
#include<map>
#include<vector>
#include<stdlib.h>
using namespace std;
#define ll long long
#define eps 1e-10
#define MOD 1000000007
#define N 100006
#define inf 1e12
int n;
int fa[N];
int num[N];
void init(){
for(int i=;i<N;i++){
fa[i]=i;
}
}
int find(int x){
return fa[x]==x?x:fa[x]=find(fa[x]);
}
void merge(int x,int y){
int root1=find(x);
int root2=find(y);
if(root1==root2) return;
fa[root1]=root2;
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
init();
scanf("%d",&n);
for(int i=;i<n-;i++){
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
if(c==){
merge(a,b);
}
} memset(num,,sizeof(num));
for(int i=;i<=n;i++){
int r=find(i);
num[r]++;
}
int ans=;
for(int i=;i<=n;i++){
ans=(ans^num[find(i)]);
}
printf("%d\n",ans);
}
return ;
}