Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.
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.
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<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int par[100];
void init(int n)
{
for(int i=1;i<=n;i++)
par[i]=i;
}
int find(int x)//寻找根节点,路径压缩
{
if(x!=par[x])
par[x]= find(par[x]);
return pa[x];
}
void unite(int a,int b)//判断是否连通
{
int fa=find(a);
int fb=find(b);
if(fa!=fb)
par[fa]=fb;
}
int main()
{int n,m,a,b,i,t;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
int tmp=0;
init(n);
scanf("%d",&m);
while(m--)
{
scanf("%d%d",&a,&b);
unite(a,b);
}
for(i=1;i<=n;i++) //确定连通分量个数;
{
if(par[i]==i)
tmp++;
}
printf("%d\n",tmp);
}
return 0;
}
本文介绍了一个关于如何计算最少需要多少张桌子来安排不同群体朋友的算法问题。该问题通过构建并查集数据结构来解决,确保认识的朋友能够坐在同一张桌子上。
638

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



