HDU 1213 How Many Tables(并查集)
2016-03-18 11:29
465 查看
题目链接:
HDU 1213 How Many Tables
题意:
有N位朋友,如果A朋友和B朋友认识,B朋友和C朋友认识,那么A、B、C都互相认识。互相认识的朋友坐一桌。
给出m对互相认识的朋友,问最少需要多少桌?
分析:
直接对每对互相认识的朋友合并,然后逐一将每位朋友的祖先标记下(find(i)),
然后统计有多少位朋友被标记了就是需要的最少桌子数量。
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; }
相关文章推荐
- 八数码总结
- 容纳40位数的n!值
- GitHub 优秀的 Android 开源项目
- 机器学习资源分享
- 高效分布式计算系统:Spark
- 模拟器那些
- kill命令
- PhP 基础
- 支持外部命令的shell实现(glob、strsep、fork)
- 分分钟掌握设计基本原则
- 【NOIP2012TG】 开车旅行 详解+代码
- Ibatis中的动态SQL:isNotNull,isPropertyAvailable,isNotEmpty用法
- Swift比Objective-C有什么优势?
- POJ 1611 The Suspects (并查集)
- C Function
- Swift和Objective-C的联系
- 机器学习中的数据清洗与特征处理综述
- 最近流行的MVP模式
- iOS开发之蓝牙通信
- test lab ~ triangle test by using junit and coverage