Cod sursa(job #3274723)

Utilizator Shaan_StefanShaan Stefan Shaan_Stefan Data 8 februarie 2025 10:33:38
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.86 kb
#include <cstddef>
#include <cstdio>
#include <exception>
#include <iostream>
#include <map>

using namespace std;

class Trie
{
private:
    int cnt = 0, lvs = 0;
    Trie *next[30] = {};
public:
    void insert(const string& str, int pos = 0)
    {
        lvs++;
        if(pos == str.size())
            cnt++;
        else
        {
            if(!next[str[pos] - 'a'])
                next[str[pos] - 'a'] = new(Trie);
            next[str[pos] - 'a']->insert(str, pos + 1);
        }
    }

    int count(const string& str, int pos = 0)
    {
        if(pos == str.size())
            return cnt;
        if(!next[str[pos] - 'a'])
            return 0;
        return next[str[pos] - 'a']->count(str, pos + 1);
    }

    int lcp(const string& str, int pos = 0)
    {
        if(pos == str.size())
            return 0;
        if(!next[str[pos] - 'a'])
            return 0;
        return 1 + next[str[pos] - 'a']->lcp(str, pos + 1);
    }

    void erase(const string& str, int pos = 0)
    {
        lvs--;
        if(pos == str.size())
            cnt--;
        else
        {
            next[str[pos] - 'a']->erase(str, pos + 1);
            if(!next[str[pos] - 'a']->lvs)
            {
                delete(next[str[pos] - 'a']);
                next[str[pos] - 'a'] = NULL;
            }
        }
    }
};

Trie tr;
int main()
{
    freopen("trie.in", "r", stdin);
    freopen("trie.out", "w", stdout);

    int op = 0;
    string str;
    char strc[30];
    while(scanf("%d", &op)>0)
    {
        scanf("%s", strc);
        str.assign(strc);
        switch(op)
        {
        case 0:
            tr.insert(str);
            break;
        case 1:
            tr.erase(str);
            break;
        case 2:
            printf("%d\n", tr.count(str));
            break;
        case 3:
            printf("%d\n", tr.lcp(str));
            break;
        }
    }
    return 0;
}