Cod sursa(job #1253422)

Utilizator scipianusFMI Ciprian Olariu scipianus Data 1 noiembrie 2014 12:00:17
Problema Hashuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.5 kb
#include <fstream>
#include <iostream>
using namespace std;
int T;
struct AVL
{
	AVL *st, *dr;
	int val, bal, h;
	AVL()
	{
		st = dr = 0;
		val = bal = h = 0;
	}
};
AVL *R, *NIL;

inline void GetHeight(AVL *nod)
{
	nod -> h = 1 + max(nod -> st -> h, nod -> dr -> h);
}

inline AVL* RotateLeft(AVL *nod)
{
	AVL *aux = nod -> st;
	nod -> st = aux -> dr;
	aux -> dr = nod;
	GetHeight(nod);
	GetHeight(aux);
	return aux;
}

inline AVL* RotateRight(AVL *nod)
{
	AVL *aux = nod -> dr;
	nod -> dr = aux -> st;
	aux -> st = nod;
	GetHeight(nod);
	GetHeight(aux);
	return aux;
}

inline AVL* Balance(AVL *nod)
{
	GetHeight(nod);
	if(nod -> st -> h > nod -> dr -> h + 1)
	{
		if(nod -> st -> dr -> h > nod -> st -> st -> h)
			nod -> st = RotateRight(nod -> st);
		nod = RotateLeft(nod);
	}
	else
	{
		if(nod -> st -> h < nod -> dr -> h - 1)
		{
			if(nod -> dr -> st -> h > nod -> dr -> dr -> h)
				nod -> dr = RotateLeft(nod -> dr);
			nod = RotateRight(nod);
		}
	}
	return nod;
}

inline AVL* SearchInsert(AVL *nod, int x)
{
	if(nod == NIL)
	{
		nod = new AVL;
		nod -> val = x;
		nod -> h = 1;
		nod -> st = nod -> dr = NIL;
		return nod;
	}
	if(nod -> val == x)
		return nod;
	if(nod -> val > x)
		nod -> st = SearchInsert(nod -> st, x);
	else
		nod -> dr = SearchInsert(nod -> dr, x);
	return Balance(nod);
}

inline int Search(AVL *nod, int x)
{
	if(nod == NIL)
		return 0;
	if(nod -> val == x)
		return 1;
	if(nod -> val > x)
		return Search(nod -> st, x);
	return Search(nod -> dr, x);
}

inline AVL* Erase(AVL *nod, int x)
{
	if(nod == NIL)
		return nod;
	if(nod -> val == x)
	{
		AVL *aux;
		if(nod -> st == NIL)
		{
			aux = nod -> dr;
			delete nod;
			return aux;
		}
		if(nod -> dr == NIL)
		{
			aux = nod -> st;
			delete nod;
			return aux;
		}
		for(aux = nod -> dr; aux -> st != NIL; aux = aux -> dr);
		nod -> val = aux -> val;
		nod -> dr = Erase(nod -> dr, aux -> val);
		return Balance(nod);
	}
	if(nod -> val > x)
		nod -> st = Erase(nod -> st, x);
	else
		nod -> dr = Erase(nod -> dr, x);
	return Balance(nod);
}

int main()
{
	int op, x, gasit;
	NIL = new AVL;
	R = NIL;
	ifstream fin("hashuri.in");
	ofstream fout("hashuri.out");
	fin >> T;
	while(T--)
	{
		fin >> op >> x;
		if(op == 1)
		{
			R = SearchInsert(R, x);
		}
		if(op == 2)
		{
			R = Erase(R, x);
		}
		if(op == 3)
		{
			gasit = Search(R, x);
			fout << gasit << "\n";
		}
	}
	fin.close();
	fout.close();
	return 0;
}