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;
} 


發佈了31 篇原創文章 · 獲贊 27 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章