How Many Tables ( 并 查 集 解 法 )

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

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

扫描二维码关注公众号,回复: 5042612 查看本文章

Sample Output

2
4

Author

Ignatius.L

Source

杭电ACM省赛集训队选拔赛之热身赛

个人回想:
前一个博客正在写并查集,第二次acm的周赛就遇到了并查集,这一题毫无疑问我把上一篇博客的find()函数码下来了,如果不理解并查集的话,记下来也行,不过能理解最好,与上一篇blog一样的,先把主函数弄完,考虑桌子数先等于人数,然后在主函数的判断过后再进行减法就可以得出需要的桌子数了,先在主函数里加入find()函数,目的适用于寻找每个人的boss(记得要先把每个人的boss初始化为他们自己)(可以利用头文件为#include< cstring >的库函数memset(pre,0,sizeof(pre))给pre [ i ]函数赋初始0值),脑子里先想好这个find()函数是干嘛的,然后把主函数给弄完,大体结构就搞定啦,然后就去想一想find()函数要怎么弄。find()函数是为了找到每个人的boss,而在主函数里是先把每个人的boss初始化为自己后,再输入谁认识谁的,这样输入的两个互相认识的人,第一组数据里大家的boss都是自己,所以只要随便把其中一个人的boss改为自己就行了,第二组数据就在第一组数据的数据下去找第二组数据的boss,然后判断两者的boss是否一样,如果一样就桌子数减一,否就跳过就行了,剩下的依此类推。看不懂的可以看一下我上一篇blog或者看一下一个有意思的并查集详解如果看不懂也没有关系,加油搞懂就行了,加油!

VS通过的代码如下:

#include <iostream>
using namespace std;
int pre[1000];

int find(int x)
{
	int r = x;
	while (pre[r] != r)
	{
		r = pre[r];
	}
	return r;
}
int main()
{
	int T, N, M, a, b;
	scanf_s("%d\n", &T);
	while (T--)
	{
		scanf_s("%d %d", &N, &M);
        int table = N;
		
		for (int i = 1;i <= N;i++)
		{
			pre[i] = i;
		}
		while (M--)
		{
			scanf_s("%d %d", &a, &b);
			int f1 = find(a);
			int f2 = find(b);
			if (f1 != f2)
			{
				pre[f1] = f2;
				table--;
			}
		}    
		cout << table << endl;
	}
}

Status
Accepted
Time
31ms
Memory
1796kB
Length
503
Lang
C++
Submitted
2018-12-16 15:43:26
RemoteRunId
27651446

猜你喜欢

转载自blog.csdn.net/weixin_43697280/article/details/85037919