Cod sursa(job #3210514)

Utilizator donCiuarinArin Donciu donCiuarin Data 6 martie 2024 14:00:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <bits/stdc++.h>
#define LM 26

using namespace std;

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

string s;

class Trie
{
private:
    Trie * next[LM] = {};
public:
    int cnt, lvs;
    Trie()
    {
        cnt = 0; lvs = 0;
    }
    void insert(const string & k, int pos = 0)
    {
        lvs++;
        if(pos == k.size())
            cnt++;
        if(pos != k.size())
        {
            int x = (int)(k[pos] - 'a');
            if(!next[x])
                next[x] = new Trie;
            next[x] -> insert(k, pos + 1);
        }
    }
    void erase(const string & k, int pos = 0)
    {
        lvs--;
        if(pos == k.size())
        {
            cnt--;
            return;
        }
        int x = (int)(k[pos] - 'a');
        next[x] -> erase(k, pos + 1);
        if(!next[x] -> lvs)
        {
            delete next[x];
            next[x] = nullptr;
        }
    }
    int count(const string & k, int pos = 0)
    {
        if(pos == k.size())
            return cnt;
        int x = (int)(k[pos] - 'a');
        if(!next[x])
            return 0;
        return next[x] -> count(k, pos + 1);
    }
    int prefix(const string & k, int pos = 0)
    {
        if(pos == k.size())
            return 0;
        int x = (int)(k[pos] - 'a');
        if(!next[x])
            return 0;
        return 1 + next[x] -> prefix(k, pos + 1);
    }
} trie;

int main()
{
    int op;
    while(fin >> op)
    {
        fin >> s;
        //cout << s << ' ';
        switch(op)
        {
        case 0:
            trie.insert(s);
            break;
        case 1:
            trie.erase(s);
            break;
        case 2:
            fout << trie.count(s) << '\n';
            break;
        case 3:
            fout << trie.prefix(s) << '\n';
            break;
        }
    }
    return 0;
}