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

hdu 2818 Building Block 并查集 路径压缩

2014-03-14 20:20 344 查看
#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;
}
刚开始时用的是队列模拟,果断的超时,在合并的时候更新了当前队列里的所有值,其实这不需要,查找的时候再更新就行了,还有就是通过路径压缩可以很快找到当前点所属的集合,对于这题如果不进行压缩就会超时。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: