Cod sursa(job #2692092)

Utilizator PopescuAndreiAlexandruPopescu Andrei Alexandru PopescuAndreiAlexandru Data 31 decembrie 2020 14:32:21
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.65 kb
#include <bits/stdc++.h>

using namespace std;

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

const int N = 55;
const int SIGMA = 26;

int ans;

char S[N];

struct Trie
{
    Trie *next[SIGMA]={};
    int WordsEndHere=0;
    int WordsContained=0;
};

Trie *root = new Trie;

void AddWord(Trie *k, int l, int d)
{
    if(l>d)
        return;
    else
        {
            int p=S[l]-'a';
            if(k->next[p]==NULL)
                k->next[p] = new Trie;
            k->next[p]->WordsContained++;
            if(l==d)
                k->next[p]->WordsEndHere++;
            AddWord(k->next[p],l+1,d);
        }
}

void DeleteWord(Trie *k, int l, int d)
{
    if(l>d)
        {
            k->WordsEndHere--;
            return;
        }
    else
        {
            int p=S[l]-'a';
            k->next[p]->WordsContained--;
            DeleteWord(k->next[p],l+1,d);
            if(k->next[p]->WordsContained==0)
                {
                    delete k->next[p];
                    k->next[p]=NULL;
                }
        }
}

void CountWords(Trie *k, int l, int d)
{
    if(l>d)
       {
           ans+=k->WordsEndHere;
           return;
       }
    else
        {
            int p=S[l]-'a';
            if(k->next[p]==NULL)
                return;
            else
                CountWords(k->next[p],l+1,d);
        }
}

void LongestPrefix(Trie *k, int l, int d)
{
    if(l>d)
        return;
    else
        {
            int p=S[l]-'a';
            if(k->next[p]==NULL)
                return;
            else
                {
                    ans++;
                    LongestPrefix(k->next[p],l+1,d);
                }
        }
}

int main()
{
    while(fin.getline(S,N))
        {
            Trie *k = root;
            switch(S[0])
                {
                case '0':
                    {
                        AddWord(k,2,strlen(S)-1);
                        break;
                    }
                case '1':
                    {
                        DeleteWord(k,2,strlen(S)-1);
                        break;
                    }
                case '2':
                    {
                        ans=0;
                        CountWords(k,2,strlen(S)-1);
                        fout<<ans<<'\n';
                        break;
                    }
                default:
                    {
                        ans=0;
                        LongestPrefix(k,2,strlen(S)-1);
                        fout<<ans<<'\n';
                        break;
                    }
                }
        }
}