真tm恶心......
Code:
#include<bits/stdc++.h> #define maxn 1000000 using namespace std; void setIO(string a) { string in=a+".in",out=a+".out"; freopen(in.c_str(),"r",stdin); } struct Union { int p[maxn]; void init() { for(int i=0;i<maxn;++i) p[i]=i; } int find(int x) { return p[x]==x?x:p[x]=find(p[x]); } // 1 : disconnect // 0 : connect int merge(int x,int y) { int a=find(x),b=find(y); if(a!=b) { p[a]=b; return 1; } return 0; } }tree,con; int n,Q; int val[maxn],sumv[maxn]; #define lson ch[x][0] #define rson ch[x][1] #define get(x) (ch[f[x]][1]==x) #define isRoot(x) (1^(ch[f[x]=tree.find(f[x])][1]==x||ch[f[x]=tree.find(f[x])][0]==x)) int ch[maxn][2],f[maxn],rev[maxn],sta[maxn],value[maxn]; void pushup(int x){ sumv[x]=sumv[lson]+sumv[rson]+val[x]; } void mark(int x) { if(!x) return; swap(lson,rson),rev[x]^=1; } void push(int x) { if(!x||!rev[x]) return; mark(lson),mark(rson),rev[x]^=1; } void rotate(int x) { int old=f[x],fold=f[old],which=get(x); if(!isRoot(old)) ch[fold][ch[fold][1]==old]=x; ch[old][which]=ch[x][which^1],f[ch[old][which]]=old; ch[x][which^1]=old,f[old]=x,f[x]=fold; pushup(old),pushup(x); } void splay(int x) { x=tree.find(x); int v=0,u=x,fa; sta[++v]=u; while(!isRoot(u)) sta[++v]=(f[u]=tree.find(f[u])), u=f[u]; while(v) push(sta[v--]); for(u=tree.find(f[u]); (fa=f[x])!=u; rotate(x)) if(f[fa]!=u) rotate(get(fa)==get(x)?fa:x); } void Access(int x) { int t=0; x=tree.find(x); while(x) splay(x),rson=t,pushup(x), t=x,x=(f[x]=tree.find(f[x])); } void MakeRoot(int x) { x=tree.find(x), Access(x), splay(x), mark(x); } void split(int x,int y) { x=tree.find(x),y=tree.find(y), MakeRoot(x), Access(y), splay(y); } void erase(int x){ lson=rson=val[x]=sumv[x]=rev[x]=f[x]=0; } void DFS(int x,int tp) { if(!x) return; tree.p[x]=tp,DFS(lson,tp), DFS(rson,tp); x=tree.find(x); if(tp!=x) erase(x); else lson=rson=rev[x]=0; } void link(int x,int y) { x=tree.find(x),y=tree.find(y), MakeRoot(x), f[x]=y; } int main() { // setIO("input"); tree.init(), con.init(); scanf("%d%d",&n,&Q); for(int i=1;i<=n;++i) scanf("%d",&val[i]),value[i]=sumv[i]=val[i]; while(Q--) { int p,a,b,x,y; scanf("%d%d%d",&p,&a,&b); // point a -> point b switch(p) { case 1 : { a=tree.find(a), b=tree.find(b); if(con.merge(a,b)) link(a,b); else { // 不属于同一点双 if(a!=b) { split(a,b), val[b]=sumv[b], DFS(b,b); } } break; } case 2 : { x=a, a=tree.find(a); Access(a), splay(a), val[a]+=b-value[x],pushup(a),value[x]=b; break; } case 3 : { a=tree.find(a),b=tree.find(b); if(con.find(a)!=con.find(b)) printf("-1\n"); else { split(a,b), printf("%d\n",sumv[b]); } break; } } } return 0; }