LCT——模板整理

来源:互联网 发布:js省市区三级联动插件 编辑:程序博客网 时间:2024/05/01 09:16

LCT动态树。用于维护森林,支持加边删边和查询链上信息等操作。
时间复杂度O(log2n)

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;typedef long long LL;const LL maxn=50010, INF=0x7fffffff;struct node{    LL fa,ch[2],w,sum,_max;    bool rev;} T[maxn];int q[maxn],top;inline void maintain(int x){    T[x].sum=T[T[x].ch[0]].sum+T[T[x].ch[1]].sum+T[x].w;    T[x]._max=max(T[x].w,max(T[T[x].ch[0]]._max,T[T[x].ch[1]]._max));}inline bool is_root(int x){    return T[T[x].fa].ch[0]!=x&&T[T[x].fa].ch[1]!=x;}inline void pushdown(int x){    if(!T[x].rev) return;    T[T[x].ch[0]].rev^=1; T[T[x].ch[1]].rev^=1;    swap(T[x].ch[0],T[x].ch[1]);    T[x].rev=0;}void rot(int k){    int p=T[k].fa, d=(T[p].ch[1]==k)^1, t=T[p].fa;    if(!is_root(p)) T[t].ch[T[t].ch[1]==p]=k;    T[p].ch[d^1]=T[k].ch[d]; T[T[k].ch[d]].fa=p;    T[k].ch[d]=p; T[p].fa=k;     maintain(p); maintain(k); T[k].fa=t;}void Splay(int x){    q[++top]=x;    for (int i=x;!is_root(i);i=T[i].fa) q[++top]=T[i].fa;    while(top) pushdown(q[top--]);    while(!is_root(x)){        int y=T[x].fa, z=T[y].fa, d1=T[y].ch[1]==x, d2=T[z].ch[1]==y;        if(!is_root(y)){            if(d1==d2) rot(y), rot(x);                  else rot(x), rot(x);        } else rot(x);    }}inline void access(int x){    for(int t=0;x;t=x,x=T[x].fa) Splay(x), T[x].ch[1]=t, maintain(x);}inline void make_root(int x){    access(x); Splay(x); T[x].rev^=1;}inline void link(int x,int y){    make_root(x); T[x].fa=y;}inline void cut(int x,int y){    make_root(x); access(y); Splay(y);}inline LL getint(){    LL res=0,ff=1; char ch=getchar();    while(!('0'<=ch&&ch<='9')){ if(ch=='-') ff=-1; ch=getchar(); }    while('0'<=ch&&ch<='9') res=res*10+ch-'0', ch=getchar();    return res*ff;}char ch[10];long long n,m,u[maxn],v[maxn];int main(){    freopen("lct.in","r",stdin);    freopen("lct.out","w",stdout);    n=getint(); T[0]._max=-INF;    for(int i=1;i<=n-1;i++) u[i]=getint(), v[i]=getint();    for(int i=1;i<=n;i++) T[i].w=getint(), T[i].sum=T[i]._max=T[i].w;    for(int i=1;i<=n-1;i++) link(u[i],v[i]);    m=getint();    while(m--){        scanf("%s",ch); int x=getint(), y=getint();        if (ch[1]=='H') Splay(x), T[x].w=y, maintain(x);        if (ch[1]=='M') cut(x,y), printf("%lld\n",T[y]._max);        if (ch[1]=='S') cut(x,y), printf("%lld\n",T[y].sum);    }    return 0;}
0 0
原创粉丝点击