How Many Tables——有多少张桌子

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

描述:

今天是伊格纳提的生日。他邀请了很多朋友。现在是晚餐时间。伊格纳提想知道他至少需要多少张桌子。你要注意,不是所有的朋友都认识对方,所有的朋友都不想和陌生人在一起。
这个问题的一个重要规则是,如果我告诉你a知道b,b知道c,这意味着a,b,c知道对方,所以他们可以留在一个表里。
例如:如果我告诉你a知道b,b知道c,d知道e,所以a,b,c可以留在一个表中,d,e必须留在另一个表中。所以伊格纳提至少需要两张桌子。

输入:

输入以整数t开头(1<=T<=25)显示了测试用例的数量。然后测试情况。每个测试用两个整数n和m开始(1<=n,m>=1000)。n表示朋友的数目,朋友的标记是从1到n。然后,M线跟随。每一行由两个整数a和b组成(a!=b)。意思是朋友甲和朋友乙互相认识。两个案子之间会有一条空格。

输出:


对于每个测试用例,只输出至少需要多少表。不要打印任何空白。

AC码:

#include<iostream>
#include<cstdio>
using namespace std;
int n,m;
int f[1001];
void init()
{//先没人一张桌子,给桌子进行编号,桌子的标号就是这个人的序号 
	for(int i=1;i<=n;i++)
	{
		f[i]=i;
	}
 } 
 int getf(int x)
 {//如果两个人不认识 
 	if(f[x]!=x)
 	f[x]=getf(f[x]);
 	return f[x];
 }
int merge(int x,int y)
{
	f[getf(y)]=getf(x);
	return f[getf(y)];
}
int main()
{
	int T,x,y,c;
	scanf("%d",&T);
	while(T--)
	{
		c=0;
		scanf("%d %d",&n,&m);//n个人,m个关系 
		init();
		for(int i=1;i<=m;i++)
		{
			scanf("%d %d",&x,&y);//x和y有关系 
			merge(x,y);
		}
		for(int i=1;i<=n;i++)
		{
			if(f[i]==i)
			c++;
		}
		printf("%d\n",c);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/hanyue0102/article/details/81624076