Cod sursa(job #868544)

Utilizator Mihnea35Gall Mihnea Mihnea35 Data 31 ianuarie 2013 10:56:06
Problema Hashuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <fstream>
#include <iostream>

using namespace std;

struct nod {
	int cheie;
	nod *s, *d;
};

nod *a;

nod *nou (int cheie) {
	nod *aux = new nod;
	aux->cheie = cheie;
	aux->s = NULL;
	aux->d = NULL;
	return aux;
}

void inserare (nod *&p, int x) {
	if (p)
		if (p->cheie > x) inserare(p->s, x);
		else if (p->cheie < x) inserare(p->d, x);
			else ;
	else p = nou(x);
}

void cautare (nod *&p, nod *&adr, int k) {
	if (p) {
		if (p->cheie == k) adr = p;
		else if (p->cheie > k) cautare(p->s, adr, k);
		else cautare(p->d, adr, k);
	}
	else adr = NULL;
}

/*void stergere_frunze (nod *&p) {
	if (p)
		if (p->s == NULL && p->d == NULL) {delete p; p = NULL;}
		else {
			stergere(p->s);
			stergere(p->d);
		}
}*/

void abcd (nod *p, nod *&q) {
	if (q->d) abcd(p, q->d);
	else {
		p->cheie = q->cheie;
		a = q;
		q = q->s;
		delete a;
	}
}

void stergere (nod *&p, int k) {
	if(p==0)
		return;
	if(p->cheie == k) {
		if (p->s == NULL && p->d == NULL) {
			delete p;
			p = NULL;
		}
		else if (p->s == NULL) {
			a = p->d;
			delete p;
			p = a;
		}
		else if (p->d == NULL) {
			a = p->s;
			delete p;
			p = a;
		}
		else abcd(p, p->s);
	}
    else {
		if(p->cheie > k) stergere(p->s, k);
		else if (p->cheie < k) stergere (p->d, k);
	}
}

/*void SRD (nod *p) {
	if (p) {
		SRD(p->s);
		cout << p->cheie << ' ';
		SRD(p->d);
	}
}*/

int main () {
	int n, op, x, i;
	nod *rad = NULL, *adr;
	ifstream f ("hashuri.in");
	ofstream g ("hasuri.out");
	f >> n;
	for (i=1; i<=n ;i++) {
		f >> op >> x;
		if (op == 1) inserare(rad, x);
		else if (op == 2) stergere(rad, x);
		else {
			cautare(rad, adr, x);
			if (adr) g << 1 <<'\n';
			else g << 0 <<'\n';
		}
	}		
	f.close();
	g.close();
	return 0;
}