Cod sursa(job #2759481)

Utilizator World_shifterMurgu Bogdan World_shifter Data 18 iunie 2021 10:15:49
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>

using namespace std;

ifstream in("trie.in");
ofstream out("trie.out");

const int NL=26, L=21;

struct nod{
    nod* fii[NL];
    int nrcuv,nrpref;
    nod(){
        for(int i=0; i<NL; i++){
            fii[i]=NULL;
        }
        nrcuv=0;
        nrpref=0;
    }
};

nod* adaugare(nod* p, char *s){
    if(p==NULL){
        p=new nod();
    }
    p->nrpref++;
    if(s[0]=='\0'){
        p->nrcuv++;
        return p;
    }
    int i=s[0]-'a';
    p->fii[i]=adaugare(p->fii[i], s+1);
    return p;
}

nod* stergere(nod* p, char* s){
    p->nrpref--;
    if(s[0]=='\0'){
        p->nrcuv--;
    }else{
        int i=s[0]-'a';
        p->fii[i]=stergere(p->fii[i], s+1);
    }
    if (p->nrpref == 0)
    {
        delete p;
        return NULL;
    }
    return p;
}

int nr_cuv(nod* p, char* s){
    if(p==NULL){
        return 0;
    }
    if(s[0]=='\0'){
        return p->nrcuv;
    }
    int i=s[0]-'a';
    return nr_cuv(p->fii[i], s+1);
}

int nr_pref(nod* p, char* s){
    if(p==NULL){
        return -1;
    }
    if(s[0]=='\0'){
        return 0;
    }
    int i=s[0]-'a';
    return 1+nr_pref(p->fii[i], s+1);
}

int main()
{
    int tip;
    char cuvant[L];
    nod* r=NULL;
    while(in>>tip>>cuvant){
        if(tip==0){
            r=adaugare(r, cuvant);
        }
        if(tip==1){
            r=stergere(r, cuvant);
        }
        if(tip==2){
            out<<nr_cuv(r, cuvant)<<"\n";
        }
        if(tip==3){
            out<<nr_pref(r, cuvant)<<"\n";
        }
    }
    return 0;
}