Cube stacking
Time limit:2000 ms |
|
Memory limit:30000 K |
Total submissions:18834 |
|
Accepted:6535 |
Case time limit:1000 ms |
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 6M 1 6C 1M 2 4M 2 6C 3C 4 Sample output 102 Source Usaco 2004 u s open |
Question:
There are n cubes and N grids, 1 ~ N number. At first, cube I was on the grid I, and each grid had exactly one cube. Now M group operations, m a B indicates that all the cubes in the grid where cube A is located are placed on all the cubes in the grid where cube B is located. C X indicates the number of cubes under cube X.
Solution:
Based on the query, you only need to know the distance from X to the father and the distance from the father to the end to know the distance from X to the end.
Solution code:
#include <iostream>#include <cstdio>using namespace std;const int maxn=31000;int father[maxn],cnt[maxn],dis[maxn];int find(int x){ if(father[x]!=x){ int tmp=father[x]; father[x]=find(father[x]); dis[x]+=dis[tmp]; } return father[x];}void combine(int x,int y){ father[x]=y; dis[x]+=cnt[y]; cnt[y]+=cnt[x];}int main(){ int m; scanf("%d",&m); for(int i=0;i<maxn;i++){ father[i]=i; cnt[i]=1; dis[i]=0; } while(m-- >0){ char ch; cin>>ch; if(ch=='M'){ int a,b; scanf("%d%d",&a,&b); if(find(a)!=find(b)) combine(find(a),find(b)); }else{ int x; scanf("%d",&x); find(x); printf("%d\n",dis[x]); } } return 0;}