hdu 2818 Building Block

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 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 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<maxlen; ++i)
10     {
11         father[i]=i;
12         all[i]=1;
13         sum[i]=0;
14     }
15 }
16 
17 int Find(int x)
18 {
19     if(x == father[x])
20         return father[x];
21     int temp=Find(father[x]);
22     sum[x]+=sum[father[x]];
23     father[x]=temp;
24     return father[x];
25 }
26 
27 void Union(int x,int y)
28 {
29     int a=Find(x);
30     int b=Find(y);
31     if(a==b)
32         return;
33     father[a]=b;
34     sum[a]+=all[b];
35     all[b]+=all[a];
36 }
37 
38 int main()
39 {
40     int n,a,b;
41     char s;
42     Init();
43     scanf("%d",&n);
44     while(n--)
45     {
46         getchar();
47         scanf("%c",&s);
48         if(s == 'M')
49         {
50             scanf("%d%d",&a,&b);
51             Union(a,b);
52         }
53         else
54         {
55             scanf("%d",&a);
56             Find(a);
57             printf("%d
",sum[a]);
58         }
59     }
60     return 0;
61 }
View Code
原文地址:https://www.cnblogs.com/shuzy/p/3187106.html