Cod sursa(job #3352313)

Utilizator Tudor_ChelaruChelaru Tudor Tudor_Chelaru Data 26 aprilie 2026 14:39:34
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>
#include <string>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
struct nod
{
    int cont=0;
    int pref=0;
    nod * next[26]={};
};
int nr;
string cuv;
void inserare(string str, nod * root)
{
    nod * aux=root;
    for(char ch:str)
    {
        if(aux->next[ch-'a']==NULL)
            aux->next[ch-'a']=new nod;
        aux->next[ch-'a']->pref++;
        aux=aux->next[ch-'a'];
    }
    aux->cont++;
}
void stergere(string str, nod * root)
{
    nod * aux=root;
    for(char ch:str)
    {
        aux->next[ch-'a']->pref--;
        aux=aux->next[ch-'a'];
    }
    aux->cont--;
    aux=root;
    for(char ch:str)
    {
        if(aux->next[ch-'a']->pref==0)
        {
            aux->next[ch-'a']=NULL;
            break;
        }
        aux=aux->next[ch-'a'];
    }
}
int tiparire(string str, nod * root)
{
    nod * aux=root;
    for(char ch:str)
    {
        if(aux->next[ch-'a']==NULL)
            return 0;
        aux=aux->next[ch-'a'];
    }
    return aux->cont;
}
int cmnpref(string str, nod * root)
{
    nod * aux=root;
    int l=0;
    for(char ch:str)
    {
        if(aux->next[ch-'a']==NULL)
            return l;
        l++;
        aux=aux->next[ch-'a'];
    }
    return l;
}
int main()
{
    nod * root=new nod;
    while(cin>>nr>>cuv)
    {
        if(nr==0)
            inserare(cuv,root);
        if(nr==1)
            stergere(cuv,root);
        if(nr==2)
            cout<<tiparire(cuv,root)<<'\n';
        if(nr==3)
            cout<<cmnpref(cuv,root)<<'\n';
    }
    return 0;
}