Cod sursa(job #360395)

Utilizator coderninuHasna Robert coderninu Data 31 octombrie 2009 12:45:57
Problema Zeap Scor 30
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.73 kb
#include <stdio.h>
#define Infinit 1000000001

struct nod { nod *st, *dr; int min, max, dif; bool del; };

nod *root;
char s[20];







inline int max(int x, int y) { return x > y ? x : y; }
inline int min(int x, int y) { if (x == -1 || y == -1) return max(x,y); return x < y ? x : y; }

void relax(nod * n)
{
	n->min = -1;
	if (n->st) n->min = n->st->min;
	if (n->dr) n->min = min(n->min, n->dr->min);
	
	n->max = -1;
	if (n->st) n->max = n->st->max;
	if (n->dr) n->max = max(n->max, n->dr->max);
	
	n->dif = -1;
	if (n->st) n->dif = n->st->dif;
	if (n->dr) n->dif = min(n->dif, n->dr->dif);
	if ((n->st && n->dr ) && n->st->max != -1 && n->dr->min != -1) n->dif = min(n->dif, n->dr->min - n->st->max);
}

void insert(int x, nod * n, int st, int dr)
{
	if (st == dr)
	{
		n->min = n->max = x;
		n->dif = -1;
		return;
	}
	int mij = (st + dr) >> 1;
	if (x <= mij)
	{
		if (n->st == NULL)
		{
			n->st = new nod;
			n->st->st = n->st->dr = NULL;
			n->st->min = n->st->max = n->st->dif = -1;
			n->st->del = false;
		}
		insert(x,n->st,st,mij);
	}
	else
	{
		if (n->dr == NULL)
		{
			n->dr = new nod;
			n->dr->st = n->dr->dr = NULL;
			n->dr->min = n->dr->max = n->dr->dif = -1;
			n->dr->del = false;
		}
		insert(x,n->dr,mij+1,dr);
	}
	
	relax(n);
}

int cauta(int x, nod *n, int st, int dr)
{
	if (st == dr) return 1;
	int mij = (st + dr) >> 1;
	if (x <= mij)
	{
		if (n->st)
			return cauta(x,n->st,st,mij);
		else
			return 0;
	}
	else
	{
		if (n->dr)
			return cauta(x,n->dr,mij+1,dr);
		else
			return 0;
	}
}

void sterge(int x, nod *n, int st, int dr)
{
	if (st == dr)
	{
		n->del = true;
		return;
	}
	int mij = (st + dr) >> 1;
	if (x <= mij)
	{
		sterge(x, n->st, st, mij);
		if (n->st->del)
		{
			delete n->st;
			n->st = NULL;
		}
	}
	else
	{
		sterge(x, n->dr, mij+1,dr);
		if (n->dr->del)
		{
			delete n->dr;
			n->dr = NULL;
		}
	}
	relax(n);
}

int toInt(char *s)
{
	int val = 0;
	for (int i = 0; s[i]<='9' && s[i]>='0'; ++i)
		val = val * 10 + s[i] - '0';
	return val;
}

int main()
{
	root = new nod;
	root->st = root->dr = NULL;
	root->min = root->max = root->dif = -1;
	root->del = false;
	freopen("zeap.in", "r", stdin);
	freopen("zeap.out", "w", stdout);
	while (!feof(stdin))
	{
		gets(s);
		if (s[0] == 'I') { insert(toInt(s + 2), root, 1, Infinit); continue; }
		if (s[0] == 'S') { if (cauta(toInt(s + 2), root, 1, Infinit)) sterge(toInt(s + 2), root, 1, Infinit); else printf("-1\n"); continue; }
		if (s[0] == 'C') { printf("%d\n", cauta(toInt(s + 2), root, 1, Infinit)); continue; }
		if (s[1] == 'A') { printf("%d\n", root->max - root->min); continue; }
		if (s[1] == 'I') { printf("%d\n", root->dif); }
	}
	
	return 0;
}