hdu 4010

来源:互联网 发布:范磊c语言 编辑:程序博客网 时间:2024/06/07 04:52
#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#define N 300003using namespace std;int fa[N],ch[N][3],size[N],key[N],maxn[N],rev[N],delta[N];int x[N],y[N],n,m;bool isroot(int x){return ch[fa[x]][1]!=x&&ch[fa[x]][0]!=x;}int get(int x){return ch[fa[x]][1]==x;}void pushdown(int x){if (rev[x]){rev[ch[x][0]]^=1;rev[ch[x][1]]^=1;rev[x]=0;swap(ch[x][0],ch[x][1]);    }    if (delta[x])    {    key[x]+=delta[x];    delta[ch[x][0]]+=delta[x];    delta[ch[x][1]]+=delta[x];    }}void update(int x){int t=max(maxn[ch[x][0]],maxn[ch[x][1]]);maxn[x]=max(t,key[x]);}void rotate(int x){int y=fa[x]; int z=fa[y]; int which=get(x);if (!isroot(y)) ch[z][ch[z][1]==y]=x;ch[y][which]=ch[x][which^1]; fa[ch[y][which]]=y;ch[x][which^1]=y; fa[y]=x; fa[x]=z;update(y); update(x);}void splay(int x){int top=0,st[N]; st[++top]=x;for (int i=x;!isroot(i);i=fa[i]) st[++top]=fa[x];for (int i=top;i>=1;i--) pushdown(st[i]);while(!isroot(x)){int y=fa[x];if (!isroot(y)) rotate(get(y)==get(x)?y:x);rotate(x);}}void access(int x){int t=0;while (x){splay(x);ch[x][1]=t;t=x; x=fa[x];}}void rever(int x){access(x); splay(x); rev[x]^=1;}void link(int x,int y){rever(x); fa[x]=y;}int  cut(int x,int y){rever(x); access(y); splay(y);if (ch[y][0]!=x) return -1;ch[y][0]=fa[x]=0;return 1;}int find(int x){access(x); splay(x);int now=x;while (ch[now][0]) now=ch[now][0];return now;}int main(){scanf("%d",&n);for (int i=1;i<=n-1;i++)  scanf("%d%d",&x[i],&y[i]);for (int i=1;i<=n;i++) { scanf("%d",&key[i]); maxn[i]=key[i];    }    for (int i=1;i<n;i++)     link(x[i],y[i]);scanf("%d",&m);for (int i=1;i<=m;i++){int op,x,y;scanf("%d%d%d",&op,&x,&y);if (op==1) {if (find(x)==find(y)){printf("-1\n");continue;}    link(x,y);}if (op==2) {if (x==y||find(x)!=find(y)){printf("-1\n");continue;}    cut(x,y);    }if (op==3) {int k; scanf("%d",&k);if (find(x)!=find(y)) { printf("-1\n"); continue; }rever(x); access(y); splay(y);key[y]+=k;delta[ch[y][0]]+=k;}if (op==4){if (find(x)!=find(y)){printf("-1\n");continue;}rever(x); access(y); splay(y);printf("%d\n",max(maxn[ch[y][0]],key[y]));} }}

0 0