题目大意:
n个结点,初始时每个结点的父节点都不存在,两种操作:
I u v : 把u的父亲设为v,距离为|u-v| mod 1000
E u : 询问u到根节点的距离。
#include <iostream>
#include <cmath>
#include <stdio.h>
using namespace std;
const int maxn=20010;
int father[maxn],dis[maxn];
int find(int x)
{
if(father[x]!=x)
{
int num=find(father[x]);
dis[x]+=dis[father[x]];
return father[x]=num;
}
else
return x;
}
int main(){
int t,n;
cin>>t;
while(t--)
{
scanf("%d",&n);
int x,y;
for(int i=1;i<=n;i++)
{
dis[i]=0;
father[i]=i;
}
char wzx[10];
while(scanf("%s",wzx)&&wzx[0]!='O')
{
if(wzx[0]=='E')
{
scanf("%d",&x);
find(x);
printf("%d\n",dis[x]);
}
else
{
scanf("%d%d",&x,&y);
father[x]=y;
dis[x]=abs(x-y)%1000;
}
}
}
return 0;
}