题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3083
换根后路径还是不变,子树分类讨论一下,树剖后线段树维护即可。
代码如下:
#include<cstdio> #include<cstring> #include<algorithm> #define mid ((l+r)>>1) #define ls (x<<1) #define rs (x<<1|1) using namespace std; typedef long long ll; int const xn=1e5+5; int n,m,hd[xn],ct,to[xn<<1],nxt[xn<<1],rt; int tim,dfn[xn],fa[xn],siz[xn],son[xn],dep[xn],top[xn],id[xn]; ll a[xn],mn[xn<<2],lzy[xn<<2],inf=1e17; ll rd() { ll ret=0,f=1; char ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=0; ch=getchar();} while(ch>='0'&&ch<='9')ret=ret*10+ch-'0',ch=getchar(); return f?ret:-ret; } ll minn(ll x,ll y){return x<y?x:y;} void add(int x,int y){to[++ct]=y; nxt[ct]=hd[x]; hd[x]=ct;} void dfs(int x,int ff) { fa[x]=ff; dep[x]=dep[ff]+1; siz[x]=1; for(int i=hd[x],u;i;i=nxt[i]) { if((u=to[i])==ff)continue; dfs(u,x); siz[x]+=siz[u]; if(siz[u]>siz[son[x]])son[x]=u; } } void dfsx(int x) { dfn[x]=++tim; id[tim]=x; if(son[x])top[son[x]]=top[x],dfsx(son[x]); for(int i=hd[x],u;i;i=nxt[i]) if((u=to[i])!=fa[x]&&u!=son[x])top[u]=u,dfsx(u); } void build(int x,int l,int r) { if(l==r){mn[x]=a[id[l]]; return;}//id!! build(ls,l,mid); build(rs,mid+1,r); mn[x]=minn(mn[ls],mn[rs]); } void turn(int x,ll v){mn[x]=v; lzy[x]=v;} void pushdown(int x) { if(!lzy[x])return; turn(ls,lzy[x]); turn(rs,lzy[x]); lzy[x]=0; } void update(int x,int l,int r,int L,int R,ll v) { if(l>=L&&r<=R){turn(x,v); return;} pushdown(x); if(mid>=L)update(ls,l,mid,L,R,v); if(mid<R)update(rs,mid+1,r,L,R,v); mn[x]=minn(mn[ls],mn[rs]); } ll query(int x,int l,int r,int L,int R) { if(L>R)return inf; if(l>=L&&r<=R)return mn[x]; pushdown(x); ll ret=inf; if(mid>=L)ret=minn(ret,query(ls,l,mid,L,R)); if(mid<R)ret=minn(ret,query(rs,mid+1,r,L,R)); return ret; } void change(int x,int y,ll v) { while(top[x]!=top[y]) { if(dep[top[x]]<dep[top[y]])swap(x,y); update(1,1,n,dfn[top[x]],dfn[x],v); x=fa[top[x]]; } if(dep[x]<dep[y])swap(x,y); update(1,1,n,dfn[y],dfn[x],v); } int find(int x,int y)//y in x { while(top[y]!=top[x]) { if(fa[top[y]]==x)return top[y]; y=fa[top[y]]; } return son[x]; } ll ask(int x) { if(x==rt)return query(1,1,n,1,n); if(dfn[rt]<dfn[x]||dfn[rt]>=dfn[x]+siz[x]) return query(1,1,n,dfn[x],dfn[x]+siz[x]-1); int y=find(x,rt); return minn(query(1,1,n,1,dfn[y]-1),query(1,1,n,dfn[y]+siz[y],n)); } int main() { n=rd(); m=rd(); for(int i=1,x,y;i<n;i++)x=rd(),y=rd(),add(x,y),add(y,x); dfs(1,0); top[1]=1; dfsx(1); for(int i=1;i<=n;i++)a[i]=rd(); build(1,1,n); rt=rd(); ll z; for(int i=1,opt,x,y;i<=m;i++) { opt=rd(); x=rd(); if(opt==1)rt=x; if(opt==2)y=rd(),z=rd(),change(x,y,z); if(opt==3)printf("%lld ",ask(x)); } return 0; }