您的位置:首页 > 其它

HDU 1213 How Many Tables (并查集)

2018-01-26 15:14 239 查看
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
[align=left]in the other one. So Ignatius needs 2 tables at least.[/align]
[align=left]
[/align]

[align=left]Input[/align]
[align=left]
[/align]
[align=left]The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T[/align]
[align=left]test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the
[/align]
[align=left]number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two[/align]
[align=left]integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line
[/align]
[align=left]between two cases.[/align]
[align=left]
[/align]
[align=left]Output[/align]
[align=left]
[/align]
[align=left]
[/align]
[align=left]For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.[/align]
[align=left]
[/align]

Sample Input

2
5 3
1 2
2 3
4 5

5 1
2 5


Sample Output

2
4


   

并查集的很基础的应用  查找合并

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<queue>
#include<map>
#include<algorithm>
#include<iostream>
#define ll long long
#define ull unsigned long long
const int N=1e9+7;
const int M=1005;

int f[M],c[M],t,i;

void init()  //初始化
{
memset(c,0,sizeof(c)),t=0;
for(i=1; i<M; i++) f[i]=i;
}

int find(int x)  //查找
{
if(x!=f[x]) f[x]=find(f[x]);
return f[x];
}

int main()
{
int T,n,k,a,b,m;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
init();
for(i=0; i<m; i++)
{
scanf("%d%d",&a,&b);
if(find(a)!=find(b))   f[find(a)]=find(b); //合并
}
for(i=1; i<=n; i++)  c[find(i)]=1;
for(i=1; i<=n; i++) if(c[i]==1) t++;  //查根的数量
printf("%d\n",t);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  并查集