# 【bzoj3786】星系探索

ETT模版题。

#include<bits/stdc++.h>
#define N 100010
using namespace std;
typedef long long ll;
const int M=200500;
int n,m,a[M];
struct Edge{int u,v,next;}G[M];
}
ll sumv[M];
inline void pushup(int x){
size[x]=size[c[x][0]]+size[c[x][1]]+w[x];
sumv[x]=sumv[c[x][0]]+sumv[c[x][1]]+w[x]*val[x];
}
inline void pushdown(int x){
}
inline void rotate(int x,int &k){
int y=fa[x],z=fa[y],l,r;
if(c[y][0]==x)l=0;else l=1;r=l^1;
if(y==k)k=x;else{if(c[z][0]==y)c[z][0]=x;else c[z][1]=x;}
fa[x]=z;fa[y]=x;fa[c[x][r]]=y;
c[y][l]=c[x][r];c[x][r]=y;
pushup(y);pushup(x);
}
inline void splay(int x,int &k){
s[top=1]=x;for(int i=x;i!=rt;i=fa[i])s[++top]=fa[i];
for(int i=top;i;--i)pushdown(s[i]);
while(x!=k){
int y=fa[x],z=fa[y];
if(y!=k)
if(c[z][0]==y^c[y][0]==x)rotate(x,k);
else rotate(y,k);
rotate(x,k);
}
}
inline void ins(int x,int v,int ww){
if(!rt)rt=x;else fa[x]=rt,c[rt][1]=x;
val[x]=v;w[x]=ww;pushup(x);splay(x,rt);
}
inline int tmax(int x){while(c[x][1])x=c[x][1];return x;}
inline int tmin(int x){while(c[x][0])x=c[x][0];return x;}
inline ll query(int x){
splay(x,rt);return sumv[c[x][0]]+1LL*w[x]*val[x];
}
inline void change(int x,int y){
splay(x,rt);int t1=tmax(c[rt][0]);
splay(x+N,rt);int t2=tmin(c[rt][1]);
splay(t1,rt);splay(t2,c[t1][1]);
int z=c[t2][0];fa[z]=c[t2][0]=0;
splay(y,rt);int t3=tmin(c[y][1]);
splay(t3,c[y][1]);fa[z]=t3;c[t3][0]=z;
}
splay(x,rt);int t1=tmax(c[rt][0]);
splay(x+N,rt);int t2=tmin(c[rt][1]);
splay(t1,rt);splay(t2,c[t1][1]);
puttag(c[t2][0],v);
}
void build(int u,int f){
ins(u+1,a[u],1);
int v=G[i].v;if(v==f)continue;
build(v,u);
}
ins(u+N+1,a[u],-1);
}
int main(){
ins(1,0,0);build(1,0);ins(N*2+1,0,0);