Ural1553.Caves and Tunnels

水题一道……动态维护树链上的最大点权,动态树水过……

wa了几次……因为没看清楚题……点权的修改是在原来的点权基础之上的……

点数过多,不能用DFS建图


//Lib
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<ctime>

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<queue>
using namespace std;
//Macro
#define rep(i,a,b) for(int i=a,tt=b;i<=tt;++i)
#define rrep(i,a,b) for(int i=a,tt=b;i>=tt;--i)
#define erep(i,e,x) for(int i=x;i;i=e[i].next)
#define irep(i,x) for(__typedef(x.begin()) i=x.begin();i!=x.end();i++)
#define read() (strtol(ipos,&ipos,10))
#define sqr(x) ((x)*(x))
#define pb push_back
#define PS system("pause");
typedef long long ll;
typedef pair<int,int> pii;
const int oo=100000000;
const double inf=1e20;
const double eps=1e-6;
string name="",in=".in",out=".out";
//Var
struct T
{
	int LC,RC,FA,KEY,MAX;
	#define lc(x) tree[x].LC
	#define rc(x) tree[x].RC
	#define fa(x) tree[x].FA
	#define key(x) tree[x].KEY
	#define Max(x) tree[x].MAX
}tree[100008];
struct E
{
	int next,node;
}e[200008];
queue<int> q;
int n,Q,tot,h[100008];
bool vis[100008];
bool isRoot(int x){return lc(fa(x))!=x&&rc(fa(x))!=x;}
inline void Update(int x){Max(x)=max(key(x),max(Max(lc(x)),Max(rc(x))));}
void Zig(int x)
{
	int y=fa(x),z=fa(y);
	if(lc(z)==y)lc(z)=x;else if(rc(z)==y)rc(z)=x;fa(x)=z;
	fa(rc(x))=y;lc(y)=rc(x);fa(y)=x;rc(x)=y;
	Update(y);
}
void Zag(int x)
{
	int y=fa(x),z=fa(y);
	if(lc(z)==y)lc(z)=x;else if(rc(z)==y)rc(z)=x;fa(x)=z;
	fa(lc(x))=y;rc(y)=lc(x);fa(y)=x;lc(x)=y;
	Update(y);
}
void Splay(int x)
{
	for(int y,z;!isRoot(x);)
	{
		y=fa(x);z=fa(y);
		if(isRoot(y))
			if(lc(y)==x)Zig(x);
			else Zag(x);
		else
			if(lc(z)==y)
				if(lc(y)==x)Zig(y),Zig(x);
				else Zag(x),Zig(x);
			else
				if(rc(y)==x)Zag(y),Zag(x);
				else Zig(x),Zag(x);
	}
}
void Expose(int x)
{
	for(int y=0;x;x=fa(x)){Splay(x);rc(x)=y;Update(x);y=x;}
}
void Build()
{
	q.push(1);vis[1]=true;int x,y;
	while(!q.empty())
	{
		x=q.front();q.pop();
		erep(i,e,h[x])
		{
			y=e[i].node;
			if(vis[y])continue;
			q.push(y);vis[y]=true;fa(y)=x;
		}
	}
}
void add(int a,int b){e[++tot].next=h[a];e[tot].node=b;h[a]=tot;}
void Init()
{
	int a,b;
	scanf("%d",&n);
	rep(i,1,n-1)scanf("%d%d",&a,&b),add(a,b),add(b,a);
	Build();
}
void Change(int x,int y){key(x)+=y;Splay(x);}
int Query(int x,int y)
{
	Expose(y);
	for(y=0;x;x=fa(x))
	{
		Splay(x);
		if(!fa(x))return max(Max(rc(x)),max(Max(y),key(x)));
		rc(x)=y;Update(x);y=x;
	}
}
void Work()
{
	char ch[10];int a,b;
	key(0)=Max(0)=-oo;
	scanf("%d",&Q);
	rep(i,1,Q)
	{
		scanf("%s%d%d",ch,&a,&b);
		if(ch[0]=='I')Change(a,b);
		else printf("%d\n",Query(a,b));
	}
	
}
int main()
{
//	freopen((name+in).c_str(),"r",stdin);
//	freopen((name+out).c_str(),"w",stdout);
	Init();
	Work();
	return 0;
}


你可能感兴趣的:(Ural1553.Caves and Tunnels)