How Many Tables
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 177 Accepted Submission(s) : 58
One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
2 5 3 1 2 2 3 4 5 5 1 2 5
2 4
/*
title:How Many Tables
问题分类:并查集
*/
#include<stdio.h>
int tree[1010];
void init(){
for(int i=1;i<1010;i++){
tree[i]=i;
}
}
int findRooot(int x){
if(tree[x]!=x){
x=findRooot(tree[x]);
}
return tree[x];
}
void merge(int x,int y){
int fx=findRooot(x);
int fy=findRooot(y);
if(fx!=fy){
tree[fy]=fx;
}
}
int main(){
freopen("in.txt","r",stdin);
int zu;
while(scanf("%d",&zu)!=EOF){
while(zu--){
init();
int n,k;
scanf("%d%d",&n,&k);
for(int i=1;i<=k;i++){
int a,b;
scanf("%d%d",&a,&b);
merge(a,b);
}
int count=0;
for(int i=1;i<=n;i++){
if(tree[i]==i){
count++;
}
}
printf("%d\n",count);
}
}
return 0;
}