Cod sursa(job #2662109)

Utilizator PopescuAndreiAlexandruPopescu Andrei Alexandru PopescuAndreiAlexandru Data 23 octombrie 2020 15:53:11
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.24 kb
#include <bits/stdc++.h>

using namespace std;

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

const int SIGMA = 28;

char s[100];

struct Trie
{
    Trie* next[SIGMA] = {};
    int wordsEndHere=0;
    int wordsContained=0;
};

Trie *root;

void AddWord(Trie *node, char *word)
{
    node->wordsContained++;
    if(*word=='\0')
        {
            node->wordsEndHere++;
            return;
        }
    int nextIndex = *word - 'a';
    if(node->next[nextIndex]==NULL)
        node->next[nextIndex] = new Trie;
    AddWord(node->next[nextIndex],word+1);
}

void DeleteWord(Trie *node, char *word)
{
    node->wordsContained--;
    if(*word=='\0')
        {
            node->wordsEndHere--;
            return;
        }
    int nextIndex = *word - 'a';
    DeleteWord(node->next[nextIndex],word+1);
    if(node->next[nextIndex]->wordsContained==0)
        {
            free(node->next[nextIndex]);
            node->next[nextIndex]=NULL;
        }
}

int FreqTrie(Trie *node, char *word)
{
    if(*word=='\0')
        return node->wordsEndHere;
    int nextIndex = *word - 'a';
    if(node->next[nextIndex]==NULL)
        return 0;
    return FreqTrie(node->next[nextIndex],word+1);
}

int LongestPrefix(Trie *node, char *word)
{
    if(*word=='\0')
            return 0;
    int nextIndex = *word - 'a';
    if(node->next[nextIndex]==NULL)
        return 0;
    return 1 + LongestPrefix(node->next[nextIndex],word+1);
}

int main()
{
    root = new Trie;
    while(fin.getline(s,SIGMA))
        {
            switch(s[0])
                {
                case '0':
                    {
                        AddWord(root,s+2);
                        break;
                    }
                case '1':
                    {
                        DeleteWord(root,s+2);
                        break;
                    }
                case '2':
                    {
                        fout<<FreqTrie(root,s+2)<<'\n';
                        break;
                    }
                default:
                    {
                        fout<<LongestPrefix(root,s+2)<<'\n';
                        break;
                    }
                }
        }
}