Friend(并查集)

来源:互联网 发布:oracl数据库 编辑:程序博客网 时间:2024/06/11 02:39

描述:

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


原创粉丝点击