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
题解
知识点:并查集。
一道典型的带权并查集题。我们用栈底方块作为根节点,权值代表到栈底(根节点)有多少个方块。但还有个问题,两个栈合并时我们并不知道合并到底部的栈有多少个方块,该给被合并的栈的根节点多少权值,于是我们可以用另一个权值数组,或者直接用原来的根节点权值代表这个栈有多少方块,这样合并时候就能直到给根节点赋值多少了。
带权并查集的路径压缩和合并操作都能用向量理解。
首先是路径压缩,已知 到父节点 的权值,即 下面到 有多少方块,以及 到根节点的权值,那么 到根节点的权值就是 到父节点 的权值加上 到根节点的权值,即 。这样递归实现即可,先解决 到根节点的权值问题,再解决 到根节点的权值问题。
其次是合并操作,我们要把栈 放在栈 之上,那么 权就为 方块数加上 的方块数, 权就为 的方块数,即 , 。这里因为根节点的权值与其他节点意义不同,没有体现向量解释的妙qwq。
时间复杂度
空间复杂度
代码
#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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧