Building Block
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3365 Accepted Submission(s): 1009
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.
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
分析:题意为开始有N堆积木,每堆有1个积木,有操作:M x y 把x所在的那一堆积木搭在y所在的那一堆上;
询问: C x :x下面有多少积木。明显为带权并查集,开一个sum【maxh】用来存当前x所在对的积木
数量,rank【maxh】存放x下有多少积木,则当find(x)!=find(y)时,rank【x】+=sum【b】,
sum【b】+=sum【a】;分析完毕。
- #include<stdio.h>
- #include<string.h>
- #include<algorithm>
- #include<iostream>
- #define maxh 30000+10
- using namespace std;
- int set[maxh],rank[maxh],sum[maxh];
- void init()
- {
- for(int i=0;i<=maxh;i++)
- {
- set[i]=i;
- rank[i]=0;
- sum[i]=1;
- }
- }
- int findx(int x)
- {
- if(x==set[x])
- return set[x];
- int p=set[x];
- set[x]=findx(set[x]);
- rank[x]+=rank[p];
- return set[x];
- }
- void Union(int x,int y)
- {
- int a=findx(x);
- int b=findx(y);
- if(a==b)
- return;
- set[a]=b;
- rank[a]=sum[b];
- sum[b]+=sum[a];
- return;
- }
- int main()
- {
- char c[3];
- int P,a,b;
- while(~scanf("%d",&P))
- {
- init();
- for(int i=0;i<P;i++)
- {
- scanf("%s",c);
- if(c[0]=='M')
- {
- scanf("%d%d",&a,&b);
- Union(a,b);
- }
- else
- {
- scanf("%d",&a);
- findx(a);
- printf("%d\n",rank[a]);
- }
- }
- }
- return 0;
- }