Cod sursa(job #2346333)

Utilizator oldatlantianSerban Cercelescu oldatlantian Data 17 februarie 2019 15:53:16
Problema Zeap Scor 80
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.55 kb
#include <bits/stdc++.h>
using namespace std;

struct Treap {
	Treap *st, *dr;
	int pr, val; } *NIL;

multiset<int> difs;
set<int> s;


static Treap *newTreap(int val) {
	return new Treap {NIL, NIL, rand(), val}; }

static Treap *join(Treap *l, Treap *r) {
	if (l == NIL) return r;
	if (r == NIL) return l;
	if (l->pr >= r->pr) {
		l->dr = join(l->dr, r);
		return l; }
	else {
		r->st = join(l, r->st);
		return r; } }

static pair<Treap*, Treap*> split(Treap *root, int key) {
	if (root == NIL)
		return make_pair(NIL, NIL);

	if (root->val < key) {
		auto res = split(root->dr, key);
		root->dr = res.first;
		res.first = root;
		return res; }
	else {
		auto res = split(root->st, key);
		root->st = res.second;
		res.second = root;
		return res; } }

static int min(Treap *root) {
	return root->st == NIL ? root->val : min(root->st); }

static int max(Treap *root) {
	return root->dr == NIL ? root->val : max(root->dr); }


int main() {
	freopen("zeap.in", "r", stdin);
	freopen("zeap.out", "w", stdout);
	srand(time(0));
	Treap *root;
	int val;

	char op[4];

	NIL = new Treap;
	*NIL = {NIL, NIL, -1, 0};
	root = NIL;

	while (scanf(" %s", op) != EOF) {
		if (!strcmp(op, "MAX")) { // max-dif
			if (s.size() < 2)
				printf("-1\n");	
			else
				printf("%d\n", *s.rbegin() - *s.begin());
			continue; }

		if (!strcmp(op, "MIN")) { // min-dif
			if (s.size() < 2)
				printf("-1\n");	
			else
				printf("%d\n", *difs.begin());
			continue; }

		if (!strcmp(op, "I")) { // insereaza
			scanf("%d", &val);
			if (s.find(val) == end(s)) {
				auto sp = split(root, val);
				int maxl = max(sp.first);
				int minr = min(sp.second);

				s.insert(val);
				if (sp.first != NIL && sp.second != NIL)
					difs.erase(difs.find(minr - maxl));
				if (sp.first != NIL)
					difs.insert(val - maxl);
				if (sp.second != NIL)
					difs.insert(minr - val);
				root = join(sp.first, join(newTreap(val), sp.second)); }

			continue; }

		if (!strcmp(op, "S")) { // sterge
			scanf("%d", &val);

			if (s.find(val) != end(s)) {
				auto spl = split(root, val);
				auto spr = split(spl.second, val + 1);
				int maxl = max(spl.first);
				int minr = min(spr.second);

				if (spl.first != NIL)
					difs.erase(difs.find(val - maxl));
				if (spr.second != NIL)
					difs.erase(difs.find(minr - val));
				if (spl.first != NIL && spl.second != NIL)
					difs.insert(minr - maxl);

				root = join(spl.first, spr.second);
				s.erase(val); }
			else
				printf("-1\n");

			continue; }

		if (!strcmp(op, "C")) { // cauta
			scanf("%d", &val);
			printf("%d\n", int(s.find(val) != end(s)));
			continue; } }

	return 0; }