Description Farmer John and Betsy is 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 is 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 cub E Y.
* In a count operation, Farmer John asks Bessie to count the number of cubes on the stack with cube X is U NDEr 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 the INTEGERS:X and y.for count operations, the line also contains a single in Teger:x.
Note that the value of N does not appear in the input file. No move operation would 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
The main topic: there are several stacks, initially there is a cube. Two operations are supported: 1.move x y: Moves the stack where x resides to the top of the stack where Y is. 2.count x: The number of cubes below x in the stack where x is located.
is a and check the set of topics, but the right value and check set is not very simple, waste a lot of brains, read a lot of problems.
Record the size of each subset and the distance to the bottom, updating each time you merge.
#include <iostream> #include <cstdio> using namespace std;
int counts[30005];
int dis[30005];
int pre[30005];
int findfather (int x) {if (pre[x] = = x) return x;
int t = pre[x];
PRE[X] = Findfather (pre[x]);
DIS[X] + = dis[t];
return pre[x];
} void Mix (int x, int y) {int fx = Findfather (x);
int fy = findfather (y);
PRE[FX] = FY; DIS[FX] + = counts[fy];///x distance plus subset size Counts[fy] + = counts[fx];///root set size plus subset size COUNTS[FX] = 0;///empty subset} int mai
N () {int p;
char c;
int x, y;
CIN >> P;
for (int i = 1; I <= 30000; ++i) {pre[i] = i;
Counts[i] = 1;
Dis[i] = 0;
} for (int i = 1; I <= p; ++i) {cin >> C;
if (c = = ' C ') {int n;
int mmm;///This variable is set to CIN >> N;
mmm = Findfather (n);
printf ("%d\n", Dis[n]); } else {cin >> X;> y;
Mix (x, y);
}} return 0;
}