洛谷P1503 鬼子进村

(Large extbf{Description: } large{有n个数,m次操作(1 leq n, m leq 5 imes 10^{4})。操作有三种:\ quad 1.添加一个数x。\ quad 2.删除上一个添加的数。\ quad 3.输出x的前驱与后继之间的距离。})

(Large extbf{Solution: } large{容易想到用平衡树,但是感觉在这道题上难免小题大做,用STL里的set即可。})

(Large extbf{Code: })

#include <bits/stdc++.h>
using namespace std;
const int N = 5e4 + 5;
int n, m, vis[N], pre[N];

int main() {
	cin >> n >> m;
	set<int> s; set<int>::iterator it;
	char c; int x, cnt = 0;
	s.insert(0); s.insert(n + 1);
	while (m--) {
		cin >> c;
		if (c == 'D') {
			cin >> x;
			pre[++cnt] = x; vis[x] = 1;
			s.insert(x);
		} else if (c == 'R') s.erase(pre[cnt]), vis[pre[cnt--]] = 0;
		else {
			cin >> x;
			if (vis[x]) cout << "0" << endl;
			else {
				it = s.lower_bound(x);
				cout << *it - *(--it) - 1 << endl;//至于这个(--it)我不明白为什么是前驱 当时百度不到查前驱的函数 在题解里找到的 记忆一下。
			}
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/Miraclys/p/12560108.html