Building Block
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1982 Accepted Submission(s): 598
Problem Description
John are playing with blocks. There are N blocks (1 <= N <= 30000) numbered 1...N。Initially, there are N piles, and each pile contains one block. Then John do some operations P times (1 <= P <= 1000000). There are two kinds of operation: M X Y : Put the whole pile containing block X up to the pile containing Y. If X and Y are in the same pile, just ignore this command. C X : Count the number of blocks under block X You are request to find out the output for each C operation.
Input
The first line contains integer P. Then P lines follow, each of which contain an operation describe above.
Output
Output the count for each C operations in one line.
Sample Input
6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4
Sample Output
1
0
2
Source
Recommend
gaojie
题目大意:有n个blocks,定义两种操作,一种是M x y 将block x加入到block y 下面,包括x的下面所有blocks。另一个是C x,计算block x 下面block 的数量并输出来。
分析:这道题可以通过并查集来解决,首先每个block的跟自己归在一类,,当遇到M操作时,将x 集合加入到y集合下面,并将y的数量加上x的数量,当碰到C 操作时,只要输出相应的数量即可。
1 #include2 #include 3 #include 4 #define maxlen 30010 5 using namespace std; 6 int father[maxlen],all[maxlen],sum[maxlen]; 7 void Init() 8 { 9 for(int i=0; i