1501 friends (并查集基本题 by(tzc1329020023))

1501 Friends


描述
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
提示
In the first sample test case, there are 5 people. We see that 1,2,3 can live in a room, while 4,5 can live in another room. So the answer should be 2. Please note even though 1 and 3 are not "direct" friends, but they are both 2's friends, so 1 and 3 are friends too.
In the second sample test case, there are 5 people, any two of them will become friends. So they can live in one room.
In the third sample test case, there are 10 people and no friend relationship between them. No two people can live the same room. They have to book 10 rooms.

题目上传者

crq






AC代码:

#include<stdio.h>
#include<string.h>
int f[101];
int find(int x)
{
	int r = x;
	while(f[r] != r)
		r = f[r];
	return r;
}
void merge(int x, int y)
{
	int fa,fb;
	fa = find(x);
	fb = find(y);
	if(fa != fb)
		f[fa] = fb;//判断两个元素是否属于同一集合,只要看他们所在集合的祖先是否相同即可
}
int main()
{
	int test,i,n,m,j,k,a,b,ans;
	scanf("%d",&test);
	while(test--)
	{
		scanf("%d%d",&n,&m);//n为friends,朋友数。 m为关系数
		for(i = 0; i <= n; i++)
			f[i] = i; //初始化,初始化后每一个元素的父节点是它本身
		ans = 0;
		for(i = 0; i < m; i++)
		{
			scanf("%d%d",&a,&b);
			merge(a,b);//合并
		}
		for(i = 1; i <= n; i++)
		{
			if(f[i] == i)
			ans++;//计数
		}
		printf("%d\n",ans);
	}
}
 

















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值