[BZOJ2761][JLOI2011]不重复数字(splay)

211 篇文章 0 订阅
33 篇文章 0 订阅

题目描述

传送门

题解

练习平衡树

代码

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
#define N 50005

int T,n,x,root,sz;
bool flag;
int f[N],ch[N][2],key[N];

void clear()
{
    flag=false;
    root=sz=x=0;
    memset(f,0,sizeof(f));memset(ch,0,sizeof(ch));memset(key,0,sizeof(key));
}
int get(int x)
{
    return ch[f[x]][1]==x;
}
void rotate(int x)
{
    int old=f[x],oldf=f[old],wh=get(x);
    ch[old][wh]=ch[x][wh^1];
    f[ch[old][wh]]=old;
    ch[x][wh^1]=old;
    f[old]=x;
    if (oldf) ch[oldf][ch[oldf][1]==old]=x;
    f[x]=oldf;
}
void splay(int x)
{
    for (int fa;fa=f[x];rotate(x))
        if (f[fa])
            rotate( (get(x)==get(fa))?fa:x );
    root=x;
}
bool insert(int x)
{
    if (!root)
    {
        root=++sz;
        key[sz]=x;
        return true;
    }
    int now=root,fa=0;
    while (1)
    {
        if (x==key[now])
        {
            splay(now);
            return false;
        }
        fa=now;
        now=ch[now][x>key[now]];
        if (!now)
        {
            ++sz;
            f[sz]=fa;ch[fa][x>key[fa]]=sz;
            key[sz]=x;
            splay(sz);
            return true;
        }
    }
}
int main()
{
    scanf("%d",&T);
    while (T--)
    {
        clear();
        scanf("%d",&n);
        for (int i=1;i<=n;++i)
        {
            scanf("%d",&x);
            if (insert(x))
            {
                if (flag) putchar(' ');
                printf("%d",x);
                flag=true;
            }
        }
        putchar('\n');
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值