Capricorn's Trial G题

网站:https://vjudge.net/contest/279641#problem/G
题目: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
问题简述:将认识的人放在一座。共有多少座。

#pragma warning(disable:4996)
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
bool vis[1005], lj[1005][1005];
int n, m;
void dfs(int start)
{
	vis[start] = false;//此时将被分组的客人设置为不存在。
	for (int i = 1; i <= n; i++)//在可能存在的客人里面寻找
	{
		if (vis[i] && lj[start][i])//如果被分组的客人和没被分组的客人认识。那么就分到同一组。不认识的话就找下一位。
		{
			vis[i] = false;//将这名客人设置为不存在。
			dfs(i);//然后再用这名客人递归寻找这名客人认识的人。
					}
	}
}
int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		int a, b, cnt = 0;
		memset(vis, true, sizeof(vis));//先将可能的客人设置为存在。
		memset(lj, false, sizeof(lj));//先将所有的关系设置为不存在。
		scanf("%d%d", &n, &m);
		for (int i = 1; i <= m; i++)
		{
			scanf("%d%d", &a, &b);
			lj[a][b] = lj[b][a] = true;//输入关系,将关系设置为存在
		}
		for (int j = 1; j <= n; j++)
		{
			if (vis[j])//从每一个没有被安排的客人开始
			{
				//printf("%d\n",j);
				cnt++;//有一个没有被安排的就分成一组。然后用DFS算法将又关系的人分到同一组。
				dfs(j);
			}
		}
		printf("%d\n", cnt);
	}
	return 0;
}

代码借鉴whiskey_wei

猜你喜欢

转载自blog.csdn.net/weixin_43508349/article/details/86663478