Hdu 1213-How Many Tables

这是一道关于Ignatius生日派对的问题,需要计算最少需要多少张桌子让所有朋友都能与认识的人同桌,而不与陌生人坐一起。题目给出了朋友之间的认识关系,使用并查集可以解决此问题。样例输入和输出展示了如何处理这种情况。
摘要由CSDN通过智能技术生成

题目链接:
传送门

Problem Description
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.

Input:
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.

Output:
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.

Sample Input:
2
5 3
1 2
2 3
4 5

5 1
2 5

Sample Output:
2
4

中文版本:
题目描述:
今天是Ignatius的生日,他邀请了许多朋友。现在是吃晚饭的时候,Ignatius想知道他至少需要多少张桌子。你要注意,并不是所有的朋友都互相认识,以及所有的朋友不想和陌生人呆在一起。这个问题的一个重要原则是如果我告诉你A认识B,并且B认识C,那意味着A、B、C都相互认识,所以他们能呆在一张桌上。
例如:如果我告诉你A认识B,B认识C,以及D认识E,所以A、B、C可以呆在一张桌子上,D、E必须呆在另一张桌子上,所以lgnatius至少需要2张桌子。

输入:
输入从一个整数T(1≤T≤25)开始,它表明了测试样例的数量。接着是T个测试样例。每个测试样例从两个整数N和M(1≤N、M≤1000)开始。N表示朋友的数量,朋友从1到N编号。后面有M行,每一行由两个整数A和B组成(A!=B),那意味着朋友A和朋友B之间互相认识,两个组测试样例之间会有一个空白行。

输出:
对于每个测试样例,只需要输出Ignatius至少需要多少张桌子,不要打印任何空格。

样例输入:
2
5 3
1 2
2 3
4 5

5 1
2 5

样例输出:
2
4

样例示意图:
在这里插入图片描述
在这里插入图片描述
解题思路:
本题考察了并查集的相关操作,不多赘述,上代码!

参考代码:

#include <stdio.h>

int t,n,m;
int parent[1001];

void init()
{
	int i;
	for(i=1;i<=n;i++)
	 parent[i]=i;
}

int find(int x)
{
	if(x==parent[x])
	 return x;
	else
	 return parent[x]=find(parent[x]); 
}

void Union(int a,int b)
{
	int A=find(a);
	int B=find(b);
	if(A!=B)
	 parent[A]=B;
}

int main()
{
	int i,a,b,count;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m); 
		init();
		count=0;
		
		for(i=0;i<m;i++)
		{
			scanf("%d%d",&a,&b);
			Union(a,b);
		}
		
		for(i=1;i<=n;i++)
		{
			if(parent[i]==i)
			 count++;
		}
		
		printf("%d\n",count);
	}
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值