Today's efficiency is not bad. make persistent efforts ^-^
In general, this question is not difficult, but the tragedy is that I understood the wrong question at first.
(1) n queues and N queuesCubeBody.
2) each queue has a cube during initialization.
3) two operations: m x Y: Put the set where X is located in the set where Y is located. To put it bluntly, put the set where Y is located after the set where X is located.
C X: How many cubes are there in cube X?
Haha, we found that, in fact, every time we "really" execute find (), we actually continue to maintain the Union. Only when we perform a union operation related to node X, after maintenance, the nodes on the x node are also maintained and directly mounted to the root node, this means that the maintenance of other points will not affect the nodes that have been maintained.
There is also the calculation. The number of elements under Node x = the number of elements in the set where X is located-the number of elements above X-1. It's easy to understand.
For more details, seeCode:
#include
# define maxn 30010int f [maxn], R [maxn], abve [maxn]; // F [] records the parent node, R [a] records the number of elements in the set where Element A is located. The abve [a] records the number of elements above element a void Init () // initializes {int I; for (I = 1; I <= maxn; I ++) {f [I] = I; R [I] = 1; abve [I] = 0 ;}} int find (INT X) {If (x = f [x]) return f [X]; int T = find (F [x]); above [x] + = above [f [x]; F [x] = T; return f [X];} // find the root node and compress the path, at the same time, maintain the value of the above []. Similarly, pay attention to the recursive process and you will find a very important thing. // It is similar to backtracking. After tracing to the root node, every element is directly mounted to the root node // This avoids repeated operations. In fact, this is also the key to path compression void Union (int x, int Y) {int A = find (x); int B = find (y); if (a = B) return; above [B] = R [a]; R [a] + = R [B]; F [B] = A;} // attaches the set where Y is located to the set where X is located. Although it is located after the set where element x is located, in fact, it is directly attached to the root node // This also leads to a word, "logical distance", abve records the logical distance from the node to the root node int main () {int I, A, B, n; char ch [2]; scanf ("% d", & N); Init (); for (I = 1; I <= N; I ++) {scanf ("% s", CH); If (CH [0] = 'M ') {scanf ("% d", & A, & B); Union (a, B);} else {scanf ("% d", & ); printf ("% d \ n", R [find (a)]-above [a]-1) ;}} return 0 ;}