Cod sursa(job #150503)

Utilizator coderninuHasna Robert coderninu Data 6 martie 2008 23:58:34
Problema Zeap Scor 10
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.88 kb
#include <stdio.h>
#define Nmax 300001

int h[Nmax], poz[Nmax], nrH, val;
char ch;

void I(int);
void S(int);
void C(int);
void MIN();
void MAX();

void upheap(int);
void downheap(int);

inline void swap(int x, int y) { poz[h[x]]=y; poz[h[y]]=x; int temp = h[x]; h[x] = h[y]; h[y] = temp; } 
inline int min(int x, int y) { return x<y ? x : y; }
inline int max(int x, int y) { return x>y ? x : y; }

int main()
{
	freopen("zeap.in", "r", stdin);
	freopen("zeap.out", "w", stdout);
	while (!feof(stdin))
	{
		scanf("%c", &ch);
		if (ch!='M')
		{
			scanf("%d\n", &val);
			switch (ch)
			{
				case 'I' : I(val); break;
				case 'S' : S(val); break;
				case 'C' : C(val); break;
			}
		}
		else 
		{
			scanf("%c%c\n",&ch, &ch);
			if (ch=='X') MAX();
			else MIN();
		}
	}
	fclose(stdin); fclose(stdout);
	return 0;
}

void I(int val)
{
	if (poz[val]) return;
	poz[val] = ++nrH;
	h[nrH]=val;
	upheap(nrH);
}

void S(int val)
{
	if (!poz[val]) { printf("-1\n"); return; }
	int loc = poz[val];
	poz[val] = 0;
	h[loc]=h[nrH--];
	poz[h[loc]] = loc;
	downheap(loc);
}

void C(int val)
{
	if (poz[val]) printf("1\n"); 
	else printf("0\n");
}

void MIN()
{
	if (nrH <= 1) { printf("-1\n"); return ; }
	int temp = h[2];
	if (nrH>2) temp = min(temp,h[3]);
	printf("%d\n", temp-h[1]);
}

void MAX()
{
	if (nrH <=1) { printf("-1\n"); return; }
	int loc = 1;
	for (; loc < nrH; loc<<=1); loc>>=1;
	int temp = -1;
	for (int i=loc; i<=nrH; i++) temp = max(temp, h[i]);
	printf("%d\n", temp-h[1]);
}

void upheap(int loc)
{
	if (loc==1) return ;
	int tata = loc >> 1;
	if (h[tata] > h[loc]) { swap(tata,loc); upheap(tata); }
}

void downheap(int loc)
{
	int fiu;
	if ((loc << 1) <= nrH)
	{
		fiu = loc << 1;
		if (fiu+1 <=nrH && h[fiu+1] < h[fiu]) fiu++;
	}
	else return;
	if (h[fiu] < h[loc]) { swap(loc,fiu); downheap(fiu); }
}