Cube stacking
| Time limit:2000 ms |
|
Memory limit:30000 K |
| Total submissions:18900 |
|
Accepted:6568 |
| 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. The distance between the sum [I] record and the root is maintained continuously.
Reference code:
#include <iostream>#include <vector>#include <map>using namespace std;const int MAXN = 30010;int p;int father[MAXN], sum[MAXN], num[MAXN];void init() { for (int i = 1; i <= 30000; i++) { father[i] = i; sum[i] = 0; num[i] = 1; }}int find_set(int x) { int tmp = father[x]; if (father[x] != x) { father[x] = find_set(father[x]); sum[x] += sum[tmp]; } return father[x];}void union_set(int x, int y) { x = find_set(x); y = find_set(y); if (x == y) return; father[x] = y; sum[x] += num[y]; num[y] += num[x];}void solve() { for (int k = 0; k < p; k++) { char op; cin >> op; if (op == 'M') { int x, y, posx; cin >> x >> y; union_set(x, y); } else if (op == 'C') { int x, cnt = 0; cin >> x; find_set(x); cout << sum[x] << endl; } }}int main() { ios::sync_with_stdio(false); while (cin >> p) { init(); solve(); } return 0;}