http://acm.hdu.edu.cn/showproblem.php?pid=1213
How Many Tables
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13492 Accepted Submission(s): 6620
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
#include<stdio.h>
#include<string.h>
int set[2000];
int Find(int x)
{
int r=x,i=x,j;
while(set[r]!=r)
r=set[r];
while(i!=r)
{
j=set[i];
set[i]=r;
i=j;
}
return r;
}
void merge(int x,int y)
{
x=Find(x);
y=Find(y);
if(y<x)
set[x]=y;
if(x<y)
set[y]=x;
}
int main()
{
int T,N,M,A,B,i,j,k;
scanf("%d",&T);
while(T--)
{
scanf("%d %d",&N,&M);
memset(set,0,sizeof(set));
for(i=1;i<=N;i++)
set[i]=i;
for(i=1;i<=M;i++)
{
scanf("%d %d",&A,&B);
merge(A,B);
}
int sum;
for(i=1,sum=0;i<=N;i++)
if(set[i]==i)
sum+=1;
printf("%d\n",sum);
}
return 0;
}
292



被折叠的 条评论
为什么被折叠?



