hdu 4010

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define N 300003
using 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值