倍增水题……
本来还想用LCT做的……然后发现根本不需要
//minamoto
#include<bits/stdc++.h>
using namespace std;
#define getc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
char buf[<<],*p1=buf,*p2=buf;
inline int read(){
#define num ch-'0'
char ch;bool flag=;int res;
while(!isdigit(ch=getc()))
(ch=='-')&&(flag=true);
for(res=num;isdigit(ch=getc());res=res*+num);
(flag)&&(res=-res);
#undef num
return res;
}
inline bool isop(char ch){
return ch=='I'||ch=='H'||ch=='O';
}
inline char readop(){
char ch;
while(!isop(ch=getc()));
return ch;
}
const int N=;
int head[N],Next[N<<],edge[N<<],ver[N<<],fa[N][],d[N],dist[N];
int n,m,tot;
inline void add(int u,int v,int e){
ver[++tot]=v,Next[tot]=head[u],head[u]=tot,edge[tot]=e;
ver[++tot]=u,Next[tot]=head[v],head[v]=tot,edge[tot]=e;
}
void dfs(int u,int f){
d[u]=d[f]+,fa[u][]=f;
for(int i=;(<<i)<=d[u];++i) fa[u][i]=fa[fa[u][i-]][i-];
for(int i=head[u];i;i=Next[i]){
int v=ver[i];
if(v==f) continue;
dist[v]=dist[u]+edge[i],dfs(v,u);
}
}
int LCA(int x,int y){
if(d[x]<d[y]) swap(x,y);
for(int i=;i>=;--i)
if(d[fa[x][i]]>=d[y]) x=fa[x][i];
if(x==y) return x;
for(int i=;i>=;--i)
if(fa[x][i]!=fa[y][i])
x=fa[x][i],y=fa[y][i];
return fa[x][];
}
int querylen(int x,int y,int k){
int lca=LCA(x,y);
if(d[x]-d[lca]+>=k){
int ans=d[x]-k+;
for(int i=;i>=;--i)
if((<<i)<=d[x]-ans) x=fa[x][i];
return x;
}
else{
int ans=d[lca]*+k-d[x]-;
for(int i=;i>=;--i){
if(d[y]-(<<i)>=ans) y=fa[y][i];
}
return y;
}
}
int main(){
//freopen("testdata.in","r",stdin);
int q=read();
while(q--){
memset(head,,sizeof(head));
memset(fa,,sizeof(fa));
d[]=dist[]=,tot=;
int n=read();
for(int i=;i<n;++i){
int u=read(),v=read(),e=read();
add(u,v,e);
}
dfs(,);
bool flag=true;
while(flag){
char op=readop();
switch(op){
case 'O':flag=false;break;
case 'I':{
int u=read(),v=read();
int lca=LCA(u,v);
printf("%d\n",dist[u]+dist[v]-*dist[lca]);
break;
}
case 'H':{
int u=read(),v=read(),k=read();
printf("%d\n",querylen(u,v,k));
break;
}
}
}
puts("");
}
return ;
}