POJ 1988 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

Solution

题目大意:给你30000个方块,一开始它们排成一排,高度为1。每次你可以将一个方块所在的竖列放到另一个方块所在的竖列上(M操作)或者询问一个方块下面有多少个方块(C操作)。 Union

窝太弱啦,参考的LYL大犇的代码和思路。。。

我们可以记录一个方块所在的竖列有多少方块\(siz\)和这个方块上面有多少方块\(up\),显然答案为\(siz_u-up_u-1\)。

现在来考虑怎么维护着两个玩意。

容易想到要用并查集维护。

详细的请看代码,代码中维护这两个信息说的都很详细了。

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <cstdio>
int getint() {
	int r = 0,k=1; char c = getchar();
	for (; c < '0' || c > '9'; c = getchar()) if (c == '-')k=-1;
	for (; '0' <= c && c <= '9'; c = getchar()) r=r*10-'0'+c;
	return r*k;
}
int getop() {
	char c = getchar();
	for (; c < 'A' || c > 'Z'; c = getchar());
	if (c == 'M') return 1;
	return 0;
}
const int n = 30000;
const int maxn = 30005;
int p;
int f[maxn], up[maxn], siz[maxn];
int find(int x) {
	if (x != f[x]) {
		int tmp = f[x];
		f[x] = find(f[x]);
		up[x] += up[tmp];
		return f[x];
	}
	else return x;
}
void carry(int fr, int to) {
	int x = find(fr);
	int y = find(to);
	if (x == y) return;
	f[y] = x;
	up[y] = siz[x];
	siz[x] += siz[y];
}
int main () {
	for (int i = 1; i <= n; ++i) f[i] = i, siz[i] = 1;
	p = getint();
	int x, y;
	while (p--) {
		if (getop()) {
			x = getint(); y = getint();
			carry(x, y);
		} else {
			x = getint(); y = find(x);
			printf("%d\n", siz[y] - up[x] - 1);
		}
	}
}