Pagini recente » Cod sursa (job #3357883) | Monitorul de evaluare | Borderou de evaluare (job #3095721) | Monitorul de evaluare | Cod sursa (job #3357897)
#include <iostream>
#include <fstream>
#include <cstring>
struct Node {
int words = 0;
int in_words = 0;
Node* children[26] = {nullptr};
};
Node* root = new Node();
void insert(const std::string& str, int val) {
Node* node = root;
for (int i = 0; i < str.size(); i++) {
int idx = str[i] - 'a';
if (!node->children[idx]) {
node->children[idx] = new Node();
}
node = node->children[idx];
node->in_words += val;
}
node->words += val;
}
int count(const std::string& str) {
Node* node = root;
for (int i = 0; i < str.size(); i++) {
int idx = str[i] - 'a';
if (!node->children[idx]) return 0;
node = node->children[idx];
}
return node->words;
}
int find_max(const std::string& str) {
Node* node = root;
int max_len = 0;
for (int i = 0; i < str.size(); i++) {
int idx = str[i] - 'a';
if (!node->children[idx]) break;
node = node->children[idx];
if (node->in_words > 0) max_len = i + 1;
}
return max_len;
}
int main() {
std::ifstream input("trie.in");
std::ofstream output("trie.out");
int op;
std::string str;
while (input >> op >> str) {
if (op == 0) insert(str, 1);
else if (op == 1) insert(str, -1);
else if (op == 2) output << count(str) << '\n';
else output << find_max(str) << '\n';
}
return 0;
}