Pagini recente » Cod sursa (job #344275) | Cod sursa (job #666406) | Cod sursa (job #343510) | Cod sursa (job #2864105) | Cod sursa (job #2784210)
#include <bits/stdc++.h>
#define LETTERS_SIZE 26
struct Trie {
std::vector<Trie*> children{LETTERS_SIZE, nullptr};
int count = 0;
int partial_count = 0;
~Trie() {
for (int i = 0; i < LETTERS_SIZE; ++i) {
if (children[i]) {
delete children[i];
}
}
}
void insert(const std::string &s, const int index = 0) {
if (index == s.size()) {
count++;
} else {
int pos = s[index] - 'a';
if (!children[pos]) {
children[pos] = new Trie();
}
children[pos]->insert(s, index + 1);
}
partial_count++;
}
int find(const std::string &s, const int index = 0) {
if (index == s.size()) {
return count;
}
int pos = s[index] - 'a';
if (!children[pos]) {
return 0;
}
return children[pos]->find(s, index + 1);
}
void erase(const std::string &s, const int index = 0) {
partial_count--;
if (index == s.size()) {
if (count > 0) {
count--;
}
return;
}
int pos = s[index] - 'a';
if (!children[pos]) {
return;
}
children[pos]->erase(s, index + 1);
}
int get_longest_prefix(const std::string &s, const int index = 0) {
if (index == s.size()) {
return 0;
}
int pos = s[index] - 'a';
if (!children[pos]) {
return 0;
}
if (!children[pos]->partial_count) {
return 0;
}
return 1 + children[pos]->get_longest_prefix(s, index + 1);
}
};
int main() {
std::ifstream in("trie.in");
std::ofstream out("trie.out");
std::string line;
Trie* t = new Trie;
while (std::getline(in, line)) {
std::stringstream ss(line);
int code;
std::string word;
ss >> code;
ss >> word;
if (code == 0) {
t->insert(word);
} else if (code == 1) {
t->erase(word);
} else if (code == 2) {
out << t->find(word) << "\n";
} else if (code == 3) {
out << t->get_longest_prefix(word) << "\n";
}
}
in.close();
out.close();
delete t;
return 0;
}