0%

fhq Treap模板

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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 100010;
int n;
int ch[N][3];
int val[N];
int heap[N];
int siz[N];
int sz;

void update(int x) {
siz[x] = siz[ch[x][0]] + siz[ch[x][1]] + 1;
}

int new_node(int v) {
siz[++sz] = 1;
val[sz] = v;
heap[sz] = rand();
return sz;
}

void split(int now, int k, int &x, int &y) {
if(!now) x = y = 0;
else {
if(val[now] <= k) {
x = now;
split(ch[now][1], k, ch[now][1], y);
} else if(val[now] > k) {
y = now;
split(ch[now][0], k, x, ch[now][0]);
}
update(now);
}

}

int merge(int x,int y)
{
if (!x || !y) return x+y;
if (heap[x] < heap[y])
{
ch[x][1]=merge(ch[x][1],y);
update(x);
return x;
}
else
{
ch[y][0]=merge(x,ch[y][0]);
update(y);
return y;
}
}

int kth(int now,int k) {
while(1) {
if (k <= siz[ch[now][0]])
now = ch[now][0];
else if (k == siz[ch[now][0]]+1)
return now;
else
k -= siz[ch[now][0]]+1, now = ch[now][1];
}
}

int main() {
scanf("%d", &n);
int root = 0, x = 0, y = 0, z = 0;
for (int i = 1; i <= n; i++) {
int opt, a;
scanf("%d%d", &opt, &a);
if(opt == 1) {
split(root, a, x, y);
root = merge(merge(x, new_node(a)), y);
} else if(opt == 2){
split(root, a, x, z);
split(x, a - 1, x, y);
y = merge(ch[y][0], ch[y][1]);
root = merge(merge(x, y), z);
} else if(opt == 3) {
split(root, a - 1, x, y);
printf("%d\n", siz[x] + 1);
root = merge(x, y);
} else if(opt == 4) {
printf("%d\n", val[kth(root, a)]);
} else if(opt == 5) {
split(root, a - 1, x, y);
printf("%d\n", val[kth(x, siz[x])]);
root = merge(x, y);
} else {
split(root, a, x, y);
printf("%d\n", val[kth(y, 1)]);
root = merge(x, y);
}
}

return 0;
}
求大佬赏个饭