啥都干不了的Treap,没有多大实用性,主要是用来理解Treap的
至于平衡树的建立的过程以及为啥么这么写,等我有时间再写吧
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <queue>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;
struct tree{
int val;//值
int lt,rt;//左右节点
int sum;//堆性质数据域
int fat;//父节点
};
tree st[999999];
int tot;
int root;
void left_rotation(int x)
{
if(root==st[x].fat)
root=x;
int fafat=st[st[x].fat].fat;
st[st[x].fat].fat=x;
if(fafat)
{
if(st[fafat].lt==st[x].fat)
st[fafat].lt=x;
else
st[fafat].rt=x;
}
if(st[x].lt)
st[st[x].lt].fat=st[x].fat,st[st[x].fat].rt=st[x].lt;
st[x].fat=fafat;
}
void right_rotation(int x)
{
if(root==st[x].fat)
root=x;
int fafat=st[st[x].fat].fat;
st[st[x].fat].fat=x;
if(fafat)
{
if(st[fafat].lt==st[x].fat)
st[fafat].lt=x;
else
st[fafat].rt=x;
}
if(st[x].rt)
st[st[x].rt].fat=st[x].fat,st[st[x].fat].lt=st[x].rt;
st[x].fat=fafat;
}
int find_table(int x)
{
int now=root;
while(now)
{
if(st[now].val==x)
return now;
if(x<st[now].val)
{
now=st[now].lt;
continue;
}
if(x>st[now].val)
{
now=st[now].rt;
continue;
}
}
return 0;
}
void del(int t)
{
int x=find_table(t);
while(st[x].lt||st[x].rt)
{
if(st[x].lt&&!st[x].rt)
{
right_rotation(st[x].lt);
continue;
}
if(st[x].rt&&!st[x].lt)
{
left_rotation(st[x].rt);
continue;
}
if(st[x].lt&&st[x].rt)
{
if(st[st[x].lt].sum<st[st[x].rt].sum)
right_rotation(st[x].lt);
else
left_rotation(st[x].rt);
}
}
if(st[x].fat)
{
if(st[st[x].fat].lt==x)
st[st[x].fat].lt=0;
else
st[st[x].fat].rt=0;
}
return;
}
void insert(int ans)
{
tot++;
st[tot].val=ans;
st[tot].sum=rand();
if(tot==1)
{
root=tot;
return;
}
int now=root;
int pre=root;
while(now)
{
if(ans<st[now].val)
{
pre=now;
now=st[now].lt;
}
if(ans>st[now].val)
{
pre=now;
now=st[now].rt;
}
}
if(ans>st[pre].val)
st[pre].rt=tot;
if(ans<st[pre].val)
st[pre].lt=tot;
st[tot].fat=pre;
while(st[tot].sum<st[st[tot].fat].sum)
{
if(tot==st[st[tot].fat].rt)
left_rotation(tot);
else
right_rotation(tot);
}
return;
}
int main()
{
srand(1e7);
int n;
scanf("%d",&n);
for(int i=1,x;i<=n;i++)
scanf("%d",&x),insert(x);
return 0;
}