


2 0 1 5 QUERY 1 QUERY 2 MOVE 2 0 MOVE 1 2 QUERY 1 6 0 6 4 6 1 0 4 MOVE 4 1 QUERY 3 MOVE 1 4 QUERY 1
1 1 2 1 1
Problem : 2475 ( Box )     Judge Status : Accepted
RunId : 14537757    Language : C++    Author : lwj1994
Code Render Status : Rendered By HDOJ C++ Code Render Version 0.01 Beta
#include<stdio.h>
#include<string.h>
struct LCT
{
    int bef[50050],pre[50050],next[50050][2];
    void init()
    {
        memset(pre,0,sizeof(pre));
        memset(next,0,sizeof(next));
    }
    void rotate(int x,int kind)
    {
        int y,z;
        y=pre[x];
        z=pre[y];
        next[y][!kind]=next[x][kind];
        pre[next[x][kind]]=y;
        next[z][next[z][1]==y]=x;
        pre[x]=z;
        next[x][kind]=y;
        pre[y]=x;
    }
    void splay(int x)
    {
        int rt;
        for(rt=x;pre[rt];rt=pre[rt]);
        if(x!=rt)
        {
            bef[x]=bef[rt];
            bef[rt]=0;
            while(pre[x])
            {
                if(next[pre[x]][0]==x)
                {
                    rotate(x,1);
                }
                else
                    rotate(x,0);
            }
        }
    }
    void access(int x)
    {
        int fa;
        for(fa=0;x;x=bef[x])
        {
            splay(x);
            pre[next[x][1]]=0;
            bef[next[x][1]]=x;
            next[x][1]=fa;
            pre[fa]=x;
            bef[fa]=0;
            fa=x;
        }
    }
    int query(int x)
    {
        access(x);
        splay(x);
        while(next[x][0])
            x=next[x][0];
        return x;
    }
    void cut(int x)
    {
        access(x);
        splay(x);
        bef[next[x][0]]=bef[x];
        bef[x]=0;
        pre[next[x][0]]=0;
        next[x][0]=0;
    }
    void join(int x,int y)
    {
        if(y==0)
            cut(x);
        else
        {
            int tmp;
            access(y);
            splay(y);
            for(tmp=x;pre[tmp];tmp=pre[tmp]);
            if(tmp!=y)
            {
                cut(x);
                bef[x]=y;
            }
        }
    }
}lct;
int main()
{
    int n,flag=0;
    while(scanf("%d",&n)!=EOF)
    {
        int i;
        if(flag)
            printf("\n");
        else
            flag=1;
        for(i=1;i<=n;i++)
        {
            int x;
            scanf("%d",&x);
            lct.bef[i]=x;
        }
        int q;
        lct.init();
        scanf("%d",&q);
        while(q--)
        {
            char str[10];
            scanf("%s",str);
            if(str[0]=='Q')
            {
                int x;
                scanf("%d",&x);
                printf("%d\n",lct.query(x));
            }
            else
            {
                int x,y;
                scanf("%d%d",&x,&y);
                lct.join(x,y);
            }
        }
    }
}版权声明:本文为博主原创文章,未经博主允许不得转载。
HDOJ 题目2475 Box(link cut tree去点找祖先)
原文:http://blog.csdn.net/yu_ch_sh/article/details/47720579