bzoj 4530 [BJOI2014]大融合 (LCT)

题目大意:给你一棵树,树的边是一条一条连上去的

洛谷P4219传送门 LOJ#2230传送门

在连边的过程中询问某条边的“负载”,即能通过这条边的所有不同的路径的数量

LCT动态维护当前节点的子树大小

size记录该节点的虚子树的大小之和,sum记录该节点为根节点的子树大小

更换虚子节点时,或者连上新的虚子树时,即access和link操作,要注意更新size

#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 100100
#define il inline 
using namespace std;

int n,m,tp;
int stk[N];
struct LinkCutTree{
    int fa[N],ch[N][2],rv[N],sz[N],sum[N];
    il int idf(int x){return ch[fa[x]][0]==x?0:1;}
    il void con(int x,int ff,int p){fa[x]=ff,ch[ff][p]=x;}
    il void rev(int x){swap(ch[x][0],ch[x][1]),rv[x]^=1;}
    il int isroot(int x){return (ch[fa[x]][0]!=x&&ch[fa[x]][1]!=x)?1:0;}
    il void pushup(int x){sum[x]=sum[ch[x][0]]+sum[ch[x][1]]+sz[x]+1;}
    il void pushdown(int x)
    {
        if(rv[x]){
            if(ch[x][0]) rev(ch[x][0]);
            if(ch[x][1]) rev(ch[x][1]);
            rv[x]=0;
        }
    }
    il void rot(int x)
    {
        int y=fa[x],ff=fa[y],px=idf(x),py=idf(y);
        if(!isroot(y))ch[ff][py]=x;fa[x]=ff;
        ch[y][px]=ch[x][px^1],fa[ch[x][px^1]]=y;
        ch[x][px^1]=y,fa[y]=x;
        pushup(y),pushup(x);
    }
    il void splay(int x)
    {
        int y=x;stk[++tp]=x;
        while(!isroot(y)){stk[++tp]=fa[y],y=fa[y];}
        while(tp){pushdown(stk[tp--]);}
        while(!isroot(x)){y=fa[x];
            if(isroot(y)) rot(x);
            else if(idf(y)==idf(x)) rot(y),rot(x);
            else rot(x),rot(x);}
        pushup(x);
    }
    il void access(int x)
    {
        for(int y=0;x!=0;y=x,x=fa[x])
        {
            splay(x);
            sz[x]-=sum[y];
            sz[x]+=sum[ch[x][1]];
            ch[x][1]=y,pushup(x);
        }
    }
    il void mkroot(int x){access(x),splay(x),rev(x);}
    il void split(int x,int y){mkroot(y),access(x),splay(x);}
    il void link(int x,int y){split(x,y),fa[y]=x,sz[x]+=sum[y],pushup(x);}
}lct;
int gint()
{
    int rett=0,fh=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')fh=-1;c=getchar();}
    while(c>='0'&&c<='9'){rett=(rett<<3)+(rett<<1)+c-'0';c=getchar();}
    return rett*fh;
}
void gchar(char str[])
{
    int num=0;char c=getchar();
    while(c<'A'||c>'Z'){c=getchar();}
    while(c>='A'&&c<='Z'){str[num++]=c;c=getchar();}
    str[num]='\0';
}

int main()
{
    n=gint(),m=gint();
    char q[5];int x,y;
    for(int i=1;i<=m;i++)
    {
        gchar(q),x=gint(),y=gint();
        if(q[0]=='A'){lct.link(x,y);}
        if(q[0]=='Q'){lct.split(x,y);
        printf("%lld\n",1ll*(lct.sum[y])*(lct.sum[x]-lct.sum[y]));}
    }
    return 0;
}


调了半天发现LCT板子敲错了...

猜你喜欢

转载自blog.csdn.net/guapisolo/article/details/82707788
今日推荐