HDU 2818 Building Block(带权并查集)
2015-07-21 15:43
471 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2818
题 意:有1----n个堆,每一堆有一个blocks,并且对他们进行两个操作:
1、把 X 所在的那一堆放到 Y 所在的那一堆上面。
2、询问 X 下面有多少个blocks。
思 路:使用并查集处理数据,并且将每个结点的高度与它之下的blocks数记录下来。
注:需要使用状态压缩,否则会超时。
代码如下:
题 意:有1----n个堆,每一堆有一个blocks,并且对他们进行两个操作:
1、把 X 所在的那一堆放到 Y 所在的那一堆上面。
2、询问 X 下面有多少个blocks。
思 路:使用并查集处理数据,并且将每个结点的高度与它之下的blocks数记录下来。
注:需要使用状态压缩,否则会超时。
代码如下:
#include <iostream> using namespace std; #include <string.h> #include <stdio.h> #include <queue> #include <algorithm> #define m 30030 typedef long long LL; int ben[m],high[m],under[m]; int findx(int x)//状态压缩后的find函数 { if(x==ben[x]) return x; int z = findx(ben[x]); under[x] += under[ben[x]]; return ben[x]=z; } void mergex( int x, int y ) { int fx = findx(x); int fy = findx(y); if(fx!=fy) { under[fx]=high[fy];//记录该结点原有的blocks数 ben[fx]=fy; high[fy]+=high[fx];//初始化blocks数目 } } int main() { int T; scanf ( "%d", &T ); for( int i = 0; i <= m; i ++ ) ben[i]=i,under[i]=0,high[i]=1; while ( T-- ) { char ch; scanf ( " %c", &ch ); if( ch == 'M' ) { int x,y; scanf ( "%d %d", &x, &y ); mergex(x,y); } else if( ch == 'C' ) { int x; scanf ( "%d", &x ); findx(x); printf("%d\n",under[x]); } } return 0; }
相关文章推荐
- Javascript SHA-1:Secure Hash Algorithm
- [转]可视化的数据结构和算法
- 统计文件中不小于某一长度的单词的个数(泛型算法实现)
- 使用他人的MD5编码类,修改形成密码串
- Extracting Structured Data from Web Pages
- (译)Cocos2d_for_iPhone_1_Game_Development_Cookbook:1.13使用CCTexture2DMutable调换调色盘
- Java中3DES加密
- Refactoring Notes-Refactoring Methods(3)
- 图书馆管理程序~~不过貌似功能!!有空再修修
- trainging contest#2(2011成都现场赛)I BY Hyoga
- C/C++头文件包含内容概览
- 堆栈的应用(1) 平衡符号 C++实现
- 程序员编程艺术第一章、左旋转字符串
- 程序员编程艺术:第三章续、Top K算法问题的实现
- 程序员编程艺术:第四章、现场编写类似strstr/strcpy/strpbrk的函数
- 十四、第三章再续:快速选择SELECT算法的深入分析与实现
- 程序员编程艺术:第七章、求连续子数组的最大和
- 程序员编程艺术:第八章、从头至尾漫谈虚函数
- 程序员编程艺术:第九章、闲话链表追赶问题
- 程序员编程艺术:第十章、如何给10^7个数据量的磁盘文件排序