Cod sursa(job #3274686)

Utilizator EnnBruhEne Andrei EnnBruh Data 8 februarie 2025 10:05:54
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>
#define endl '\n'

using namespace std;

const string fileName = "trie";
ifstream in  (fileName + ".in");
ofstream out (fileName + ".out");

const int maxSize = 102;
const int inf = 0x3f3f3f3f;

class Trie {
    int cnt = 0, lvs = 0;
    Trie *next[30] = { };

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

    void erase(const string& str, int pos = 0) {
        lvs--;
        if (pos == int(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'] = nullptr;
            }
        }
    }

    int count(const string& str, int pos = 0) {
        if (pos == int(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 == int(str.size()))
            return 0;
        if (!next[str[pos] - 'a'])
            return 0;
        return 1 + next[str[pos] - 'a']->lcp(str, pos + 1);
    }
} current;

int main( ) {
    ios_base :: sync_with_stdio( false );
    cin.tie( NULL ); cout.tie( NULL );

    int task; string word;
    while (in >> task >> word) {
            //out << task << ' ' << word << endl;
            switch ( task ) {
                case 0: current.insert(word, 0); break;
                case 1: current.erase(word, 0); break;
                case 2: out << current.count(word, 0) << endl; break;
                case 3: out << current.lcp(word, 0) << endl; break;
            }
    }

    return 0;
}