HDU 1213 How Many Tables(并查集)
来源:互联网 发布:鸡尾酒会礼仪 知乎 编辑:程序博客网 时间:2024/06/05 16:14
题目链接:
HDU 1213 How Many Tables
题意:
有N位朋友,如果A朋友和B朋友认识,B朋友和C朋友认识,那么A、B、C都互相认识。互相认识的朋友坐一桌。
给出m对互相认识的朋友,问最少需要多少桌?
分析:
直接对每对互相认识的朋友合并,然后逐一将每位朋友的祖先标记下(find(i)),
然后统计有多少位朋友被标记了就是需要的最少桌子数量。
#include <iostream>#include <cstdio>#include <cstring>#include <stack>#include <algorithm>#include <cmath>using namespace std;const int maxn = 1010;int pre[maxn], vis[maxn];int T, n, m, a, b;/*int find(int x){ return pre[x] == x ? x : pre[x] = find(pre[x]);}*/int find(int x){ int r = x; while (pre[r] != r) r = pre[r]; int i = x, j; while (pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r;}void mix(int x, int y){ int fx = find(x); int fy = find(y); if (fx != fy) { if (fy < fx) swap(fx, fy); pre[fy] = fx; }}int main(){#ifdef LOCAL freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout);#endif scanf("%d", &T); while (T--) { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) pre[i] = i; for (int i = 1; i <= m; i++) { scanf("%d%d", &a, &b); mix(a, b); } memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n; i++) vis[find(i)] = 1; int ans = 0; for (int i = 1; i <= n; i++) ans += vis[i]; printf("%d\n", ans); } return 0;}
0 0
- HDU 1213 How Many Tables(并查集)
- hdu 1213 How Many Tables(并查集练习)
- [ACM] hdu 1213 How Many Tables(并查集)
- [ACM] hdu 1213 How Many Tables(并查集)
- hdu 1213 How Many Tables(并查集学习)
- HDU-#1213 How Many Tables (并查集)
- HDU - 1213 How Many Tables (简单并查集)
- HDU 1213 How Many Tables(并查集)
- HDU 1213 How Many Tables (并查集)
- HDU 1213【】How Many Tables(并查集)
- hdu 1213 How Many Tables(并查集)
- hdu 1213 How Many Tables (并查集)
- hdu 1213 How Many Tables(并查集算法)
- HDU 1213 How Many Tables(并查集)
- HDU-1213 How Many Tables(并查集)
- HDU 1213 How Many Tables(并查集)
- HDU 1213 How Many Tables(并查集)
- HDU 1213 How Many Tables(并查集)
- Swift比Objective-C有什么优势?
- 跑spark作业,众多版本jar包管理
- 高效分布式计算系统:Spark
- 2016SDAU课程练习一 1006
- php java bridge NoSuchFieldException
- HDU 1213 How Many Tables(并查集)
- 机器学习资源分享
- Java线程中run和start方法的区别
- gif,png,jpeg,区别
- float 类型与“0值”比较
- 八数码总结
- springMVC
- centos7 配置开机自启redis
- 机房重构——七层登录