Building Block
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (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.
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
Recommend
有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;
}