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

hdu 2818 Building Block(加权并查集)

2014-11-02 22:21 381 查看
题意翻译过来就是:开始有n棵树,每棵树的大小为1,然后做一些合并操作,同时要维护一个顺序关系和树的size。。

将C X Y 中的Y作为新的父亲就好做了。。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
#define REP(i,s,t) for(int (i)=(s);(i)<=(t);++(i))
typedef long long LL;
const int maxn = 30000;

int pa[maxn+5];
int under[maxn+5];
int tot[maxn+5];

int find(int x) {
if (x == pa[x]) return pa[x];
int t = pa[x];
pa[x] = find(t);
under[x] += under[t];
return pa[x];
}

int main() {
freopen("input.in", "r", stdin);
char buf[100];
int x, y, n;
cin >> n;
REP(i, 0, maxn) {pa[i] = i;under[i] = 0;tot[i] = 1;}
while (n--) {
scanf("%s",buf);
if (buf[0] == 'M') {
scanf("%d%d",&x,&y);
int fx = find(x), fy = find(y);
if (fx != fy) {
under[fx] = tot[fy];
pa[fx] = fy;
tot[fy] += tot[fx];
}
}
else {
scanf("%d",&x);
find(x);
printf("%d\n",under[x]);
}
}
/*
REP(i, 1, 6) find(i);
REP(i, 1, 6) cout << under[i] << ' ';cout << endl;
REP(i, 1, 6) cout << tot[i] << ' ';cout << endl;
REP(i, 1, 6) cout << pa[i] << ' ';cout << endl;
*/
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: