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[N], d[N];
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;
}