Cod sursa(job #2440257)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 18 iulie 2019 00:50:29
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.18 kb
#include <fstream>

using namespace std;

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

struct Trie
{
        short int cnt_end;
        short int cnt;
        Trie *kids[26];
        Trie()
        {
                cnt_end = cnt = 0;
                for (int i = 0; i < 26; i++)
                        kids[i] = 0;
        }
};

Trie *root = new Trie;

void add(string w)
{
        Trie *node = root;
        for (auto &ch : w)
        {
                int x = ch - 'a';
                if (node -> kids[x] == 0)
                        node -> kids[x] = new Trie;
                node = node -> kids[x];
                node -> cnt++;
        }
        node -> cnt_end++;
}

void del(string w)
{
        Trie *node = root;
        for (auto &ch : w)
        {
                Trie *ant = node;
                int x = ch - 'a';
                node = node -> kids[x];
                node -> cnt--;
                if (node -> cnt == 0)
                {
                        delete node;
                        ant -> kids[x] = 0;
                        return;
                }
        }
        node -> cnt_end--;
}

int frq(string w)
{
        Trie *node = root;
        for (auto &ch : w)
        {
                int x = ch - 'a';
                if (node -> kids[x] == 0)
                        return 0;
                node = node -> kids[x];
        }
        return node -> cnt_end;
}

int lcp(string w)
{
        Trie *node = root;
        int sol = 0;
        for (auto &ch : w)
        {
                int x = ch - 'a';
                if (node -> kids[x] == 0)
                        return sol;
                sol++;
                node = node -> kids[x];
        }
        return sol;
}

int main()
{
        int t;
        while (fin >> t)
        {
                string w;
                fin >> w;
                if (t == 0)
                        add(w);
                if (t == 1)
                        del(w);
                if (t == 2)
                        fout << frq(w) << "\n";
                if (t == 3)
                        fout << lcp(w) << "\n";
        }
}