#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <ctime> using namespace std; struct Node
{
int f,d;
}; Node node[];
int T,n,u,v; /*
void findset(int x,int &d,int &f)
{
if(node[x].f==x) return;
findset(f,node[f].d,node[f].f);
d+=node[f].d;
f=node[f].f;
}
*/ int findset(int x)
{
if(node[x].f==x) return x;
int tmp=findset(node[x].f);//tmp暂时存下返回值,因为node[x].f要在node[x].d+=node[node[x].f].d后才能改变
node[x].d+=node[node[x].f].d;
return node[x].f=tmp;
} int main()
{
//freopen("/home/user/桌面/in","r",stdin);
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
char op[];
for(int i=;i<=;i++)
{
node[i].d=;
node[i].f=i;
}
while(scanf("%s",op)==&&op[]!='O')
{
if(op[]=='I')//I i j
{
scanf("%d%d",&u,&v);
node[u].f=v;
node[u].d+=abs(u-v)%;
//printf("%d %d\n",node[u].f,node[u].d);
}
else
{
scanf("%d",&u);
findset(u);
printf("%d\n",node[u].d);
//for(int i=1;i<=4;i++)
//printf("f=%d d=%d\n",node[i].f,node[i].d);
}
}
}
//printf("time=%.3lf",(double)clock()/CLOCKS_PER_SEC);
return ;
}