There are n Independent magnets (1-N labels) on the table. One person moves the N heaps, and the other person asks.
Rule: m a B: the magnet numbered a is placed on the top of the magnet numbered B'
: C a asks about the number of magnets under magnet!
Analysis: Using and querying sets, each pile of magnets is considered as a set. "m a B" means to merge A to B. Each set is ordered and three variables are set.
F: the root node, which is initialized to itself;
ALL: number of elements in the set with this node as the root;
Num: the distance from this point to its root node (number of elements );
SoAll [f [a]-num [a]-1The number of elements contained in the set with node A as the root node! (That is, the number of magnets !!!)
The Code is as follows:
# Include <cstdio> # include <cstring> # include <iostream> using namespace STD; const int maxn = 52014; int N, num [maxn], all [maxn], f [maxn]; void Init () {for (INT I = 1; I <maxn; I ++) {f [I] = I; All [I] = 1; // at this time, only one root node exists! Num [I] = 0 ;}} int find (INT X) {If (F [x]! = X) {int TE = f [X]; F [x] = find (F [x]); num [x] + = num [Te];} return f [X];} void Unity (int A, int B) {int x = find (A), Y = find (B); F [y] = X; // The root node of A is the parent node of B's root node !!! Num [y] = All [X]; // update the distance from the root node of B to the root node of! All [x] + = All [y]; // update all [a] because a new magnet set is placed on B.} Int main () {int t; while (CIN> T) {n = T; Init (); While (t --) {char STR [12]; int, b; CIN> STR; If (STR [0] = 'M') {// place a on B! Cin> A> B; unity (a, B);} else {CIN> A; // It is a magnet pressed under! Cout <all [find (a)]-num [a]-1 <Endl; // except for the magnet! }}} Return 0 ;}
Poj-1988-Cube stacking