Cod sursa(job #2436405)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 5 iulie 2019 17:37:25
Problema Trie Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.7 kb
#include <iostream>
#include <cstdio>
#include <map>

using namespace std;

struct Trie {
        int subtree = 0;
        int cnt = 0;
        map <int, int> go;
};

Trie nodes[(int) 1e5];
int sz;

int main() {
        freopen ("trie.in", "r", stdin);
        freopen ("trie.out", "w", stdout);
        sz++;
        int type;
        while (cin >> type) {
                string s;
                cin >> s;
                if (type == 0) {
                        int nod = 0;
                        nodes[nod].subtree++;
                        for (auto &ch : s) {
                                int x = ch - 'a';
                                if (nodes[nod].go[x] == 0) {
                                        sz++;
                                        nodes[nod].go[x] = sz - 1;
                                }
                                nod = nodes[nod].go[x];
                                nodes[nod].subtree++;
                        }
                        nodes[nod].cnt++;
                }
                if (type == 1) {
                        int nod = 0;
                        nodes[nod].subtree--;
                        for (auto &ch : s) {
                                int x = ch - 'a';
                                nod = nodes[nod].go[x];
                                nodes[nod].subtree--;
                        }
                        nodes[nod].cnt--;
                }
                if (type == 2) {
                        int nod = 0;
                        bool to_early = 0;
                        for (auto &ch : s) {
                                int x = ch - 'a';
                                if (nodes[nod].go[x] == 0) {
                                        to_early = 1;
                                        break;
                                }
                                nod = nodes[nod].go[x];
                        }
                        int res = 0;
                        if (!to_early)
                                res = nodes[nod].cnt;
                        cout << res << "\n";
                }
                if (type == 3) {
                        int nod = 0, lcp = 0;
                        for (auto &ch : s) {
                                int x = ch - 'a';
                                nod = nodes[nod].go[x];
                                if (nod == 0)
                                        break;
                                if (nodes[nod].subtree == 0)
                                        break;
                                lcp++;
                        }
                        cout << lcp << "\n";
                }
        }
}