您的位置:首页 > 其它

杭电 hdu 1213 How Many Tables(经典并查集 基础题)

2015-07-13 09:28 357 查看
杭电 hdu 1213  How ManyTables(经典并查集   基础题)

How Many Tables

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 17488    Accepted Submission(s): 8582


[align=left]Problem Description[/align]
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.

 

[align=left]Input[/align]
The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked
from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.

 

[align=left]Output[/align]
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.

 

[align=left]Sample Input[/align]

2
5 3
1 2
2 3
4 5

5 1
2 5

 

[align=left]Sample Output[/align]

2
4

 

[align=left]Author[/align]
Ignatius.L
 

[align=left]Source[/align]
杭电ACM省赛集训队选拔赛之热身赛

 

[align=left]Recommend[/align]
Eddy
 

题意:Ignatius要开生日聚会,邀请了很多朋友来参加,于是要准备桌子,要求就是认识的朋友之间坐一张桌子,他会给出两个朋友A和B,表明

A和B认识,如果A认识B,B认识C,那么A,B,C就坐在一起,要是A认识B,B认识C,D认识E,那么就要准备两张桌子,一张给A,B,C一张给D,E

最后问总共要准备多少张桌子

题解:用并查集来做,将朋友放在一棵树上,也就是有相同的根结点),最后就是有几棵树,也就是几张桌子。
由于题目会更新父亲结点,所以只要father[x] == x,就表明这是根结点,而一棵树只有一个根结点,所以找有多少个根结点就好了

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

#define maxn 10000

int father[maxn];

void Init (int n) //赋初值,将每一个点都当做是一棵树,等认定为朋友时在合并树
{
int i;

for (i = 1; i <= n; ++i)
father[i] = i; //这只是一种普遍的赋初值
}

int Find (int x) //寻找这个点所在的树的根结点
{
int rt = x;

if (father[x] != x)
{
rt = Find (father[x]);
father[x] = rt; //剪枝,使时间减少,不断更新父亲结点,让它靠近根结点,减少递归
}
return rt;
}

void Union (int a, int b)
{
int fa = Find (a);
int fb = Find (b);

if (fa != fb) //合并是朋友的两个结点所在的树
father[fa] = fb;
}

int main()
{
int T, n, m, i, a, b;

scanf ("%d", &T);
while (T--)
{
scanf ("%d%d", &n, &m);
Init (n);
for (i = 0; i < m; ++i)
{
scanf ("%d%d", &a, &b);
Union (a, b);
}
int cnt = 0;
for (i = 1; i <= n; ++i) //查找有多少个根结点,也就是多少棵树
{
if (father[i] == i)
cnt++;
}
printf ("%d\n", cnt);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  杭电