同 AcWing 950 郁闷的出纳员
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using p = pair<int, int>;
const int inf(0x3f3f3f3f);
const int maxn(1e5 + 10);
int idx, root;
char op[2];
struct node {
int val, siz;
int fa, ch[2];
} tree[maxn];
template<typename T = int>
inline const T read()
{
T x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-') f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 3) + (x << 1) + ch - '0';
ch = getchar();
}
return x * f;
}
template<typename T>
inline void write(T x, bool ln)
{
if (x < 0) {
putchar('-');
x = -x;
}
if (x > 9) write(x / 10, false);
putchar(x % 10 + '0');
if (ln) putchar(10);
}
inline int new_node(int val)
{
++idx;
tree[idx].val = val;
tree[idx].siz = 1;
return idx;
}
inline void push_up(int cur)
{
tree[cur].siz = tree[tree[cur].ch[0]].siz + tree[tree[cur].ch[1]].siz + 1;
}
inline bool get_rel(int cur, int fa)
{
return tree[fa].ch[1] == cur;
}
inline void connect(int cur, int fa, int rel)
{
tree[fa].ch[rel] = cur;
tree[cur].fa = fa;
}
inline void rotate(int cur)
{
int fa = tree[cur].fa;
int gf = tree[fa].fa;
bool rel = get_rel(cur, fa);
connect(tree[cur].ch[rel ^ 1], fa, rel);
connect(cur, gf, get_rel(fa, gf));
connect(fa, cur, rel ^ 1);
push_up(fa);
push_up(cur);
}
inline void splaying(int cur, int top)
{
while (tree[cur].fa not_eq top) {
int fa = tree[cur].fa;
int gf = tree[fa].fa;
if (gf not_eq top) {
get_rel(cur, fa) ^ get_rel(fa, gf) ? rotate(cur) : rotate(fa);
}
rotate(cur);
}
if (not top) {
root = cur;
}
}
inline void insert(int val)
{
int cur = root, fa = 0;
while (cur) {
fa = cur;
cur = tree[cur].ch[val > tree[cur].val];
}
cur = new_node(val);
connect(cur, fa, val > tree[fa].val);
splaying(cur, 0);
}
inline int lower_bound(int val)
{
int cur = root, res = 0;
while (cur) {
if (tree[cur].val >= val) {
res = cur;
cur = tree[cur].ch[0];
} else {
cur = tree[cur].ch[1];
}
}
return res;
}
inline int get_val(int rank)
{
int cur = root;
while (cur) {
if (tree[tree[cur].ch[0]].siz >= rank) {
cur = tree[cur].ch[0];
} else if (tree[tree[cur].ch[0]].siz + 1 == rank) {
break;
} else {
rank -= tree[tree[cur].ch[0]].siz + 1;
cur = tree[cur].ch[1];
}
}
return tree[cur].val;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("input.txt", "r", stdin);
#endif
int n = read(), m = read();
insert(-inf);
insert(inf);
int d = 0, cnt = 0;
while (n--) {
scanf("%s", op);
int k = read();
if (*op == 'I' and k >= m) {
insert(k - d);
++cnt;
} else if (*op == 'A') {
d += k;
} else if (*op == 'S') {
d -= k;
int l = 1, r = lower_bound(m - d);
splaying(r, 0);
splaying(l, r);
tree[l].ch[1] = 0;
push_up(l);
push_up(r);
} else if (*op == 'F') {
write(tree[root].siz - 2 >= k ? (get_val(tree[root].siz - k) + d) : -1, true);
}
}
write(cnt + 2 - tree[root].siz, true);
return 0;
}