Cod sursa(job #2436384)
Utilizator | Data | 5 iulie 2019 16:58:30 | |
---|---|---|---|
Problema | Trie | Scor | 50 |
Compilator | cpp-64 | Status | done |
Runda | Arhiva educationala | Marime | 2.75 kb |
#include <iostream>
#include <cstdio>
#include <map>
#include <vector>
using namespace std;
struct Trie {
int subtree = 0;
int cnt = 0;
map <int, int> go;
};
vector <Trie> nodes;
int main() {
freopen ("trie.in", "r", stdin);
freopen ("trie.out", "w", stdout);
nodes.push_back({});
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) {
nodes.push_back({});
nodes[nod].go[x] = (int) nodes.size() - 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";
}
}
}