并查集简单题
2015-07-29 23:45
459 查看
The Suspects
题目传送:POJ-1611-The SuspectsAC代码:
[code]#include <map> #include <set> #include <cmath> #include <deque> #include <queue> #include <stack> #include <cstdio> #include <cctype> #include <string> #include <vector> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #define LL long long #define INF 0x7fffffff using namespace std; int n, m; const int maxn = 30005; int pa[maxn]; int tot[maxn];//记录当前集合的总数 int find(int x) { return pa[x] == x ? x : pa[x] = find(pa[x]);//带路径压缩 } void link(int x, int y) { int px = find(x); int py = find(y); if(px == py) return; pa[px] = py; tot[py] += tot[px]; } int main() { while(scanf("%d %d", &n, &m) != EOF) { if(n == 0 && m == 0) break; for(int i = 0; i <= n; i ++) { pa[i] = i; tot[i] = 1; } int k, h, s; for(int i = 0; i < m; i ++) { scanf("%d", &k); scanf("%d", &h); for(int j = 1; j < k; j ++) { scanf("%d", &s); link(h, s); } } printf("%d\n", tot[find(0)]); } return 0; }
Cube Stacking
题目传送:POJ - 1988 - Cube StackingAC代码:
[code]#include <map> #include <set> #include <cmath> #include <deque> #include <queue> #include <stack> #include <cstdio> #include <cctype> #include <string> #include <vector> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #define LL long long #define INF 0x7fffffff using namespace std; const int maxn = 30005; int pa[maxn]; int under[maxn]; int sum[maxn]; int p; int find(int x) { if(x == pa[x]) { return x; } int t = find(pa[x]); under[x] += under[pa[x]];//路径压缩的时候要更新under数组,且这个数组只能放这里,因为要先更新祖先 pa[x] = t; return pa[x]; } void link(int x, int y) {//把x所在的堆放到y所在的堆上 int px = find(x); int py = find(y); if(px == py) { return; } pa[px] = py; under[px] = sum[py];//将下面那个堆的总数更新到上面那个堆的根 sum[py] += sum[px];//计算现在这个堆的总数,不能和上面那个位置互换 } int main() { while(scanf("%d", &p) != EOF) { for(int i = 0; i < maxn; i ++) { pa[i] = i; under[i] = 0; sum[i] = 1; } char op[15]; int a, b; for(int i = 0; i < p; i ++) { scanf("%s", op); if(op[0] == 'M') { scanf("%d %d", &a, &b); link(a, b); } else { scanf("%d", &a); find(a); printf("%d\n", under[a]); } } } return 0; }
相关文章推荐
- 整数转化为整数字符串
- 关于ios开发中的分模块开发
- Single Number
- 7.29学习
- js 四种函数调用模式
- Java关键字final、static使用总结
- 《一起学》系列
- 快速幂(C语言实现) 超详细
- 技术积累
- 解开Android应用程序组件Activity的"singleTask"之谜
- Java学习--(四)新的数据类型:类(class);field,method
- 数据库相关(2)
- 【LeetCode】228 - Summary Ranges
- 学习心得三
- pagerAdapter的不同使用方法
- HDOJ Attack 4031【树状数组】
- ThinkPHP的缓存 F方法
- JDK之jstat的用法
- python 项目 Memory game
- Linux环境编程资源总结