RT
#include <iostream>
#include <cmath>
using namespace std;
struct tree{
int dis = 0,father = -1;
}node[20001];
int find_father(int x){
if(node[x].father == -1)
return x;
int second_father = node[x].father;
node[x].father = find_father(node[x].father);
node[x].dis += node[second_father].dis;
return node[x].father;
}
int main(){
int t;
cin >> t;
while(t--){
int n;
cin >> n;
char cao_zuo;cin >> cao_zuo;
while(cao_zuo != 'O'){
if(cao_zuo == 'E'){
int x;
cin >> x;
find_father(x);
cout << node[x].dis << endl;
}
else{
int x,y;
cin >> x >> y;
node[x].father = y;
node[x].dis = abs(x - y) % 1000;
}
cin >> cao_zuo;
}
}
return 0;
}
/*
1
4
E 3
I 3 1
E 3
I 1 2
E 3
I 2 4
E 3
O
*/