Cod sursa(job #3039588)

Utilizator SmauSmau George Robert Smau Data 28 martie 2023 18:14:05
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.72 kb
#include <bits/stdc++.h>

#define LENGTH 26

using namespace std;

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

class Trie {
    private:
        int count = 0;
        int leaves = 0;
        Trie *next[LENGTH] = {};
    public:
        void Insert(const string& str, int pos = 0) {
            leaves ++;
            if(pos == int(str.size())) {count ++; return;}
            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 == int(str.size())) return count;
            if(!next[str[pos] - 'a']) return 0;
            return next[str[pos] - 'a']->Count(str, pos + 1);
        }

        int LongestCommonPreffix(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']->LongestCommonPreffix(str, pos + 1);
        }

        void Erase(const string& str, int pos = 0) {
            leaves --;
            if(pos == int(str.size())) {count --; return;}

            next[str[pos] - 'a']->Erase(str, pos + 1);
            if(!next[str[pos] - 'a']->leaves) {
                delete next[str[pos] - 'a'];
                next[str[pos] - 'a'] = NULL;
            }
        }
};

int main() {
    int task; string word;
    Trie T;
    while(fin >> task >> word) {
        switch(task) {
            case 0: T.Insert(word); break;
            case 1: T.Erase(word); break;
            case 2: fout << T.Count(word) << '\n'; break;
            case 3: fout << T.LongestCommonPreffix(word) << '\n'; break;
        }
    }

    return 0;
}