HDU 1213 How Many Tables (并查集)
2016-07-23 16:50
513 查看
How Many Tables
题目链接:
http://acm.hust.edu.cn/vjudge/contest/123393#problem/CDescription
Today is Ignatius' birthday. He invites a lot of friends. Now it's dinner time. Ignatius wants to know how many tables he needs at least. You have to notice that not all the friends know each other, and all the friends do not want to stay with strangers.One important rule for this problem is that if I tell you A knows B, and B knows C, that means A, B, C know each other, so they can stay in one table.
For example: If I tell you A knows B, B knows C, and D knows E, so A, B, C can stay in one table, and D, E have to stay in the other one. So Ignatius needs 2 tables at least.
Input
The input starts with an integer T(1<=T<=25) which indicate the number of test cases. Then T test cases follow. Each test case starts with two integers N and M(1<=N,M<=1000). N indicates the number of friends, the friends are marked from 1 to N. Then M lines follow. Each line consists of two integers A and B(A!=B), that means friend A and friend B know each other. There will be a blank line between two cases.Output
For each test case, just output how many tables Ignatius needs at least. Do NOT print any blanks.Sample Input
25 3
1 2
2 3
4 5
5 1
2 5
Sample Output
24
题意:
n个人参加晚宴;完全不认识的两个人不能被分配在同一餐桌;
认识具有传递性:A认识B B认识C,那么A和C也认识.
题解:
很明显的并查集模版题.将认识两个人合并到同一集合;
最后统计有多少个不同的集合即可;
注意:部分编译器不允许变量名与关键字冲突;故注意next和rank这些关键字,以免CE.
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <queue> #include <map> #include <set> #include <vector> #define LL long long #define eps 1e-8 #define maxn 1100 #define inf 0x3f3f3f3f #define IN freopen("in.txt","r",stdin); using namespace std; int fa[maxn]; int _rank[maxn]; void init_set() { for(int i=0; i<maxn; i++) { fa[i] = i; _rank[i] = 0; } } int find_set(int x) { return fa[x] = (x==fa[x]? x:find_set(fa[x])); } void unit_set(int x, int y) { x = find_set(x); y = find_set(y); if(_rank[x] < _rank[y]) swap(x, y); fa[y] = x; if(_rank[x] == _rank[y]) _rank[x]++; } int n, m; int main(int argc, char const *argv[]) { //IN; int t; cin >> t; while(t--) { cin >> n >> m; init_set(); while(m--) { int x,y; scanf("%d %d", &x, &y); unit_set(x,y); } int cnt = 0; bool ans[maxn] = {0}; for(int i=1; i<=n; i++) { ans[find_set(i)] = 1; } for(int i=1; i<=n; i++) if(ans[i]) cnt++; printf("%d\n", cnt); } return 0; }
相关文章推荐
- 1018. 锤子剪刀布 (20)--刷题记录
- linux入门
- Weka和Mulan的介绍和理解
- 修改实现自动审核织梦DedeCMS会员发表的最新文章
- MFC中的RTTI(Runtime Type Identification, 运行时类型识别)详解(参考《深入浅出MFC》)
- 奶牛锻炼
- MFC消息映射机制实现
- 我的书单
- 我眼中BA(业务需求分析师)的技能广度和深度
- @Transactional spring 配置事务 注意事项
- 2016夏季练习——最小生成树
- phpstrom + ideavim 详细配置
- oop 连连看游戏
- 16.7.23
- Java基础之 原码、反码、补码
- "su"命令和"su -"的不同之处
- Codeforces Round #364 (Div. 2) D. As Fast As Possible
- scp免密码传送文件
- 排名(sort结构体)
- 【POJ 3040】Allowance