传送门
【题目分析】
不同于上一个换根的题,这道题求的是子树最小值。
所以我想了很久。。。。。。还想着将子树全部改为INF再一个一个更新回去。。。。
我好菜啊qwq
其实就只用在1~dfn[las]-1和dfn[las]+siz[las]~n之间取最小值就行了嘛。。。。
qwq
【代码~】
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e5+10;
const int MAXM=2e5+10;
const int INF=0x3f3f3f3f;
int n,q,cnt;
int rt=1;
int a[MAXN];
int head[MAXN],depth[MAXN],siz[MAXN],fa[MAXN],son[MAXN],top[MAXN];
int nxt[MAXM],to[MAXM];
int dfn[MAXN],ys[MAXN],tot;
struct Tree{
int l,r;
int minn;
}tr[MAXN<<2];
int Read(){
int i=0,f=1;
char c;
for(c=getchar();(c>'9'||c<'0')&&c!='-';c=getchar());
if(c=='-')
f=-1,c=getchar();
for(;c>='0'&&c<='9';c=getchar())
i=(i<<3)+(i<<1)+c-'0';
return i*f;
}
void add(int x,int y){
nxt[cnt]=head[x];
head[x]=cnt;
to[cnt]=y;
cnt++;
}
void dfs1(int u,int f){
siz[u]=1;
for(int i=head[u];i!=-1;i=nxt[i]){
int v=to[i];
if(v==f)
continue;
depth[v]=depth[u]+1;
fa[v]=u;
dfs1(v,u);
siz[u]+=siz[v];
if(siz[v]>siz[son[u]])
son[u]=v;
}
}
void dfs2(int u,int tp){
top[u]=tp;
dfn[u]=++tot;
ys[tot]=u;
if(!son[u])
return ;
dfs2(son[u],tp);
for(int i=head[u];i!=-1;i=nxt[i]){
int v=to[i];
if(v==fa[u]||v==son[u])
continue;
dfs2(v,v);
}
}
void push_up(int root){
tr[root].minn=min(tr[root<<1].minn,tr[root<<1|1].minn);
}
void build(int root,int l,int r){
tr[root].l=l,tr[root].r=r;
if(l==r){
tr[root].minn=a[ys[l]];
return ;
}
int mid=l+r>>1;
build(root<<1,l,mid);
build(root<<1|1,mid+1,r);
push_up(root);
}
void update(int root,int l,int r,int x,int key){
if(l==r){
tr[root].minn=key;
return ;
}
int mid=l+r>>1;
if(x<=mid)
update(root<<1,l,mid,x,key);
else
update(root<<1|1,mid+1,r,x,key);
push_up(root);
}
int query(int root,int l,int r,int L,int R){
if(l>R||r<L)
return INF;
if(L<=l&&r<=R)
return tr[root].minn;
int mid=l+r>>1;
if(R<=mid)
return query(root<<1,l,mid,L,R);
else{
if(L>mid)
return query(root<<1|1,mid+1,r,L,R);
else
return min(query(root<<1,l,mid,L,mid),query(root<<1|1,mid+1,r,mid+1,R));
}
}
int lca(int x,int y){
while(top[x]!=top[y]){
if(depth[top[x]]<depth[top[y]])
swap(x,y);
x=fa[top[x]];
}
return depth[x]<depth[y]?x:y;
}
int find(int x,int y){
while(top[x]!=top[y]){
if(depth[top[x]]<depth[top[y]])
swap(x,y);
if(fa[top[x]]==y)
return top[x];
x=fa[top[x]];
}
if(depth[x]<depth[y])
swap(x,y);
return son[y];
}
int main(){
memset(head,-1,sizeof(head));
n=Read(),q=Read();
for(int i=1;i<=n;++i){
int x=Read();
a[i]=Read();
if(!x)
continue;
add(x,i),add(i,x);
}
dfs1(1,-1),dfs2(1,1);
build(1,1,n);
while(q--){
char cz[3];
scanf("%s",cz);
if(cz[0]=='V'){
int x=Read(),k=Read();
update(1,1,n,dfn[x],k);
}
if(cz[0]=='E')
rt=Read();
if(cz[0]=='Q'){
int x=Read();
int lc=lca(rt,x);
int las=find(rt,lc);
if(x==rt){
cout<<tr[1].minn<<'\n';
continue;
}
if(lc!=x){
cout<<query(1,1,n,dfn[x],dfn[x]+siz[x]-1)<<'\n';
continue;
}
cout<<min(query(1,1,n,1,dfn[las]-1),query(1,1,n,dfn[las]+siz[las],n))<<'\n';
}
}
return 0;
}