hdu 1213 How Many Tables 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1213
并查集水
题目大意:分桌吃饭,认识的人一桌。
题目分析:明显并查集。
code:
#include<stdio.h>
#include<string.h>
int match[1010];
void find(int x,int y)
{
while(x!=match[x])x=match[x];
while(y!=match[y])y=match[y];
if(x!=y)match[y]=x;
}
int main()
{
int t,i,j,n,m,a,b,temp,sum;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
memset(match,-1,sizeof(match));
for(i=0;i<1010;i++)
{
match[i]=i;
}
while(m--)
{
scanf("%d%d",&a,&b);
if(a>b)temp=a,a=b,b=temp;
//while(a!=b)match[b]=a,b=a,a=match[a];
find(a,b);
}
for(sum=0,i=1;i<=n;i++)
{
if(match[i]==i)sum++;
}
printf("%d\n",sum);
}
return 0;
}
PS:整三日未水,渐技艺生疏、思维钝化,与大神差距更有一日万里之势,念及此事,不免悲从中来,于是痛下决心,按原计划行事。
PSS:并查集的思想还没完全理解,注释掉的地方是自己的方法,样例过wrong answer……