Cod sursa(job #1503877)

Utilizator TeodorCotetCotet Teodor TeodorCotet Data 17 octombrie 2015 01:12:00
Problema Hashuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.32 kb

#include <fstream>

using namespace std;

int N;

struct Nod{

	int key; bool filled;

	Nod* st;
	Nod* dr;

	Nod(int key) {

		filled = true;
		this->st = NULL;
		this->dr = NULL;
		this->key = key;
	}
};

void adauga(Nod** cpcurent,const int key) {

	Nod* curent = *cpcurent;

	if(*cpcurent == NULL) {

		(*cpcurent) = new Nod(key);
		return ;
	}
	
	if(key > curent->key) {

		if(curent->dr == NULL)  {

			Nod* node = new Nod(key);
			curent->dr = node;
		}  else  adauga(&curent->dr, key);

	} else {

		if(curent->st == NULL) {

			Nod* node = new Nod(key);
			curent->st = node;

		} else  adauga(&curent->st, key);
	}

}

void sterge(Nod* father, Nod* curent, const int key, const bool direction) {


	if(curent == NULL) return ;

	if(curent->key == key) { 
		//stergerea

		if(curent->st == NULL) {
			if( curent->dr == NULL) {

				//ambele NULL
				if(direction == 0)
					father->st = NULL;
				else 
					father->dr = NULL;

				return ;
			} else {
				//st = null, dr != null
				if(direction == 1)
					father->dr = curent->dr;
				else 
					father->st = curent->dr;

				return ;
			}
		} else {
			//dr == null, st != null
			
			if(curent->dr == NULL) {

				if(direction == 1)
					father->dr = curent->st;
				else 
					father->st = curent->st;
			} else {

				//dr != null, st != null

				Nod* aux = curent->st;
				Nod* father_aux = aux;

				while(aux->dr != NULL) {
					father_aux = aux;
					aux = aux->dr;
				}

				curent->key = aux->key;
				//trebuie doar sa mai stergem aux, cand stim ca nu are copii la dr

				if(aux->st == NULL) {

					father_aux->dr = NULL;
					return;
				} else {

					father_aux->dr = aux->st;
				}


			}

		}

		return;
	}

	if(curent->key > key) 
		sterge(curent, curent->st, key, 0);
	else 
		sterge(curent, curent->dr, key, 1);
	
}

int interogare(Nod* curent, int key) {

	if(curent == NULL) return 0;

	if(curent->key == key && curent->filled == true) return 1;

	if(curent->key > key) return interogare(curent->st, key);
	return interogare(curent->dr, key);
}


int main() {

	ifstream fin ("hashuri.in");
	ofstream fout ("hashuri.out");

	Nod* root = NULL;


	int type; int x;

	fin >> N;


	while(N--) {

		

		fin >> type >> x;

		switch(type) {

			case 1: adauga(&root, x); break;
			case 2: sterge(root, root, x, 0); break;
			case 3: fout << interogare( root, x) << '\n'; break;
		}
	}

	return 0;
}