Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P1486 [NOI2004] 郁闷的出纳员

P1486 [NOI2004] 郁闷的出纳员

平衡树维护,对于操作 I ,新建一个节点;对于操作 F ,查询第 $k$ 大数。都是平衡树的基本操作。

查看代码
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
#include <iostream>
#include <cstdio>
#include <climits>
#define inf INT_MAX
using namespace std;
const int N = 1e5 + 10;
int n, m, rt, idx, delta;
struct Node
{
int s[2], p, v, sz;
void init(int a, int b)
{
v = a;
p = b;
sz = 1;
}
}tr[N];
void pushup(int x)
{
tr[x].sz = tr[tr[x].s[0]].sz + tr[tr[x].s[1]].sz + 1;
}
void rotate(int x)
{
int y = tr[x].p, z = tr[y].p;
int k = tr[y].s[1] == x;
tr[z].s[tr[z].s[1] == y] = x;
tr[x].p = z;
tr[y].s[k] = tr[x].s[k ^ 1];
tr[tr[x].s[k ^ 1]].p = y;
tr[x].s[k ^ 1] = y;
tr[y].p = x;
pushup(y);
pushup(x);
}
void splay(int x, int k)
{
while (tr[x].p != k)
{
int y = tr[x].p, z = tr[y].p;
if (z != k)
if ((tr[y].s[1] == x) ^ (tr[z].s[1] == y))
rotate(x);
else
rotate(y);
rotate(x);
}
if (!k)
rt = x;
}
int insert(int v)
{
int u = rt, p = 0;
while (u)
{
p = u;
u = tr[u].s[v > tr[u].v];
}
u = ++idx;
if (p)
tr[p].s[v > tr[p].v] = u;
tr[u].init(v, p);
splay(u, 0);
return u;
}
int get(int v)
{
int u = rt, res;
while (u)
{
if (tr[u].v >= v)
{
res = u;
u = tr[u].s[0];
}
else
u = tr[u].s[1];
}
return res;
}
int get_k(int k)
{
int u = rt;
while (true)
{
if (tr[tr[u].s[0]].sz >= k)
u = tr[u].s[0];
else if (tr[tr[u].s[0]].sz + 1 == k)
return tr[u].v;
else
{
k -= tr[tr[u].s[0]].sz + 1;
u = tr[u].s[1];
}
}
return -1;
}
int main()
{
cin >> n >> m;
int L = insert(-inf), R = insert(inf);
int tot = 0;
while (n--)
{
char op[2];
int k;
cin >> op >> k;
if (op[0] == 'I')
{
if (k >= m)
{
insert(k - delta);
tot++;
}
}
else if (op[0] == 'A')
delta += k;
else if (op[0] == 'S')
{
delta -= k;
R = get(m - delta);
splay(R, 0);
splay(L, R);
tr[L].s[1] = 0;
pushup(L);
pushup(R);
}
else
{
if (tr[rt].sz - 2 < k)
cout << -1 << endl;
else
{
int t = get_k(tr[rt].sz - k);
if (~t)
cout << t + delta << endl;
else
cout << -1 << endl;
}
}
}
cout << tot - (tr[rt].sz - 2);
return 0;
}