原题树的统计Count
LCT动态维护树信息.比链剖好写但是速度真的没太有优势…
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define LL long long
#define MAXN 50010
#define MAXINT 0x7fffffff
using namespace std;
struct splay
{
int fa,ch[2];
LL sum,maxn,w;
bool rev;
}tree[MAXN];
int q[MAXN],top;
char ch[10];
void print();
long long U,V,n,m,u[MAXN],v[MAXN];
inline void in(long long &x)
{
int flag=1;char ch=getchar();x=0;
while (!(ch>=‘0‘&&ch<=‘9‘)) flag=ch==‘-‘?-1:1,ch=getchar();
while (ch>=‘0‘&&ch<=‘9‘) x=x*10+ch-‘0‘,ch=getchar();x*=flag;
}
inline bool is_root(int x)
{
return tree[tree[x].fa].ch[0]!=x&&tree[tree[x].fa].ch[1]!=x;
}
inline void push_up(int x)
{
tree[x].sum=tree[tree[x].ch[0]].sum+tree[tree[x].ch[1]].sum+tree[x].w;
tree[x].maxn=max(tree[x].w,max(tree[tree[x].ch[0]].maxn,tree[tree[x].ch[1]].maxn));
}
inline void push_down(int x)
{
if (tree[x].rev)
{
tree[x].rev^=1;tree[tree[x].ch[0]].rev^=1;tree[tree[x].ch[1]].rev^=1;
swap(tree[x].ch[0],tree[x].ch[1]);
}
}
inline void rot(int x)
{
int y=tree[x].fa,z=tree[y].fa,l,r;
l=(tree[y].ch[1]==x);r=l^1;
if (!is_root(y)) tree[z].ch[(tree[z].ch[1]==y)]=x;
tree[tree[x].ch[r]].fa=y;tree[y].fa=x;tree[x].fa=z;
tree[y].ch[l]=tree[x].ch[r];tree[x].ch[r]=y;
push_up(y);push_up(x);
}
inline void Splay(int x)
{
q[++top]=x;
for (int i=x;!is_root(i);i=tree[i].fa) q[++top]=tree[i].fa;
while (top) push_down(q[top--]);
while (!is_root(x))
{
int y=tree[x].fa,z=tree[y].fa;
if (!is_root(y))
{
if (tree[y].ch[0]==x^tree[z].ch[0]==y) rot(x);
else rot(y);
}
rot(x);
}
}
inline void access(int x)
{
for (int t=0;x;t=x,x=tree[x].fa) Splay(x),tree[x].ch[1]=t,push_up(x);
}
inline void make_root(int x)
{
access(x);Splay(x);tree[x].rev^=1;
}
inline void link(int x,int y)
{
make_root(x);tree[x].fa=y;
}
inline void cut(int x,int y)
{
make_root(x);access(y);Splay(y);
}
int main()
{
in(n);tree[0].maxn=-MAXINT;
for (int i=1;i<n;i++) in(u[i]),in(v[i]);
for (int i=1;i<=n;i++) in(tree[i].w),tree[i].sum=tree[i].maxn=tree[i].w;
for (int i=1;i<n;i++) link(u[i],v[i]);
in(m);
while (m--)
{
scanf("%s",ch);in(U);in(V);
if (ch[1]==‘H‘) Splay(U),tree[U].w=V,push_up(U);
if (ch[1]==‘M‘) cut(U,V),printf("%lld\n",tree[V].maxn);
if (ch[1]==‘S‘) cut(U,V),printf("%lld\n",tree[V].sum);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-15 08:43:05