Cod sursa(job #2452992)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 2 septembrie 2019 00:41:14
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>

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

class Trie {
  private:
    int cnt = 0;
    int ptrs = 0;
    Trie *next[26] = {};

  public:
    void insert(char* str) {
        if (!str[0])
            cnt++;
        else {
            if (!next[str[0] - 'a']) {
                next[str[0] - 'a'] = new Trie;
                ptrs++;
            }
            next[str[0] - 'a']->insert(str + 1);
        }
    }

    bool remove(char* str) {
        if (!str[0])
            return --cnt == 0 && !ptrs;
        if (next[str[0] - 'a']->remove(str + 1)) {
            delete next[str[0] - 'a'];
            next[str[0] - 'a'] = NULL;
            return --ptrs == 0 && !cnt;
        }
        return false;
    }

    int count(char* str) {
        if (!str[0])
            return cnt;
        if (!next[str[0] - 'a'])
            return 0;
        return next[str[0] - 'a']->count(str + 1);
    }

    int lcp(char* str) {
        if (!str[0] || !next[str[0] - 'a'])
            return 0;
        return 1 + next[str[0] - 'a']->lcp(str + 1);
    }
};

int main() {
    Trie trie;
    int type; char str[25];

    while (fin >> type >> str) {
        if (!type)
            trie.insert(str);
        else if (type == 1)
            trie.remove(str);
        else if (type == 2)
            fout << trie.count(str) << '\n';
        else
            fout << trie.lcp(str) << '\n';
    }

    fout.close();
    return 0;
}