Friends(并查集)
来源:互联网 发布:业务管理系统 源码 编辑:程序博客网 时间:2024/05/16 23:41
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.
input
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
Output one line for each test case, indicating the minimum number of rooms they have to book.
sample input5 3
1 2
2 3
4 5
5 4
1 2
2 3
3 4
4 5
10 0
sample output
2
1
10
Hint
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.
#include<cstdio>#include<algorithm>#include<cstring>#include<cmath>using namespace std;int arr[105];int find(int x){return arr[x]==x?x:find(arr[x]);}void merge(int a,int b){int r1,r2;r1=find(a);r2=find(b);if(r1!=r2)arr[r1]=r2;}int main(){int n,m,x,y,t,cnt;scanf("%d",&t);while(t--){scanf("%d %d",&n,&m);for(int i=0;i<=n;i++){arr[i]=i;}for(int i=0;i<m;i++){scanf("%d %d",&x,&y);merge(x,y);}cnt=0;for(int i=1;i<=n;i++){if(arr[i]==i)cnt++;}printf("%d\n",cnt);}}
- Friends(并查集)
- Friends(并查集)
- Friends--并查集
- uva 10608 - Friends(并查集)
- uva 10608 - Friends (并查集)
- UVa 10608 - Friends(并查集)
- UVA - 10608-Friends(并查集)
- UVa 10608 - Friends(并查集)
- uva 10608 Friends(并查集)
- UVA---10608-Friends(并查集)
- Virtual Friends (并查集)
- Friends+uva+并查集
- (并查集)B - Friends(8.4.1)
- HDU 3172 Virtual Friends(并查集)
- HDU 3172 Virtual Friends(带权并查集)
- hdu-3172 Virtual Friends(并查集+容器)
- HDOJ 3172 Virtual Friends(并查集 + STL)
- TOJ 2469.Friends(并查集基础题目)
- 资讯精选 | 想感受“新零售”的未来吗?请看这四个案例!
- angular2学习笔记 2
- 关于 python cls 笔记
- 三级联动,面向过程与面向对象方法
- 正则表达式进阶
- Friends(并查集)
- UML 之 顺序图(Sequence Diagram)
- 动态规划之走台阶问题
- 模板与泛型编程
- JSON在线编缉器命令行工具-解放你的双手
- css优先级 中文版MDN补充翻译
- Hibernate-------<1>初步学习
- 接口自动化之DataUtilPractice 类数据验证
- 多项式加法(10分)