Cod sursa(job #2567815)

Utilizator Cezar211Popoveniuc Cezar Cezar211 Data 3 martie 2020 19:01:24
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
struct nod
{
    int ap;
    nod* p[27];
    nod()
    {
        ap = 0;
        for(int i=0; i<=26; i++)
            p[i] = 0;
    }
};
nod* rad;
int op;
char c[21];
int nr_aparitii(nod* t, char* s)
{
    if(*s == '\n')
        return t->ap;
    if(t->p[*s-'a']!=0)
        return nr_aparitii(t->p[*s-'a'], s+1);
    return 0;
}
void adauga(nod* t, char* s)
{
    if(*s == '\n')
    {
        t->ap++;
        return;
    }
    if(t->p[*s-'a'] == 0)
    {
        t->p[*s-'a'] = new nod;
        adauga(t->p[*s-'a'], s+1);
    }
    else adauga(t->p[*s-'a'], s+1);
}
bool are_fii(nod* t)
{
    for(int i=0; i<=26; i++)
        if(t->p[i] != 0)
            return 1;
    return 0;
}
bool sterge(nod* t, char* s)
{
    if(*s == '\n')
        t->ap--;
    else if(sterge(t->p[*s-'a'], s+1))
        t->p[*s-'a'] = 0;
    if(rad!=t && !are_fii(t) && t->ap == 0)
    {
        delete t;
        return 1;
    }
    return 0;
}
int prefix(nod* t, char* s)
{
    if(*s == '\n' || t->p[*s-'a']==0)
        return 0;
    return 1+prefix(t->p[*s-'a'], s+1);
}
int main()
{
    rad = new nod;
    while(fin >> op)
    {
        fin >> c;
        c[strlen(c)] = '\n';
        if(op == 0)
            adauga(rad, c);
        else if(op == 1)
            sterge(rad, c);
        else if(op == 2)
            fout << nr_aparitii(rad, c) << '\n';
        else fout << prefix(rad, c) << '\n';
    }
    return 0;
}