您的位置:首页 > 其它

POJ 1988 Cube Stacking

2016-07-13 15:10 260 查看

题目分析

典型的带权并查集,这道题有2个操作,一个是将带a的那一堆石头移到带b的那一堆石头上面,另一个是询问a号石头下面有多少石头。这里我定义了3个数组,fa用于查父节点,he查编号为i的石头下面有多少石头,sum表示以a为根节点的石头堆中有多少石头。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 30005;

int sum[maxn],he[maxn],fa[maxn];  //sum表示这堆石头有多少个,he表示

void init(){
for(int i = 0; i < maxn; i++){
sum[i] = 1;
he[i] = 0;
fa[i] = i;
}
}

int Find(int x){
if(x == fa[x]) return fa[x];
int temp = Find(fa[x]);
he[x] += he[fa[x]];
fa[x] = temp;
return fa[x];
}

int main()
{
int P;
scanf("%d", &P);
char op;
int x,y;
init();
while(P--){
cin >> op;
if(op == 'M') {
scanf("%d%d", &x, &y);
int xx = Find(x);
int yy = Find(y);
he[xx] = sum[yy];
sum[yy] += sum[xx];
fa[xx] = yy;
}else{
scanf("%d", &x);
Find(x);
printf("%d\n", he[x]);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: