bzoj 2733 [HNOI2012]永无乡 splay启发式合并

splay启发式合并

#include <bits/stdc++.h>
using namespace std;
#define N 110000
#define which(x) (ch[fa[x]][1]==x)
int n,m,Q;
char s[11];
int ft[N],root[N],val[N];
int fa[N],ch[N][2],size[N];
int find(int x){return ft[x]==x ? x:ft[x]=find(ft[x]);}
void pushup(int x)
{size[x]=size[ch[x][0]]+size[ch[x][1]]+1;}
void rotate(int x)
{
    int y=fa[x],k=which(x);
    ch[y][k]=ch[x][k^1];
    ch[fa[y]][which(y)]=x;
    ch[x][k^1]=y;

    fa[x]=fa[y];fa[y]=x;
    fa[ch[y][k]]=y;

    pushup(y);pushup(x);
}
void splay(int x)
{
    while(fa[x])
    {
        int y=fa[x];
        if(!fa[y])rotate(x);
        else 
        {
            if(which(x)^which(y))
                rotate(x);
            else rotate(y);
            rotate(x);
        }
    }   
    root[find(x)]=x;
}
void insert(int x,int y)
{
    ch[x][0]=ch[x][1]=0;size[x]=1;
    while(1)
    {
        if(val[x]<val[y])
        {
            if(!ch[y][0])
                {fa[x]=y,ch[y][0]=x;size[y]++;break;}
            y=ch[y][0];
        }
        else
        {
            if(!ch[y][1])
                {fa[x]=y,ch[y][1]=x;size[y]++;break;}
            y=ch[y][1];
        }
    }
    splay(x);
}
void dfs(int x,int y)
{
    if(!x)return;
    dfs(ch[x][0],y);
    dfs(ch[x][1],y);
    insert(x,root[y]);
}
void merge(int x,int y)
{
    x=find(x);y=find(y);
    if(x==y)return;
    ft[x]=y;
    dfs(root[x],y);
}
int find(int x,int K)
{
    if(size[ch[x][0]]+1==K)
        return x;
    if(size[ch[x][0]]>=K)
        return find(ch[x][0],K);
    return find(ch[x][1],K-size[ch[x][0]]-1);
}
int main()
{
    //freopen("tt.in","r",stdin);
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)scanf("%d",&val[i]);
    for(int i=1;i<=n;i++)
        ft[i]=i,root[i]=i,size[i]=1;
    for(int i=1,x,y;i<=m;i++)
    {
        scanf("%d%d",&x,&y);
        merge(x,y);
    }
    scanf("%d",&Q);
    for(int x,y,K;Q--;)
    {
        scanf("%s",s+1);
        if(s[1]=='B')
        {
            scanf("%d%d",&x,&y);
            merge(x,y);
        }
        else 
        {
            scanf("%d%d",&x,&K);
            splay(x);
            if(size[x]<K){puts("-1");continue;}
            printf("%d\n",find(x,K));
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值