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

这题也是带权并查集,设三个数组pre[i],num[i](代表i所在集合的数字总数),root[i]表示i下面的数字总数。每次移动时输入两个数a,b,因为移动过程中a所在的所有数都移动到b所在集合所有数的上面,所以令a的祖先t1的父亲为b的祖先t2,这样下面递归的时候,root[i]可以递归相加。

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<map>
#include<string>
using namespace std;
char s[10];
int pre[30005],num[30005],root[30005];
int find(int x)
{
int temp;
if(pre[x]==x)return x;
temp=pre[x];
pre[x]=find(pre[x]);
root[x]+=root[temp];
return find(pre[x]);
} int main()
{
int p,i,m,j,a,b,t1,t2;
while(scanf("%d",&p)!=EOF)
{
for(i=0;i<=30005;i++){
pre[i]=i;num[i]=1;root[i]=0;
}
while(p--)
{
scanf("%s",s);
if(s[0]=='M'){
scanf("%d%d",&a,&b);
t1=find(a);t2=find(b);
if(t1==t2)continue;
pre[t1]=t2;
root[t1]+=num[t2];
num[t2]+=num[t1];
}
else if(s[0]=='C'){
scanf("%d",&a);
t1=find(a);
printf("%d\n",root[a]);
}
}
}
return 0;
}

最新文章

  1. 参考__Linux
  2. 让你fork下来的项目与源项目保持同步
  3. struts2的核心和工作原理
  4. iOS高效调试
  5. HTML静态网页 css样式表
  6. numpy——linspace创建等差数列
  7. liunx 套接字编程(Linux_C++)
  8. IE6 IE8下背景图片不显示问题
  9. Dynamics CRM 2011编程系列(60):JS编程之CRUD辅助类(JQuery版)
  10. js字符串倒序
  11. 搭建Struts2开发环境
  12. 多模块分布式系统的简单服务访问 - OSGI原形(.NET)
  13. 实现ie6下的居中
  14. 【转】amCharts,一款值得推荐的Flash charts图组件
  15. python_adb 图形界面获取app测试数据,并展示部分测试报告v1.0版本
  16. C# 之 static的用法详解
  17. js 判断是否可以打开本地软件
  18. 解决PuTTY中文乱码
  19. Subset II leetcode java
  20. [php] cookie 跨域共享

热门文章

  1. 【Linux】postfix大坑笔记
  2. CTFshow萌新赛-千字文
  3. merge join pg伪代码
  4. 20.java设计模式之解释器模式
  5. [从源码学设计]蚂蚁金服SOFARegistry之配置信息
  6. GitLab-CI/CD入门实操
  7. Vijos-P1103题解【线段树】
  8. POJ1629:picnic planning
  9. 1.8V转5V电平转换芯片,1.8V转5V的电源芯片
  10. Java中的深浅拷贝问题,你清楚吗?