Cod sursa(job #2691023)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 26 decembrie 2020 18:54:43
Problema Trie Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.09 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(int node, const string& str, int pos) {
        trie[node].lvs++;
        if (pos == (int) str.size()) {
            trie[node].cnt++;
            return;
        }
        if (!trie[node].next[str[pos] - 'a']) {
            trie[node].next[str[pos] - 'a'] = trie.size();
            trie.emplace_back();
        }
        insert(trie[node].next[str[pos] - 'a'], str, pos + 1);
    }

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

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

    int lcp(int node, const string& str, int pos) {
        if (pos == (int) str.size())
            return 0;
        if (!trie[node].next[str[pos] - 'a'])
            return 0;
        return 1 + lcp(trie[node].next[str[pos] - 'a'], str, pos + 1);
    }
};

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