#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<algorithm>
using namespace std;
const int MAXN = 100000 + 55;
int L[MAXN], R[MAXN], F[MAXN];
int tre[MAXN];
int tot, root;
inline void clear()
{
memset(L, -1, sizeof(L));
memset(R, -1, sizeof(R));
memset(F, -1, sizeof(F));
tot = root = 0;
}
void insert(int t, int x)
{
if (tot == 0)
{
root = ++tot;
tre[root] = x;
F[root] = root;
return;
}
if (x >= tre[t])
{
if (R[t] > 0)
{
insert(R[t], x);
}
else
{
R[t] = ++tot;
tre[R[t]] = x;
F[R[t]] = t;
}
}
else
{
if (L[t] > 0)
{
insert(L[t], x);
}
else
{
L[t] = ++tot;
tre[L[t]] = x;
F[L[t]] = t;
}
}
}
void rotate(int x)
{
if (F[x] == x)
return;
int fa = F[x];
int zu = F[F[x]];
if (R[fa] == x)//是右
{
R[fa] = L[x];
F[L[x]] = fa;
L[x] = fa;
F[fa] = x;
if (zu != fa)//父亲not是root
{
if (fa == R[zu])
R[zu] = x;
else
L[zu] = x;
F[x] = zu;
}
else
{
F[x] = x;
root = x;
}
}
else
{
L[fa] = R[x];
F[R[x]] = fa;
R[x] = fa;
F[fa] = x;
if (zu != fa)//父亲not是Loot
{
if (fa == L[zu])
L[zu] = x;
else
R[zu] = x;
F[x] = zu;
}
else
{
F[x] = x;
root = x;
}
}
}
void output(int t)
{
if (L[t] > 0)
{
output(L[t]);
}
if (t != 0)
printf("%d\n", tre[t]);
if (R[t] > 0)
{
output(R[t]);
}
}
int find(int t,int x)
{
if (x == tre[t])
return t;
if (R[t]>0 &&x > tre[t])
return find(R[t], x);
return find(L[t], x);
}
void splay(int x)
{
while (x != root)
{
rotate(x);
}
}
void delete_splay(int t, int x)
{
splay(find(t,x));
int del = root;
if (L[del] > 0 && R[del] > 0)
{
int temp = R[del];
root = R[del];
while (L[temp]>0)
{
temp = L[temp];
}
L[temp] = L[del];
F[L[del]] = temp;
F[root] = root;
tre[del] = 0;
L[del] = R[del] = F[del] = -1;
return;
}
else
{
if (L[root] > 0)
{
root = L[root];
F[root] = root;tre[del] = 0;
L[del] = R[del] = F[del] = -1;
return;
}
else if(R[root]>0)
{
root = R[root];
F[root] = root;tre[del] = 0;
L[del] = R[del] = F[del] = -1;
}
else
{
clear();
}
}
}
int main()
{
clear();
int n;
scanf("%d", &n);
tot = 0;
root = 0;
for (int i = 0; i < n; i++)
{
int a;
scanf("%d", &a);
insert(root, a);
splay(tot);
}
delete_splay(root, 2);
output(root);
}
/*
9
1 2 4 3 7 6 5 9 8
*/
splay
最新推荐文章于 2021-09-06 14:49:50 发布