Cod sursa(job #2544727)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 12 februarie 2020 13:46:36
Problema Trie Scor 90
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>

using namespace std;

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

const int SIGMA = 26;
const int MAX_LEN = 20;

class Trie
{
public:
    Trie *sons[SIGMA];

    int nrap, nrc;

    Trie()
    {
        for(int i = 0; i < SIGMA; i++)
            sons[i] = NULL;

        nrap = nrc = 0;
    }
};

Trie *root = new Trie();

int type;
char word[MAX_LEN + 5];

Trie* Insert(Trie* node, char *s)
{
    node-> nrap++;

    if(s[0] == '\0')
        node-> nrc++;
    else
    {
        if(node-> sons[s[0] - 'a'] == NULL)
            node-> sons[s[0] - 'a'] = new Trie();

        node-> sons[s[0] - 'a'] = Insert(node-> sons[s[0] - 'a'], s + 1);
    }

    return node;
}

Trie* Delete(Trie* node, char *s)
{
    node-> nrap--;

    if(s[0] == '\0')
        node-> nrc--;
    else
        node-> sons[s[0] - 'a'] = Delete(node-> sons[s[0] - 'a'], s + 1);

    if(node-> nrap == 0)
        node = NULL;

    return node;
}

int NrAp(Trie* node, char *s)
{
    if(node == NULL)
        return 0;

    if(s[0] == '\0')
        return node-> nrc;

    if(node-> sons[s[0] - 'a'] == NULL)
        return 0;

    return NrAp(node-> sons[s[0] - 'a'], s + 1);
}

int BestPref(Trie* node, char *s)
{
    if(s[0] == '\0')
        return 0;

    if(node-> sons[s[0] - 'a'] != NULL)
        return 1 + BestPref(node-> sons[s[0] - 'a'], s + 1);

    return 0;
}

int main()
{
    while(fin >> type)
    {
        fin >> word;

        if(type == 0)
            root = Insert(root, word);
        else if(type == 1)
            root = Delete(root, word);
        else if(type == 2)
            fout << NrAp(root, word) << '\n';
        else
            fout << BestPref(root, word) << '\n';
    }
    return 0;
}