Pagini recente » Cod sursa (job #671374) | Monitorul de evaluare | Cod sursa (job #3357941) | Cod sursa (job #3357972) | Cod sursa (job #3357794)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
const int ALPHABET = 26;
struct Node {
int words = 0;
int in_words = 0;
Node* children[ALPHABET] = {nullptr};
};
void insert(Node* root, const std::string& str) {
Node* curr = root;
for (char c : str) {
int idx = c - 'a';
if (!curr->children[idx]) {
curr->children[idx] = new Node();
}
curr = curr->children[idx];
curr->in_words++;
}
curr->words++;
}
void remove(Node* root, const std::string& str) {
Node* curr = root;
for (char c : str) {
int idx = c - 'a';
curr = curr->children[idx];
curr->in_words--;
}
curr->words--;
}
int count(Node* root, const std::string& str) {
Node* curr = root;
for (char c : str) {
int idx = c - 'a';
if (!curr->children[idx]) return 0;
curr = curr->children[idx];
}
return curr->words;
}
int find_max(Node* root, const std::string& str) {
Node* curr = root;
int result = 0;
for (int i = 0; i < str.size(); i++) {
int idx = str[i] - 'a';
if (!curr->children[idx] || curr->children[idx]->in_words == 0) break;
curr = curr->children[idx];
if (i > 0) result = i + 1;
}
return result;
}
int main() {
std::ifstream input("trie.in");
std::ofstream output("trie.out");
Node* root = new Node();
int op;
std::string str;
while (input >> op >> str) {
if (op == 0) {
insert(root, str);
} else if (op == 1) {
remove(root, str);
} else if (op == 2) {
output << count(root, str) << '\n';
} else {
output << find_max(root, str) << '\n';
}
}
return 0;
}