Friend(并查集)

描述:

There are some people traveling together. Some of them are friends. The friend relation is transitive, that is, if A and B are friends, B and C are friends, then A and C will become friends too.These people are planning to book some rooms in the hotel. But every one of them doesn't want to live with strangers, that is, if A and D are not friends, they can't live in the same room.Given the information about these people, can you determine how many rooms they have to book at least? You can assume that the rooms are large enough.


输入:

The first line of the input is the number of test cases, and then some test cases followed.

The first line of each test case contain two integers N and M, indicating the number of people and the number of the relationship between them. Each line of the following M lines contain two numbers A and B (1 ≤ A ≤ N , 1 ≤ B ≤ N , A ≠ B), indicating that A and B are friends.

You can assume 1 ≤ N ≤ 100, 0 ≤ M ≤ N * (N-1) / 2. All the people are numbered from 1 to N.



输出:

Output one line for each test case, indicating the minimum number of rooms they have to book.



样例输入:

3
5 3
1 2
2 3
4 5
5 4
1 2
2 3
3 4
4 5
10 0


样例输出:

2

1

10



题目大意:

一群人住酒店,规定A是B的朋友B是C的朋友则A也是C的朋友。一群人只有朋友和陌生人的关系。陌生人不能住在一起问最少要开几间房。



/*
并查集模板题 */
#include<stdio.h>
#include<algorithm>
using namespace std;
int city[105];
int find(int x)
{
	return city[x]==x?x:find(city[x]);						//判断任意两个人是否为朋友关系(即判断祖先是否相同) 
}
void join(int a,int b)
{
	int r1,r2;
	r1=find(a);
	r2=find(b);
	if(r1!=r2)												
	city[r1]=r2;
}
int main()
{
	int n,m,x,y,t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %d",&n,&m);
		for(int i=0;i<=n;i++)							 //初始化,初始化后每一个元素的父节点是它本身 
		{
			city[i]=i;
		}
		for(int i=0;i<m;i++)
		{
			scanf("%d %d",&x,&y);
			join(x,y);                                    //连接朋友关系(即指向同一祖先)						
		}
		int count=0;
		for(int i=1;i<=n;i++)							//计算不同祖先的数量 
		{
			if(city[i]==i)
			count++;
		}
		printf("%d\n",count);
	}
	return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值