Pagini recente » Istoria paginii info-oltenia-2018/individual/9 | Cod sursa (job #1967649) | Clasament fmi-no-stress-3 | Cod sursa (job #2626905) | Cod sursa (job #3278326)
#include <bits/stdc++.h>
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
const int SIZE = 2e5;
const int ALPHABET_SIZE = 26;
int trie[SIZE][ALPHABET_SIZE], isEnd[SIZE], frecv[SIZE], nodes = 1;
void Insert(std::string text) {
int node = 0;
for (char ch : text) {
int idx = ch - 'a';
if (!trie[node][idx]) trie[node][idx] = nodes++;
node = trie[node][idx];
frecv[node]++;
}
isEnd[node]++;
}
void Delete(std::string text) {
int node = 0;
for (char ch : text) {
int idx = ch - 'a';
node = trie[node][idx];
frecv[node]--;
}
isEnd[node]--;
}
int Search(std::string text) {
int node = 0;
for (char ch : text) {
int idx = ch - 'a';
if (!trie[node][idx]) return 0;
node = trie[node][idx];
}
return isEnd[node];
}
int LongestPrefix(std::string text) {
int node = 0, len = 0;
for (char ch : text) {
int idx = ch - 'a';
if (!trie[node][idx]) break;
node = trie[node][idx];
if (!frecv[node]) break;
len++;
}
return len;
}
int main() {
std::ios::sync_with_stdio(false);
fin.tie(nullptr); fout.tie(nullptr);
int op; std::string word;
while (fin >> op >> word) {
switch (op) {
case 0: Insert(word); break;
case 1: Delete(word); break;
case 2: fout << Search(word) << "\n"; break;
case 3: fout << LongestPrefix(word) << "\n"; break;
}
}
return 0;
}