link-cut-tree

dfs:

struct bian
{
    int nex,nex_node;
    bian(int x=0,int y=0):
        nex(x),nex_node(y) {}
} edge[1000005];

int head[500005],edge_num=0;

void add_edge(int now,int nex)
{
    edge[edge_num]=bian(nex,head[now]);
    head[now]=edge_num++;
}

int path_pre[500005];

void dfs(int x,int fa)
{
    path_pre[x]=fa;
    for(int i=head[x]; ~i; i=edge[i].nex_node)
    {
        int nex=edge[i].nex;
        if(nex==fa)continue;
        dfs(nex,x);
    }
}

splay:

#define ls(x) tree[x].lson
#define rs(x) tree[x].rson
#define fa(x) tree[x].pre
#define grafa(x) tree[tree[x].pre].pre

struct node
{
    int pre,lson,rson;
    int val,siz;
    node(int pre=-1,int lson=-1,int rson=-1,
         int val=0,int siz=0):
        pre(pre),lson(lson),rson(rson),
        val(val),siz(siz) {}
} tree[500005];

void pushup(int x)
{
    tree[x].siz=1;
    if(~ls(x))
        tree[x].siz+=tree[ls(x)].siz;
    if(~rs(x))
        tree[x].siz+=tree[rs(x)].siz;
}

void zig(int x)
{
    int y=fa(x);
    if(~fa(y))
        if(ls(fa(y))==y)
            ls(fa(y))=x;
        else rs(fa(y))=x;
    fa(x)=fa(y),fa(y)=x;
    ls(y)=rs(x);
    if(~ls(y))fa(ls(y))=y;
    rs(x)=y;
    pushup(y),pushup(x);
}

void zag(int x)
{
    int y=fa(x);
    if(~fa(y))
        if(ls(fa(y))==y)
            ls(fa(y))=x;
        else rs(fa(y))=x;
    fa(x)=fa(y),fa(y)=x;
    rs(y)=ls(x);
    if(~rs(y))fa(rs(y))=y;
    ls(x)=y;
    pushup(y),pushup(x);
}

void splay(int x,int wz=-1)
{
    while(x!=wz && fa(x)!=wz)
        if(grafa(x)==wz)
            if(ls(fa(x))==x)zig(x);
            else zag(x);
        else if(ls(fa(x))==x && ls(grafa(x))==fa(x))
            zig(fa(x)),zig(x);
        else if(rs(fa(x))==x && rs(grafa(x))==fa(x))
            zag(fa(x)),zag(x);
        else if(ls(fa(x))==x && rs(grafa(x))==fa(x))
            zig(x),zag(x);
        else if(rs(fa(x))==x && ls(grafa(x))==fa(x))
            zag(x),zig(x);
}

access:

int aux_root(int x)
{
    while(~ls(x))x=ls(x);
    return x;
}

int access(int x)
{
    int deper=-1;
    while(~x)
    {
        splay(x);
        fa(rs(x))=-1;
        rs(x)=deper;
        pushup(x);
        if(~deper)fa(deper)=x;
        deper=x;
        x=path_pre[aux_root(x)];
    }
    return deper;
}

lca:

int lca(int x,int y)
{
    access(x);
    return access(y);
}

你可能感兴趣的:(link-cut-tree)