Poj-1988-Cube stacking

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.