Cod sursa(job #1503906)

Utilizator TeodorCotetCotet Teodor TeodorCotet Data 17 octombrie 2015 03:31:34
Problema Hashuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.28 kb
#include <fstream>

using namespace std;


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

int N;

struct Nod{

	int key; bool filled;

	Nod* st;
	Nod* dr;

	Nod(int key) {

		this->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,  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* father_aux = curent;
				Nod* aux = curent->st;

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

				curent->key = aux->key;

				if(curent->st->dr == NULL)
					sterge(father_aux, aux, aux->key, 0);
				else
					sterge(father_aux, aux, aux->key, 1);
				
				return ;
				
			}

		}

		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 )  return 1;

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


int main() {

	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;
}