思路
用带权并查集维护到根的距离即可
代码
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
int fa[101000],dis[101000],n,T;
void init(void){
for(int i=1;i<=100000;i++)
fa[i]=i,dis[i]=0;
}
int find(int x){
if(fa[x]==x){
dis[x]=0;
return x;
}
else{
int t=find(fa[x]);
dis[x]+=dis[fa[x]];
return fa[x]=t;
}
}
void merge(int x,int y){//x->y
fa[x]=y;
dis[x]=abs(y-x)%1000;
}
int main(){
scanf("%d",&T);
while(T--){
init();
scanf("%d",&n);
char c=getchar();
while(c!='E'&&c!='I'&&c!='O')
c=getchar();
while(c!='O'){
if(c=='E'){
int u;
scanf("%d",&u);
find(u);
printf("%d\n",dis[u]);
}
else{
int u,v;
scanf("%d %d",&u,&v);
merge(u,v);
}
c=getchar();
while(c!='E'&&c!='I'&&c!='O')
c=getchar();
}
}
return 0;
}