Cube Stacking
| Time Limit: 2000MS |
|
Memory Limit: 30000K |
| Total Submissions: 20392 |
|
Accepted: 7148 |
| Case Time Limit: 1000MS |
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 cube Y.
* In a count operation, Farmer John asks Bessie to count the number of cubes on the stack with Cube X is under the C Ube 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
6M 1 6C 1M 2 4M 2 6C 3C 4
Sample Output
102
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib > #include <string> #include <algorithm> #include <queue> #include <vector> #include < stack>using namespace std; #define MAXN 30010int n;int dist[maxn],fa[maxn],rnk[maxn];char opt[2];int Find (int x) {if ( FA[X]==X) return fa[x]; int temp=fa[x]; Fa[x]=find (Fa[x]); DIST[X]+=DIST[TEMP]; return fa[x];} int main () {int x, y; while (scanf ("%d", &n)!=eof) {for (int i=0;i<maxn;i++) {fa[i]=i; dist[i]=0; Rnk[i]=1; } for (int i=0;i<n;i++) {scanf ("%s", opt); if (opt[0]== ' M ') {scanf ("%d%d", &x,&y); int fx,fy; Fx=find (x), Fy=find (y); if (fx!=fy) {fa[fy]=fx; DIST[FY]=RNK[FX]; RNK[FX]+=RNK[FY]; }} else if (opt[0]== ' C ') {scanf ("%d", &x); printf ("%d\n", Rnk[find (x)]-dist[x]-1); }}} return 0;}
(with right and check set) POJ 1988