Cod sursa(job #2769276)

Utilizator vlad2009Vlad Tutunaru vlad2009 Data 14 august 2021 14:17:36
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.93 kb
#include <fstream>

using namespace std;

struct Trie
{
    int nr = 0, c = 0;
    Trie *sons[26];
    Trie()
    {
        for (int i = 0; i < 26; i++)
        {
            sons[i] = NULL;
        }
    };
    void add(const string &s, int poz = 0)
    {
        c++;
        if (poz == s.size())
        {
            nr++;
            return;
        }
        if (sons[s[poz] - 'a'] == NULL)
        {
            sons[s[poz] - 'a'] = new Trie;
        }
        sons[s[poz] - 'a'] -> add(s, poz + 1);
    }
    void del(const string &s, int poz = 0)
    {
        c--;
        if (poz == s.size())
        {
            nr--;
            return;
        }
        sons[s[poz] - 'a'] -> del(s, poz + 1);
    }
    int cnt(string &s, int poz = 0)
    {
        if (c == 0)
        {
            return 0;
        }
        if (poz == s.size())
        {
            return nr;
        }
        if (sons[s[poz] - 'a'] != NULL)
        {
            return sons[s[poz] - 'a'] -> cnt(s, poz + 1);
        }
        return 0;
    }
    int pref(string &s, int poz = 0)
    {
        if (c == 0)
        {
            return 0;
        }
        if (poz == s.size())
        {
            return poz;
        }
        if (sons[s[poz] - 'a'] != NULL && sons[s[poz] - 'a'] -> c != 0)
        {
            return sons[s[poz] - 'a'] -> pref(s, poz + 1);
        }
        return poz;
    }
};

Trie *T;

int main()
{
    ifstream fin("trie.in");
    ofstream fout("trie.out");
    T = new Trie;
    int tip;
    string s;
    while (fin >> tip >> s)
    {
        if (tip == 0)
        {
            T -> add(s);
        }
        else if (tip == 1)
        {
            T -> del(s);
        }
        else if (tip == 2)
        {
            fout << T -> cnt(s) << "\n";
        }
        else
        {
            fout << T -> pref(s) << "\n";
        }
    }
    return 0;
}