您的位置:首页 > 产品设计 > UI/UE

hdu 2818 Building Block (多个权值的并查集)

2017-07-18 11:39 483 查看
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. 

InputThe first line contains integer P. Then P lines follow, each of which contain an operation describe above.
OutputOutput 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


d1代表这个盒子下面的盒子数,d2代表以当前盒子做底的上面盒子数

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<vector>
#include<cmath>
//#include <bits/stdc++.h>
using namespace std;
const int N = 5e5+7;
typedef long long LL;
int d1
, d2
, f
;
int get(int x)
{
if(x==f[x]) return x;
int t=f[x];
f[x]=get(f[x]);
d1[x]=d1[t]+d1[x];
return f[x];
}

int main()
{
int n;
while(scanf("%d", &n)!=EOF)
{
for(int i=0;i<=30000;i++) f[i]=i, d2[i]=1;
memset(d1,0,sizeof(d1));
while(n--)
{
char str[4];
scanf("%s",str);
if(str[0]=='M')
{
int x, y;
scanf("%d %d", &x, &y);
int a=get(x),b=get(y);
if(a!=b)
{
f[a]=b;
d1[a]=d2[b];
d2[b]+=d2[a];
d2[a]=0;
}
}
else
{
int x;
scanf("%d", &x);
get(x);
cout<<d1[x]<<endl;
}
}

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: