POJ 1988 Cube Stacking
2016-07-13 15:10
260 查看
题目分析
典型的带权并查集,这道题有2个操作,一个是将带a的那一堆石头移到带b的那一堆石头上面,另一个是询问a号石头下面有多少石头。这里我定义了3个数组,fa用于查父节点,he查编号为i的石头下面有多少石头,sum表示以a为根节点的石头堆中有多少石头。#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int maxn = 30005; int sum[maxn],he[maxn],fa[maxn]; //sum表示这堆石头有多少个,he表示 void init(){ for(int i = 0; i < maxn; i++){ sum[i] = 1; he[i] = 0; fa[i] = i; } } int Find(int x){ if(x == fa[x]) return fa[x]; int temp = Find(fa[x]); he[x] += he[fa[x]]; fa[x] = temp; return fa[x]; } int main() { int P; scanf("%d", &P); char op; int x,y; init(); while(P--){ cin >> op; if(op == 'M') { scanf("%d%d", &x, &y); int xx = Find(x); int yy = Find(y); he[xx] = sum[yy]; sum[yy] += sum[xx]; fa[xx] = yy; }else{ scanf("%d", &x); Find(x); printf("%d\n", he[x]); } } return 0; }
相关文章推荐
- Swift - 各种手势检测大全(UIGestureRecognizer及其子类)
- 有一个做饭好吃的妈妈是一种什么体验?
- cos和sin的傅立叶变换
- Java-BubbleSort
- 【转】phpstorm+Xdebug断点调试PHP
- ST_SRID
- cc2541从机向主机传大数据
- 约瑟夫问题I
- 大数据技术Hadoop面试题,看看你能答对多少?
- DockerJava+Tomcat环境搭建
- 如何使用Git上传项目代码到github
- [leetcode]95. Unique Binary Search Trees II
- Swift - 触摸事件(点击,移动,抬起等)说明及用例
- 长期后台运行 Service
- 瀑布流布局
- Android面试之JVM
- Yum本地Rpm库设置
- 关于hg的命令
- PrintStream打印流
- 安卓传递对象之Serializable