Pagini recente » Cod sursa (job #2000529) | Monitorul de evaluare | Cod sursa (job #1161283) | Monitorul de evaluare | Cod sursa (job #3352017)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct TRIE {
vector<int> next;
int pref, end;
TRIE() {
next = vector<int>(26, -1);
pref = end = 0;
}
};
string s;
vector<TRIE> trie;
void insert() {
int u = 0;
trie[u].pref++;
for (char ch : s) {
int c = ch - 'a';
if (trie[u].next[c] == -1) {
trie[u].next[c] = trie.size();
trie.push_back(TRIE());
}
u = trie[u].next[c];
trie[u].pref++;
}
trie[u].end++;
}
void erase() {
int u = 0;
// verificăm dacă există
for (char ch : s) {
int c = ch - 'a';
if (trie[u].next[c] == -1)
return; // nu există
u = trie[u].next[c];
}
if (trie[u].end == 0) return;
// scădem
u = 0;
trie[u].pref--;
for (char ch : s) {
int c = ch - 'a';
u = trie[u].next[c];
trie[u].pref--;
}
trie[u].end--;
}
int cate_cuv_s() {
int u = 0;
for (char ch : s) {
int c = ch - 'a';
if (trie[u].next[c] == -1)
return 0;
u = trie[u].next[c];
}
return trie[u].end;
}
int cel_mai_lung_prefix() {
int u = 0, cnt = 0;
for (char ch : s) {
int c = ch - 'a';
if (trie[u].next[c] == -1)
break;
u = trie[u].next[c];
if (trie[u].pref == 0)
break;
cnt++;
}
return cnt;
}
int main() {
trie.push_back(TRIE()); // 🔥 ROOT (foarte important)
int nr;
while (fin >> nr >> s) {
if (nr == 0) {
insert();
} else if (nr == 1) {
erase();
} else if (nr == 2) {
fout << cate_cuv_s() << '\n';
} else {
fout << cel_mai_lung_prefix() << '\n';
}
}
return 0;
}