题目链接:UVa 1329 Corporative Network
做过一个类似的题目吧,现在才知道这叫做带权并查集。d[i]记录节点i到父节点的距离,查询的时候父节点在变,所以数组的值也在改变。
#include <iostream>
#include <cstdio>
//#include <cmath>
#include <algorithm>
using namespace std;
const int MAX_N = 20000 + 100;
int p[MAX_N], d[MAX_N];
int _find(int x)
{
if(p[x] != x)
{
int root = _find(p[x]);
d[x] += d[p[x]];
return p[x] = root;
}
else
return x;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int n, u, v;
char str[3];
scanf("%d", &n);
for(int i = 0; i <= n; i++)
p[i] = i, d[i] = 0;
while(scanf("%s", str), str[0] != 'O')
{
if(str[0] == 'E')
{
scanf("%d", &u);
_find(u);
printf("%d\n", d[u]);
}
else if(str[0] == 'I')
{
scanf("%d%d", &u, &v);
p[u] = v;
d[u] = abs(u - v) % 1000;
}
}
}
return 0;
}