HDU 2818 Building Block 加权并查集
2016-05-08 18:45
435 查看
Building Block
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768K (Java/Others)
Total Submission(s): 4548 Accepted Submission(s): 1408
Problem Description
John are playing with blocks. There are N blocks (1 <= N <= 30000) numbered 1...N。Initially, there are N piles, and each pile contains one block. Then John do some operations P times (1 <= P <= 1000000). There are two kinds of operation:
M X Y : Put the whole pile containing block X up to the pile containing Y. If X and Y are in the same pile, just ignore this command.
C X : Count the number of blocks under block X
You are request to find out the output for each C operation.
Input
The first line contains integer P. Then P lines follow, each of which contain an operation describe above.
Output
Output the count for each C operations in one line.
Sample Input
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4
Sample Output
1
0
2
Source
2009 Multi-University Training Contest 1 - Host
by TJU
Recommend
gaojie | We have carefully selected several similar problems for you: 2819 2824 2821 2820 2822
点击打开题目链接
有N个砖头,编号为1~N。有两种操作, 第一种是M x y, 把 x 所在的那一堆砖头全部移动放到 y 所在的那堆上面。 第二种操作是C x, 即查询 x 下面有多少个砖头。
带权并查集的应用, 用 Num[ x ] 来表示以 x 为根的这棵树的节点总数(x 必须是根,没有父亲节点), Under[ x ] 数组来表示 x 砖头下面有多少个砖头。
如果把a堆砖放到b堆砖上面, 那么a堆最底面那个砖头root_a的下面原本是有0个砖头的, 搬过去之后,变成了有 b 堆砖的数量个。然后root_a之上的数量便根据root_a的值进行更新。更新的步骤在查找时路径压缩的那一步进行。
#include <cstdio>
#include <iostream>
using namespace std;
const int MAXN = 30000 + 10;
int Fa[MAXN], Under[MAXN], Num[MAXN];
void Init()
{
for (int i = 0; i < MAXN; i++)
{
Fa[i] = i; //初始化并查集,自成一个连通分量
Num[i] = 1; //i是根节点,初始化以它为根的树共有1个节点
}
}
int Find(int x)
{
if (x == Fa[x]) return x;
int fa = Fa[x];
Fa[x] = Find(Fa[x]); //递归查找老祖宗
Under[x] += Under[fa]; //加上父亲的
return Fa[x];
}
void Union(int x, int y)
{
int tx = Find(x), ty = Find(y); //先查找两者的祖先
if (tx == ty) return;
Fa[tx] = ty; //合并
Under[tx] = Num[ty]; //tx下面多了Num[ty]个
Num[ty] += Num[tx]; //以ty为根的树多了Num[tx]个节点
Num[tx] = 0; //以tx为根的树没有结点(此时tx已经不是一个树的真正根节点)
}
int main()
{
int t, x, y;
char cmd[10];
Init();
scanf("%d", &t);
while (t--)
{
scanf("%s", cmd);
if (cmd[0] == 'C')
{
scanf("%d", &x);
Find(x);
printf("%d\n", Under[x]);
}
else
{
scanf("%d%d", &x, &y);
Union(x, y);
}
}
return 0;
}
相关文章推荐
- 简单的四则运算
- 数的奇偶性
- ACMer博客瀑布流分析
- ACM程序设计大赛题目分类
- 计算字符串最后一个单词长度
- ACM网址
- 1272 小希的迷宫
- 1272 小希的迷宫
- hdu 1250 大数相加并用数组储存
- 矩阵的乘法操作
- 蚂蚁爬行问题
- 蚂蚁爬行问题
- 求两个数的最大公约数【ACM基础题】
- 打印出二进制中所有1的位置
- 杭电题目---一只小蜜蜂
- HDOJ 1002 A + B Problem II (Big Numbers Addition)
- 初学ACM - 半数集(Half Set)问题 NOJ 1010 / FOJ 1207
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1002
- 1611:The Suspects