Cod sursa(job #2470170)

Utilizator mlupseLupse-Turpan Mircea mlupse Data 8 octombrie 2019 20:03:46
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Nod
{
    int NSons,Nr;
    Nod * Son[26];
    Nod()
    {
        NSons = Nr = 0;
        for(int i = 0; i < 26; ++i)
            Son[i] = 0;
    }
};
Nod * Trie = new Nod;
char Line[25];

void Insert(char Word[], Nod * p)
{
    if(!Word[0])
    {
        p->Nr++;
        return;
    }

    int Index = Word[0] - 'a';

    if(!p->Son[Index])
    {
        p->Son[Index] = new Nod;
        p->NSons++;
    }
    Insert(Word + 1, p->Son[Index]);
}

int Print(char Word[], Nod * p)
{
    if(!Word[0])
        return p->Nr;

    int Index = Word[0] - 'a';

    if(!p->Son[Index])
        return 0;
    return Print(Word + 1,p->Son[Index]);
}

int Prefix(char Word[], Nod * p, int Count)
{
    if(!Word[0])
        return Count;

    int Index = Word[0] - 'a';

    if(!p->Son[Index])
        return Count;

    return Prefix(Word + 1, p->Son[Index],Count + 1);
}

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

    if(p->Nr == 0 && p->NSons == 0 && p != Trie)
    {
        delete p;
        return 1;
    }

    return 0;
}

int main()
{
    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;
}