您的位置:首页 > 其它

UVA 1329 - Corporative Network(带权并查集)

2014-07-25 23:24 211 查看


UVA 1329 - Corporative Network

题目链接

题意:有n个结点,开始都是单独的结点,现在有I操作和E操作,I u v表示吧u的父亲结点设为,距离为|u - v| % 1000,E操作询问u到根的距离

思路:带权并查集,就多一个权表示距离即可

代码:

#include <cstdio>
#include <cstring>
#include <cstdlib>

const int N = 20005;

int t, n, parent
, d
;

int find(int x) {
if (x == parent[x]) return x;
int px = find(parent[x]);
d[x] += d[parent[x]];
return parent[x] = px;
}

int main() {
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 0; i <= n; i++) {
parent[i] = i; d[i] = 0;
}
char q[5];
int a, b;
while (~scanf("%s", q)) {
if (q[0] == 'O') break;
if (q[0] == 'E') {
scanf("%d", &a);
find(a);
printf("%d\n", d[a]);
}
if (q[0] == 'I') {
scanf("%d%d", &a, &b);
int pa = find(a);
int pb = find(b);
parent[a] = b;
d[a] = abs(a - b) % 1000;
}
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: