hdu 2818 Building Block 并查集 路径压缩
2014-03-14 20:20
399 查看
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define N 30005 int set ; int num ; int cnt ; int find(int x){ if(set[x]==x) return x; int temp=set[x]; set[x]=find(set[x]);//路径压缩,不进行路径压缩果断的超时!! cnt[x]+=cnt[temp];//合并结果 return set[x]; } void insert(int x,int y){ int fx=find(x); int fy=find(y); if(fx==fy) return; cnt[fx]=num[fy]; num[fy]+=num[fx]; num[fx]=0; set[fx]=fy;//通过这里将两个集合合并了 } int main(){ int n; while(scanf("%d",&n)!=EOF){ for(int i=0;i<N;i++){ set[i]=i; num[i]=1;//包含数字i的那个pile上总共有多少个数字 cnt[i]=0;//当前数字下面的数量 } int x,y; char ch; while(n--){ getchar();//吸收换行 scanf("%c",&ch); if(ch=='M'){ scanf("%d%d",&x,&y); insert(x,y); } else { scanf("%d",&x); find(x); printf("%d\n",cnt[x]); } } } return 0; }刚开始时用的是队列模拟,果断的超时,在合并的时候更新了当前队列里的所有值,其实这不需要,查找的时候再更新就行了,还有就是通过路径压缩可以很快找到当前点所属的集合,对于这题如果不进行压缩就会超时。
相关文章推荐
- [HDOJ2818]Building Block(带权并查集,路径压缩)
- hdu-2818/POJ-1988 Building Block(并查集+路径压缩)
- 【HDU】2818-Building Block(并查集)
- hdu 1213 How Many Tables 并查集模板题+路径压缩
- hdu 2818 Building Block(并查集,输出一元素下边有多少)
- HDU 3635 Dragon Balls(并查集--路径压缩拓展应用)
- HDU 2818 Building Block(并查集)
- hdu 2818 Building Block(带权并查集)
- HDU 3635 并查集+路径压缩+记录每个点移动次数
- hdu 2818 Building Block(加权并查集)
- HDU 3038 How Many Answers Are Wrong(路径压缩并查集)
- hdu 2818 Building Block【基础带权并查集】
- hdu 3635 Dragon Balls ( 并查集路径压缩)
- HDU 4496D-City2013通化邀请赛D题(并查集 需要压缩路径)
- ?HDU 2818 Building Block 求大神讲解 (并查集)
- hdu 2818 Building Block (并查集)(根据父节点来更新)
- 卡路径压缩的并查集题目-hdu 1856
- HDU 3038 How Many Answers Are Wrong (并查集路径压缩)
- HDU 2818 Building Block (带权并查集)
- HDU 2818 Building Block【并查集+根节点偏移量】