Pagini recente » Cod sursa (job #189588) | Cod sursa (job #377432) | Cod sursa (job #117916) | Cod sursa (job #1172615) | Cod sursa (job #3040884)
#include <iostream>
#include <fstream>
#include <vector>
struct Trie {
private:
struct Node {
int words = 0;
int children_size = 0;
std::vector<Node *> children = std::vector<Node *>(26, std::nullptr_t());
};
Node *root = new Node;
void insert(const std::string &str, Node *&node, int ptr = 0) {
if (ptr == str.size()) {
node->words++;
return;
}
if (node->children[str[ptr] - 'a'] == nullptr) {
node->children[str[ptr] - 'a'] = new Node;
node->children_size++;
}
insert(str, node->children[str[ptr] - 'a'], ptr + 1);
}
bool remove(const std::string &str, Node *&node, int ptr = 0) {
if (ptr == str.size()) {
node->words--;
} else if (remove(str, node->children[str[ptr] - 'a'], ptr + 1)) {
node->children[str[ptr] - 'a'] = nullptr;
node->children_size--;
}
if (node->words == 0 && node->children_size == 0 && node != root) {
delete node;
return true;
}
return false;
}
int max_prefix(const std::string &str, Node *node, int len = 0, int ptr = 0) {
if (ptr == str.size() || node->children[str[ptr] - 'a'] == nullptr) return len;
return max_prefix(str, node->children[str[ptr] - 'a'], len + 1, ptr + 1);
}
public:
Trie() = default;
void insert(const std::string &str) {
insert(str, root);
}
int count(const std::string &str) {
int ptr = 0;
Node *node = root;
while (ptr != str.size() && node != nullptr) {
node = node->children[str[ptr] - 'a'];
ptr++;
}
if (node == nullptr) return 0;
return node->words;
}
void remove(const std::string &str) {
remove(str, root);
}
int max_prefix(const std::string &str) {
return max_prefix(str, root);
}
};
int main() {
std::ifstream input("trie.in");
std::ofstream output("trie.out");
Trie trie;
int op;
std::string str;
while (input >> op >> str) {
switch (op) {
case 0:
trie.insert(str);
break;
case 1:
trie.remove(str);
break;
case 2:
output << trie.count(str) << '\n';
break;
default:
output << trie.max_prefix(str) << '\n';
break;
}
}
return 0;
}