洛谷 P3369【模板】普通平衡树(Treap/SBT)

题目

https://www.luogu.org/problemnew/show/P3369

题意

splay的基本操作

题解

https://blog.csdn.net/qq_30974369/article/details/77587168

把链接中的模板拿来用就好,先插入INF和-INF作为边界,那模板功能不全,我又添加了MinTh函数和KTh函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include <stdio.h>

struct node
{
int ch[2];
int ff,cnt,sz,val;
};
const int MAXN = 1e5+10;
const int INF = 1e8+10;
int root,n,tot;
node t[MAXN];

void PushUp(int x)
{
t[x].sz = t[t[x].ch[0]].sz + t[t[x].ch[1]].sz + t[x].cnt;
}

void Rotate(int x)
{
int y = t[x].ff;
int z = t[y].ff;
int k = (t[y].ch[1]==x);

t[z].ch[t[z].ch[1]==y]=x;
t[x].ff = z;
t[y].ch[k] = t[x].ch[k^1];
t[t[x].ch[k^1]].ff = y;
t[x].ch[k^1] = y;
t[y].ff = x;

PushUp(y);
PushUp(x);
}

void Splay(int x, int goal)
{
while(t[x].ff != goal)
{
int y = t[x].ff;
int z = t[y].ff;
if(z != goal)
(t[z].ch[0]==y)^(t[y].ch[0]==x)?Rotate(x):Rotate(y);
Rotate(x);
}
if(goal == 0) root = x;
}

void Find(int x)
{
int u = root;
if(!u) return;
while(t[u].ch[x > t[u].val] && x != t[u].val)
u = t[u].ch[x > t[u].val];
Splay(u, 0);
}

void Insert(int x)
{
int u = root, ff = 0;
while(u && t[u].val != x)
{
ff = u;
t[u].sz++;
u = t[u].ch[x > t[u].val];
}
if(u) t[u].cnt++, t[u].sz++;
else
{
u = ++tot;
if(ff) t[ff].ch[x > t[ff].val] = u;
t[u].ch[0] = t[u].ch[1] = 0;
t[tot].ff = ff;
t[tot].val = x;
t[tot].cnt = 1;
t[tot].sz = 1;
}
Splay(u, 0);
}

int Next(int x, int f)
{
Find(x);
int u = root;
if(t[u].val > x && f) return u;
if(t[u].val < x && !f) return u;
u = t[u].ch[f];
while(t[u].ch[f^1]) u = t[u].ch[f^1];
return u;
}

void Delete(int x)
{
int last = Next(x, 0);
int next = Next(x, 1);
Splay(last, 0);
Splay(next, last);
int del = t[next].ch[0];

if(t[del].cnt > 1)
{
t[del].cnt--;
t[del].sz--;
Splay(del, 0);
}
else
{
t[next].ch[0] = 0;
PushUp(next);
}
}

//查询x的最小排名
void MinTh(int x)
{
Find(x);
printf("%d\n",t[t[root].ch[0]].sz);
}
//查询排名为x的数
void KTh(int x)
{
int u = root;
while(true)
{
if(x > t[t[u].ch[0]].sz && x <= t[t[u].ch[0]].sz+t[u].cnt)
{
printf("%d\n",t[u].val);
return;
}
else if(x > t[t[u].ch[0]].sz+t[u].cnt)
{
x -= t[t[u].ch[0]].sz+t[u].cnt;
u = t[u].ch[1];
}
else u = t[u].ch[0];
}
}

int main()
{
root = tot = 0;
int opt,x;
scanf("%d",&n);
Insert(-INF);
Insert(INF);
for(int i = 0; i < n; ++i)
{
scanf("%d %d",&opt,&x);
if(opt == 1) Insert(x);
else if(opt == 2) Delete(x);
else if(opt == 3) MinTh(x);
else if(opt == 4) KTh(x+1);
else if(opt == 5) printf("%d\n",t[Next(x, 0)].val);
else if(opt == 6) printf("%d\n",t[Next(x, 1)].val);
}
return 0;
}