题目:POJ 1988 Cube Stacking(带权并查集)

版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/88361863

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

看其他人的题解,还不是很明白这道题的代码是怎么个意思,只是大体上感觉可以。
在find函数那里就卡了一个小时,应该是每次递归找自己的上面的一个箱子,找到最后,在回溯的过程中更新自己的deep值。
在就是合并两堆箱子,如果不在一堆上,让x所在堆放到y所在堆,这样y的deep值就从0变成了一开始x所在堆的总数,然后x作为新堆的最上面的箱子,它的deep还是0,sum值就变成原先x堆的总数加上y堆的总数。

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

int father[30005], sum[30005], deep[30005];
//最终的根节点是最上面的箱子编号 
//deep[i]是i箱子上箱子的个数, sum[i]为i箱子所在堆总数 
int find(int x)
{
	int tmp;
	if (x==father[x])
		return x;
	tmp=father[x];
	father[x]=find(tmp);
	deep[x]+=deep[tmp];
	return father[x];
}
int main()
{
	int T;
	char str[3];
	for (int i=1; i<=30005; i++){
		father[i]=i;
		sum[i]=1;
		deep[i]=0;
	}
	scanf("%d", &T);
	for (int i=1; i<=T; i++){
		scanf("%s", str);
		if (str[0]=='M'){
			int x, y;
			scanf("%d%d", &x, &y);
			int fx=find(x);
			int fy=find(y);
			if (fx!=fy){
				father[fy]=fx;//把x所在堆放到y所在堆上 
				deep[fy]=sum[fx];
				sum[fx]+=sum[fy];
			}
		}else
		{
			int x;
			scanf("%d", &x);
			printf("%d\n", sum[find(x)]-deep[x]-1);
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42172261/article/details/88361863