FChang @ 2024-08-21 08:27:02
#include<bits/stdc++.h>
#define fi first
#define se second
using namespace std;
const int N = 3e5 + 5;
int n;
vector <pair<int,pair<int,int> > > e[N];
int fa[N], dep[N], top[N], son[N], siz[N], rnk[N], dfn[N], d[N], p[N];
int cnt;
void dfs1(int x,int f) {
siz[x] = 1;
for(auto v : e[x]) {
if(v.fi==f) continue;
dfn[v.fi] = ++cnt;
rnk[cnt] = v.fi;
p[v.se.se] = cnt;
fa[v.fi] = x;
dep[v.fi] = dep[x] + 1;
d[v.fi] = v.se.fi;
dfs1(v.fi,x);
siz[x] += siz[v.fi];
if(siz[v.fi] > siz[son[x]]) son[x] = v.fi;
}
return ;
}
void dfs2(int x,int tp) {
top[x] = tp;
for(auto v : e[x]) {
if(v.fi==fa[x]) continue;
if(v.fi==son[x]) dfs2(v.fi,tp);
else dfs2(v.fi,v.fi);
}
return ;
}
struct xds_Tree {
int tree[N];
#define mid (l+r>>1)
#define ls (x<<1)
#define rs (x<<1|1)
void pushup(int x) {
return void(tree[x] = max(tree[ls], tree[rs]));
}
void build(int x,int l,int r) {
if(l==r) return void(tree[x] = d[rnk[l]]);
build(ls,l,mid), build(rs,mid+1,r);
return void(pushup(x));
}
void update(int x,int l,int r,int L,int d) {
if(l==r&&L==l) return void(tree[x] = d);
if(L<=mid) update(ls,l,mid,L,d);
else update(rs,mid+1,r,L,d);
return void(pushup(x));
}
int query(int x,int y) {
int res = 0;
while(top[x]!=top[y]) {
if(dep[top[x]] < dep[top[y]]) swap(x,y);
res = max(res,Query(1,1,n,dfn[top[x]],dfn[x]));
x = fa[top[x]];
}
if(dfn[x] > dfn[y]) swap(x,y);
res = max(res,Query(1,1,n,dfn[x]+1,dfn[y]));
return res;
}
int Query(int x,int l,int r,int L,int R) {
if(l>=L&&r<=R) return tree[x];
int res = 0;
if(L<=mid) res = Query(ls,l,mid,L,R);
if(R>mid) res = max(res,Query(rs,mid+1,r,L,R));
return res;
}
}T;
int main() {
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin>>n;
int u, v, w;
for(int i=1; i<n; ++i) {
cin>>u>>v>>w;
e[u].push_back({v,{w,i}});
e[v].push_back({u,{w,i}});
}
dfn[1] = ++cnt;
dfs1(1,1);
dfs2(1,1);
T.build(1,1,n);
string opt;
int x, y;
while(1) {
cin>>opt;
if(opt=="DONE") break;
else if(opt=="QUERY") {
cin>>x>>y;
if(x==y) cout<<0<<"\n";
else cout<<T.query(x,y)<<"\n";
} else {
cin>>x>>y;
T.update(1,1,n,p[x],y);
}
}
return 0;
}