Cod sursa(job #867451)

Utilizator SebiSebiPirtoaca George Sebastian SebiSebi Data 29 ianuarie 2013 18:27:17
Problema Hashuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include<iostream>
#include<fstream>
using namespace std;
 
struct nod {
    int info;
    nod *st,*dr;
};
typedef nod *PNOD;
 
PNOD rad;
 
void inserare(PNOD &p, int x)
{
    if(p==NULL) {
        p=new nod;
        p->st=NULL;
        p->dr=NULL;
        p->info=x;
    }
    else if(p->info!=x) {
        if(p->info>x)
            inserare(p->st,x);
        else inserare(p->dr,x);
    }
}
 
int cautare(PNOD &p, int x)
{
    if(p==NULL)
        return 0;
    if(p->info==x)
        return 1;
    if(p->st && p->info>x)
        return cautare(p->st,x);
    else if(p->dr && p->info<x)
        return cautare(p->dr,x);
    else return 0;
}
 
void c3(PNOD &p, PNOD &t)
{
    if(p==NULL)
        return;
    if(p->dr)
        c3(p->dr,t);
    else {
        PNOD aux;
        t->info=p->info;
        aux=p->st;
        delete p;
        p=aux;
    }
}
 
void stergere(PNOD &p, int x)
{
    if(p==0)
        return;
    if(p->info==x) {
        if(p->st==0 && p->dr==0) {
            delete p;
            p=NULL;
        }
        else if(p->dr) {
            PNOD aux;
            aux=p->dr;
            delete p;
            p=aux;
        }
        else if(p->st) {
            PNOD aux;
            aux=p->st;
            delete p;
            p=aux;
        }
        else
            c3(p,p);
    }
    else {
        if(p->info>x)
            stergere(p->st,x);
        else stergere(p->dr,x);
    }
}
 
int main ()
{
    int n,op,x,i,nr;
    ifstream f("hashuri.in");
    ofstream g("hashuri.out");
    f>>n;
    nr=0;
    for(i=1;i<=n;i++) {
        f>>op>>x;
        if(op==1) 
            inserare(rad,x);
        else if(op==2) 
            stergere(rad,x);
        else g<<cautare(rad,x)<<'\n';
    }
    f.close();
    g.close();
    return 0;
}