4530: [Bjoi2014]大融合

题目链接

题目大意:一棵树,动态加边,询问经过一条边的路径条数

题解:LCT 维护子树信息

我的收获:2333

#include 
using namespace std;

#define ls c[x][0]
#define rs c[x][1]

const int N=1e5+10;

int n,q;
int c[N][2],fa[N],size[N],sum[N],stk[N];
bool rev[N];

bool f(int x){return c[fa[x]][1]==x;}
bool isr(int x){return c[fa[x]][0]!=x&&c[fa[x]][1]!=x;}
void update(int x){sum[x]=sum[ls]+sum[rs]+size[x]+1;}
void reverse(int x){if(!x) return ;swap(ls,rs);rev[x]^=1;}
void pushdown(int x){if(!rev[x]) return ;reverse(ls);reverse(rs);rev[x]=0;}

void rotate(int x){
    int y = fa[x], z = fa[y], k =f(x);
    if(!isr(y)) c[z][f(y)] = x; fa[x] = z;
    c[y][k] = c[x][!k]; fa[c[y][k]] = y;
    c[x][!k] = y; fa[y] = x; update(y);
}

void maintain(int x)
{
    int top=0;stk[++top]=x;
    for(;!isr(x);x=fa[x]) stk[++top]=fa[x];
    while(top) pushdown(stk[top--]);
}

void splay(int x)
{
    maintain(x);
    for(;!isr(x);rotate(x))
        if(!isr(fa[x])) rotate(f(x)==f(fa[x])?fa[x]:x);
    update(x);
}

void access(int x){for(int y=0;x;y=x,x=fa[x]) splay(x),size[x]+=sum[c[x][1]]-sum[y],c[x][1]=y,update(x);}
void mkrt(int x){access(x);splay(x);reverse(x);}
void link(int x,int y){mkrt(x);mkrt(y);fa[x]=y;size[y]+=sum[x];update(y);}
void cut(int x,int y){mkrt(x);access(y);splay(y);}

void work()
{
    char opt[5];int x,y;
    while(q--){
        scanf("%s%d%d",opt,&x,&y);
        if(opt[0]=='A') link(x,y);
        else cut(x,y),printf("%lld\n",1ll*sum[x]*(sum[y]-sum[x]));
    }
}

void init()
{
    scanf("%d%d",&n,&q);
}

int main()
{
    init();
    work();
    return 0;
}

你可能感兴趣的:(4501-4750)