链接:https://vjudge.net/contest/66964#problem/C
题目
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.
题意
小I的生日会上邀请了很多朋友,但是为了倡导不铺张浪费的环保精神,小I准备将餐桌数降到最少。
一张桌子上的人必须互相认识才可以。如果A认识B,B认识C,那么A与C也认识。
现在小I求助你,帮助他算出最少放几张桌子就可以。
思路
并查集模板题,所以就直接上代码了。
伊丽莎白!
代码
#include<bits/stdc++.h>
using namespace std;
int fa[1050];
int findf(int n)
{
if(fa[n]==n)
return n;
else
return fa[n]=findf(fa[n]);
}
int main()
{
int T,n,m,x,y;
cin>>T;
while(T--)
{
int cnt=0;
cin>>n>>m;
for(int i=1;i<=n;i++)
fa[i]=i;
for(int i=1;i<=m;i++)
{
cin>>x>>y;
if(findf(x)!=findf(y))
{
fa[findf(y)]=findf(x);
}
}
for(int i=1;i<=n;i++)
if(fa[i]==i)
cnt++;
cout<<cnt<<endl;
}
}
每日一道题,开心~~