Cod sursa(job #2844763)

Utilizator mlupseLupse-Turpan Mircea mlupse Data 5 februarie 2022 13:14:09
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Nod
{
    int Nr,NrSons;
    Nod * Son[26];
    Nod()
    {
        Nr = NrSons = 0;
        for(int i = 0; i < 26; ++i)
            Son[i] = 0;
    }
};
Nod * Trie = new Nod;

void Insert(char * S, Nod * p)
{
    if(!(*S))
    {
        p->Nr++;
        return;
    }
    int Index = *S - 'a';
    if(! (p->Son[Index]))
    {
        p->Son[Index] = new Nod;
        p->NrSons++;
    }
    Insert(S + 1,p->Son[Index]);
}

int Print(char * S, Nod * p)
{
    if(!(*S))
        return p->Nr;
    int Index = *S - 'a';
    if(p->Son[Index])
        return Print(S+1,p->Son[Index]);
    else
        return 0;
}

int Delete(char * S, Nod * p)
{
    if(!(*S))
    {
        p->Nr--;
    }
    else
    {
        int Index = *S - 'a';
        if( Delete(S + 1, p->Son[Index]) == 1)
        {
            p->Son[Index] = 0;
            p->NrSons--;
        }
    }
    if(p->Nr ==0 && p->NrSons == 0 && p != Trie)
    {
        delete p; return 1;
    }
    return 0;
}

int Prefix(char * S, Nod * p, int k)
{
    int Index = *S - 'a';

    if(!(*S) || !(p->Son[Index]))
        return k;
    else
        return Prefix(S+1,p->Son[Index],k+1);

}
int main()
{
    char Line[25];
    while(fin.getline(Line,25))
    {
        if(Line[0] == '0')
            Insert(Line + 2,Trie);
        if(Line[0] == '1')
            Delete(Line + 2, Trie);
        if(Line[0] == '2')
            fout << Print(Line+2,Trie) << "\n";
        if(Line[0] == '3')
        {
            fout << Prefix(Line + 2, Trie, 0) << "\n";
        }

    }

    return 0;
}