treap

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<iostream>
#define MAXMOD 999983
#define maxn 1111111
using namespace std;
int n,m,v,root,tot,a[maxn],l[maxn],r[maxn],data[maxn],num[maxn];
int RR(int x)
{
    int y=l[x];
    l[x]=r[y];
    r[y]=x;
    return y;
}
int LR(int x)
{
    int y=r[x];
    r[x]=l[y];
    l[y]=x;
    return y;
}
int insert(int root,int key)
{
     if (!(root+1))
     {
         num[tot++]=rand()%MAXMOD;
         data[tot]=key;
         l[tot]=r[tot]=-1;         
         return tot;
     }
     if (key<data[root])
     {
         l[root]=insert(l[root],key);
         if (num[l[root]]>num[root]) root=RR(root);         
     }
     else
     {
         r[root]=insert(r[root],key);
         if (num[r[root]]>num[root]) root=LR(root);         
     }
     return root;
}
int delete1(int root,int key)
{
    if (key<data[root]) { l[root]=delete1(l[root],key); return root; }
       else if (key>data[root]) { r[root]=delete1(r[root],key); return root; }
               else {
                         if (l[root]==-1 && r[root]==-1) return -1;
                         if (l[root]!=-1 && (r[root]!=-1 && num[l[root]]>num[r[root]] || r[root]==-1)) 
                         {
                             root=RR(root);
                             r[root]=delete1(r[root],key);
                             return root;
                         }
                         if (r[root]!=-1 && (l[root]!=-1 && num[r[root]]>num[l[root]] || l[root]==-1))
                         {
                             root=LR(root);
                             l[root]=delete1(l[root],key);
                             return root;                            
                         }
                    }
}
void dfs(int x)
{
     if (l[x]+1) dfs(l[x]);
     printf("%d ",data[x]);
     if (r[x]+1) dfs(r[x]);
}
int main()
{
    freopen("1.in","r",stdin);
    freopen("1.out","w",stdout);
    srand(time(0));
    scanf("%d",&n);
    for (int i=0;i<n;i++) l[i]=r[i]=-1;    
    root=-1;
    for (int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
        root=insert(root,a[i]);
    }
    dfs(root);
    cout<<"\n";
    scanf("%d",&m);
    for (int i=0;i<m;i++) { scanf("%d",&v); root=delete1(root,v); dfs(root); cout<<"\n"; }
    dfs(root);
    return 0;
}

 

转载于:https://www.cnblogs.com/strawberryfgalois/p/4091916.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值