How Many Tables
http://acm.hdu.edu.cn/diy/contest_showproblem.php?pid=1002&cid=12467&hide=0
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 11 Accepted Submission(s) : 5
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
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.
Input
Output
Sample Input
2 5 3 1 2 2 3 4 5 5 1 2 5
Sample Output
2 4
Author
Source
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 1005
int parent[N];
void init(int n){
for(int i=1;i<=n;i++)
parent[i]=i;
}
int find(int x){
while(x!=parent[x])
x=parent[x];
return x;
}
void merge(int x,int y){
x=find(x);
y=find(y);
parent[x]=y;
}
int main(){
int n,m,sum,t,x,y;
scanf("%d",&t);
while(t--){
sum=0;
scanf("%d %d",&n,&m);
init(n);
while(m--){
scanf("%d %d",&x,&y);
merge(x,y);
}
for(int i=1;i<=n;i++){
if(find(i)==i)
sum++;
}
printf("%d\n",sum);
}
return 0;
}