HDU-2818-Building Block

来源:互联网 发布:桌球游戏 知乎 编辑:程序博客网 时间:2024/06/11 11:24

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2818

Building Block


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
6M 1 6C 1M 2 4M 2 6C 3C 4
 

Sample Output
102
 

题目分析:带权并查集  
n块砖头,分为n堆,有两种操作M:把x堆放在y堆上面,C:求x堆的下面有多少个砖头。在普通并查集的基础上加上两个数组up[x]和down[x],分别表示x所在堆的大小以及x下面的元素。当移动时,首先确定x所在的那一堆最底部的X以及y所在那一堆最底部的Y,那么down[X]的数目就是另外一堆的up[Y],可以根据find(x)递归去一边寻找根一边更新其他未知的down[x],。

代码如下:

#include<iostream>#include<cstring>#include<cmath>#include<algorithm>#include<cstdio> using namespace std;int city,road;int pre[33333];int up[33333],down[33333];int find(int r){    if(pre[r]==r)    return r;    else    {        int t=find(pre[r]);        down[r]=down[r]+down[pre[r]];        pre[r]=t;         return pre[r];    }}void merge(int x,int y){    int t1=find(x);    int t2=find(y);    if(t1!=t2)    {        pre[t1]=t2;        down[t1]=up[t2];        up[t2]+=up[t1];    }}int main(){int n;while(cin>>n){int i;        char str[11];        int x,y;        for(i=0;i<=30010;i++)//否则会超时         {        pre[i]=i;        up[i]=1;//以上的部分包括自己             down[i]=0;//下面的数量 }for(i=1;i<=n;i++){cin>>str;if(str[0]=='M'){scanf("%d%d",&x,&y);merge(x,y);}else{scanf("%d",&x);find(x);cout<<down[x]<<endl;}}}return 0;}

原创粉丝点击