1006: 球
Time Limit: 1 Sec Memory Limit: 128 MB
[ Submit][ Status][ Web Board]
Problem Description
Icy is a lonely boy. He was so boring these days. So he started to play a game himself. First, he took a heap of balls with many different colors. ( One ball with only one color ) Then he repeated to pick two balls and put them back. Each time the two balls he chose is of the same color. After M times, Icy was too boring to fall asleep.
Now, a boring people wanna ask you a very easy question: how many different colors are there in the original heap at most ?
Input
The first line contains one integer T indicating the number of test cases.
For each test case, the first line contains two integer numbers N and M (0 <= N,M<= 10000) that represents the total number of balls and the number of times Icy took balls.Balls are numbered from 1 to N.Each of the following M lines contains two integer numbers A and B (1 <= A, B <= N). It means that Icy picked ball A and ball B.
Output
For each test case, output an integer that satisfies the problem description.
Sample Input
2 3 3 1 2 2 3 1 3 3 1 1 2
Sample Output
1 2 #include<stdio.h> #define maxn 1005 int r[maxn],num[maxn]; int n,m; int root(int a) { if(r[a]==a) return a; else return r[a]=root(r[a]); } void init() { for(int i=1;i<=n;i++) r[i]=i,num[i]=1; } int merge(int a,int b) { int ra,rb; ra=root(ra); rb=root(rb); if(ra==rb) return 0; if(num[ra]>num[rb]) r[rb]=ra,num[ra]+=num[rb]; else r[ra]=rb,num[rb]+=num[ra]; } int main() { int t,i,a,b; scanf("%d",&t); while(t--) { int cnt=0; scanf("%d%d",&n,&m); init(); for(i=1;i<=m;i++) { scanf("%d%d",&a,&b); merge(a,b); } for(i=1;i<=n;i++) if(r[i]==i) cnt++; printf("%d\n",cnt); } return 0; }