Cod sursa(job #2696595)

Utilizator VladMxPMihaila Vlad VladMxP Data 16 ianuarie 2021 10:33:34
Problema Trie Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>

#define CH(s) s-'a'

using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");

struct Trie
{
    int cnt,nrfii;
    Trie* fiu[26];
};
Trie *T = new Trie();

void insereaza(Trie* nod, char* s)
{
    if(*s==0)
    {
        nod->cnt++;
        return;
    }
    if(nod->fiu[CH(*s)]==NULL)
    {
        nod->fiu[CH(*s)]=new Trie();
        nod->nrfii++;
    }
    insereaza(nod->fiu[CH(*s)],s+1);
}

int sterge(Trie* nod, char* s)
{
    if(*s==0)
    {
        nod->cnt--;
    }
    else if(sterge(nod->fiu[CH(*s)],s+1))
    {
        nod->fiu[CH(*s)]=NULL;
        nod->nrfii--;
    }
    if(nod->cnt==0&&nod->nrfii==0&&nod!=T)
    {
        delete nod;
        return 1;
    }
    return 0;
}

int aparitii(Trie* nod, char* s)
{
    if(*s==0||nod->fiu[CH(*s)]==NULL)
        return nod->cnt;
    return aparitii(nod->fiu[CH(*s)],s+1);
}

int lungmax(Trie* nod, char* s, int k)
{
    if(*s==0||nod->fiu[CH(*s)]==NULL)
        return k;
    else return lungmax(nod->fiu[CH(*s)],s+1,k+1);
}

int main()
{
    char line[32];
    fin.getline(line,32);
    while(!fin.eof())
    {
        switch(line[0])
        {
            case '0': insereaza(T,line+2);break;
            case '1': sterge(T,line+2);break;
            case '2': fout<<aparitii(T,line+2)<<'\n';break;
            case '3': fout<<lungmax(T,line+2,0)<<'\n';break;
        }
        fin.getline(line,32);
    }
}