并查集的简单运用
在使用并查集的过程中维护当前点到根的距离
代码如下:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define MAXN 20100
using namespace std;
int dis[MAXN], p[MAXN];
int findset(int x) {
if(p[x] == x)
return x;
else {
int root = findset(p[x]);//在这个过程中求出了p[x]到根的距离dis[p[x]]
dis[x] += dis[p[x]];
return p[x] = root;
}
}
int main(void) {
int T, N, c, d, i;
char ch;
cin >> T;
while(T--) {
cin >> N;
for(i=0; i<N; ++i) {
dis[i] = 0;
p[i] = i;
}
while(true) {
getchar();
ch = getchar();
if(ch == 'E') {
cin >> c;
findset(c);
cout << dis[c] << endl;
} else if(ch == 'I'){
cin >> c >> d;
p[c] = d;
dis[c] = abs(c-d)%1000;
} else if(ch == 'O')
break;
}
}
return 0;
}