POJ1988 Cube Stacking
题目
Description
Farmer John and Betsy are playing a game with N (1 <= N <= 30,000)identical cubes labeled 1 through N. They start with N stacks, each containing a single cube. Farmer John asks Betsy to perform P (1<= P <= 100,000) operation. There are two types of operations:
moves and counts.
* In a move operation, Farmer John asks Bessie to move the stack containing cube X on top of the stack containing cube Y.
* In a count operation, Farmer John asks Bessie to count the number of cubes on the stack with cube X that are under the cube X and report that value.
Write a program that can verify the results of the game.
Input
* Line 1: A single integer, P
* Lines 2..P+1: Each of these lines describes a legal operation. Line 2 describes the first operation, etc. Each line begins with a 'M' for a move operation or a 'C' for a count operation. For move operations, the line also contains two integers: X and Y.For count operations, the line also contains a single integer: X.
Note that the value for N does not appear in the input file. No move operation will request a move a stack onto itself.
Output
Print the output from each of the count operations in the same order as the input file.
Sample Input
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4
Sample Output
1
0
2
Source
题解
知识点:并查集。
一道典型的带权并查集题。我们用栈底方块作为根节点,权值代表到栈底(根节点)有多少个方块。但还有个问题,两个栈合并时我们并不知道合并到底部的栈有多少个方块,该给被合并的栈的根节点多少权值,于是我们可以用另一个权值数组,或者直接用原来的根节点权值代表这个栈有多少方块,这样合并时候就能直到给根节点赋值多少了。
带权并查集的路径压缩和合并操作都能用向量理解。
首先是路径压缩,已知 \(A\) 到父节点 \(B\) 的权值,即 \(A\) 下面到 \(B\) 有多少方块,以及 \(B\) 到根节点的权值,那么 \(A\) 到根节点的权值就是 \(A\) 到父节点 \(B\) 的权值加上 \(B\) 到根节点的权值,即 \(\vec{AB} + \vec{BR} = \vec{AR}\)。这样递归实现即可,先解决 \(B\) 到根节点的权值问题,再解决 \(A\) 到根节点的权值问题。
其次是合并操作,我们要把栈 \(A\) 放在栈 \(B\) 之上,那么 \(B\) 权就为 \(A\) 方块数加上 \(B\) 的方块数,\(A\) 权就为 \(B\) 的方块数,即 \(\vec{AB} = |B|\) ,\(|B| = |A|+|B|\) 。这里因为根节点的权值与其他节点意义不同,没有体现向量解释的妙qwq。
时间复杂度 \(O(P\log N + N)\)
空间复杂度 \(O(N)\)
代码
#include <bits/stdc++.h>
using namespace std;
int fa[30007], a[30007];
int find(int x) {
if (fa[x] == x) return x; ///返回根节点
int pre = fa[x];///保存原父节点
fa[x] = find(fa[x]);///更新原父节点到根节点的距离,更新父节点为根节点
if (pre != fa[pre]) a[x] += a[pre];///原父节点不是根节点,则距离为原父节点到根节点距离加自身到原父节点距离
return fa[x];///返回根节点
}
///根节点栈底元素,权值表示整个栈元素个数
///其他节点表示非栈底元素,权值表示到父节点的距离
///当然也可以把距离和栈大小分开成两个数组,而不是合并在一个权值里,会方便一点
int main() {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
for (int i = 1;i <= 30000;i++) a[i] = 1, fa[i] = i;
int p;
cin >> p;
while (p--) {
char op;
cin >> op;
if (op == 'M') {
int x, y;
cin >> x >> y;
int rx = find(x);
int ry = find(y);
fa[rx] = ry;///x根的父更新为y根
int t = a[ry];///y权 = 原x权+原y权,x权 = 原y权
a[ry] += a[rx];
a[rx] = t;
}
else if (op == 'C') {
int x;
cin >> x;
cout << (find(x) == x ? 0 : a[x]) << '\n'; ///距离在查之前要更新的,因为不知道这条路径是否查询过
}
}
return 0;
}
本文来自博客园,作者:空白菌,转载请注明原文链接:https://www.cnblogs.com/BlankYang/p/16463352.html

浙公网安备 33010602011771号