传送门
lct模板题。
只是这一次变成了维护链上的和。
代码:
#include<bits/stdc++.h>
#define N 30005
using namespace std;
inline int read(){
int ans=0;
char ch=getchar();
while(!isdigit(ch))ch=getchar();
while(isdigit(ch))ans=(ans<<3)+(ans<<1)+(ch^48),ch=getchar();
return ans;
}
int rev[N],fa[N],sum[N],son[N][2],stk[N],val[N],top,n,m;
inline int which(int x){return x==son[fa[x]][1];}
inline bool isroot(int x){return !fa[x]||(x!=son[fa[x]][0]&&x!=son[fa[x]][1]);}
inline void pushup(int p){sum[p]=sum[son[p][0]]+sum[son[p][1]]+val[p];}
inline void pushdown(int p){
if(!rev[p])return;
swap(son[p][0],son[p][1]),rev[p]^=1;
if(son[p][0])rev[son[p][0]]^=1;
if(son[p][1])rev[son[p][1]]^=1;
}
inline void rotate(int x){
int y=fa[x],z=fa[y],t=which(x);
if(z&&!isroot(y))son[z][which(y)]=x;
fa[y]=x,fa[x]=z,son[y][t]=son[x][t^1],son[x][t^1]=y;
if(son[y][t])fa[son[y][t]]=y;
pushup(y),pushup(x);
}
inline void splay(int x){
stk[top=1]=x;
for(int i=x;!isroot(i);i=fa[i])stk[++top]=fa[i];
while(top)pushdown(stk[top--]);
while(!isroot(x)){if(!isroot(fa[x]))rotate(which(fa[x])==which(x)?fa[x]:x);rotate(x);}
}
inline void access(int x){for(int y=0;x;x=fa[y=x])splay(x),son[x][1]=y,pushup(x);}
inline void makeroot(int x){access(x),splay(x),rev[x]^=1,pushdown(x);}
inline int findroot(int x){
access(x),splay(x);
while(pushdown(x),son[x][0])x=son[x][0];
return splay(x),x;
}
inline void link(int x,int y){makeroot(x),fa[x]=y;}
inline void cut(int x,int y){makeroot(x),access(y),splay(y),son[y][0]=fa[x]=0,pushup(y);}
int main(){
n=read();
for(int i=1;i<=n;++i)val[i]=read();
m=read();
while(m--){
char s[15];
int x,y;
scanf("%s",s),x=read(),y=read();
if(s[0]=='b'){
makeroot(x),access(y);
if(findroot(y)!=x)puts("yes"),link(x,y);
else puts("no");
}
else if(s[0]=='p')splay(x),val[x]=y,pushup(x);
else{
makeroot(x),access(y);
if(findroot(y)!=x)puts("impossible");
else splay(y),printf("%d\n",sum[y]);
}
}
return 0;
}