题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1213
题目大意:今天是Ignatius的生日,他要宴请一些客人,但是客人彼此之间并不是完全互相认识的,规定如果A认识B,且B认识C,则认为A,B,C互相认识,可以安排在同一桌,求需要安排的桌数。
解题思路:简单的并查集。
AC代码:
#include <iostream>
using namespace std;
int father[1005];
int getfather(int num)
{
while(num!=father[num])
num = father[num];
return num;
}
void myunion(int x,int y)
{
int rootx = getfather(x);
int rooty = getfather(y);
if(rootx!=rooty)father[rooty] = rootx;
}
int main()
{
int t;
int n,m;
int a,b;
int count;
// int linked[1005];
while(cin>>t)
{
while(t--)
{
count=0;
cin>>n>>m;
for(int i=1;i<=n;i++)
father[i] = i;
for(int i=1;i<=m;i++)
{
cin>>a>>b;
myunion(a,b);
}
for(int i=1;i<=n;i++)
{
if(father[i]==i)count++;
}
cout<<count<<endl;
}
}
return 0;
}
本文介绍了一道使用并查集解决社交宴请桌次问题的编程题,详细阐述了解题思路和AC代码,适用于算法与数据结构的学习。
503

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



