Cod sursa(job #2307520)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 24 decembrie 2018 19:12:01
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include<cstdio>
using namespace std;

struct Nod{
    Nod *fii[26];
    int nrp,nrc;
    Nod(){
        nrp=nrc=0;
        for(int i=0;i<26;i++)
            fii[i]=NULL;
    }
};

Nod *r;

Nod *adauga(Nod *p,char *s){
    if (p==NULL) p=new Nod;
    p-> nrp++;
    if (s[0]==0){
        p-> nrc++;
        return p;
    }
    p-> fii[s[0]-'a']=adauga(p-> fii[s[0]-'a'],s+1);
    return p;
}

Nod *sterge(Nod *p,char *s){
    p-> nrp--;
    if (s[0]==0){
        p-> nrc--;
    }
    else
        p-> fii[s[0]-'a']=sterge(p-> fii[s[0]-'a'],s+1);
    if (p-> nrp==0){
        delete p;
        p = NULL;
    }
    return p;
}

int nr_ap(Nod *p,char *s){
    if (p==NULL) return 0;
    if (s[0]==0) return p-> nrc;
    return nr_ap(p-> fii[s[0]-'a'],s+1);
}

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

int main(){
    freopen ("trie.in","r",stdin);
    freopen ("trie.out","w",stdout);
    int op;
    char c[21];
    while(scanf("%d",&op)!=EOF){
        scanf (" ");
        scanf ("%s",&c);
        scanf ("\n");
        if (op==0) r=adauga(r,c);
        else
        if (op==1) r=sterge(r,c);
        else
        if (op==2) printf ("%d\n",nr_ap(r,c));
        else printf ("%d\n",comun(r,c));
    }
    return 0;
}