Cod sursa(job #2691081)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 26 decembrie 2020 22:59:35
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>
using namespace std;

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

class Trie {
  private:
    struct Node {
        int cnt = 0;
        int lvs = 0;
        int next[26] = {};
    };
    vector<Node> trie{1};

  public:
    void insert(const string& str) {
        int node = 0;
        for (char chr : str) {
            trie[node].lvs++;
            if (!trie[node].next[chr - 'a']) {
                trie[node].next[chr - 'a'] = trie.size();
                trie.emplace_back();
            }
            node = trie[node].next[chr - 'a'];
        }
        trie[node].cnt++;
        trie[node].lvs++;
    }

    bool erase(int node, const string& str, int pos) {
        if (pos == (int) str.size()) {
            if (trie[node].lvs > 1) {
                trie[node].cnt--;
                trie[node].lvs--;
                return false;
            }
            return true;
        }
        if (!erase(trie[node].next[str[pos] - 'a'], str, pos + 1)) {
            trie[node].lvs--;
            return false;
        }
        trie[node].next[str[pos] - 'a'] = 0;
        return --trie[node].lvs == 0;
    }

    int count(const string& str) {
        int node = 0;
        for (char chr : str) {
            if (!trie[node].next[chr - 'a'])
                return 0;
            node = trie[node].next[chr - 'a'];
        }
        return trie[node].cnt;
    }

    int lcp(const string& str) {
        int node = 0, len = 0;
        for (char chr : str) {
            if (!trie[node].next[chr - 'a'])
                return len;
            node = trie[node].next[chr - 'a'];
            len++;
        }
        return len;
    }
};

int main() {
    Trie trie;
    int type; string str;
    while (fin >> type >> str)
        if (!type)
            trie.insert(str);
        else if (type == 1)
            trie.erase(0, str, 0);
        else if (type == 2)
            fout << trie.count(str) << '\n';
        else
            fout << trie.lcp(str) << '\n';
    return 0;
}