Pagini recente » Ghid infoarena: Wiki | Cod sursa (job #720339) | Cod sursa (job #2785767) | Cod sursa (job #2822564) | Cod sursa (job #3204750)
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
struct TrieNode {
bool is_word;
int count;
TrieNode *children[26];
TrieNode() {
is_word = false;
count = 0;
for (int i = 0; i < 26; i++) {
children[i] = nullptr;
}
}
};
void insert(TrieNode *root, string word) {
for (char c : word) {
int index = c - 'a';
if (root->children[index] == nullptr) {
root->children[index] = new TrieNode();
}
root = root->children[index];
}
root->is_word = true;
root->count++;
}
int find_count(TrieNode *root, string word) {
for (char c : word) {
int index = c - 'a';
if (root->children[index] == nullptr) {
return 0;
}
root = root->children[index];
}
return root->count;
}
int find_longest_prefix(TrieNode *root, string word) {
int longest_prefix = 0;
for (char c : word) {
int index = c - 'a';
if (root->children[index] == nullptr) {
break;
}
root = root->children[index];
longest_prefix++;
}
return longest_prefix;
}
int main() {
ifstream in("trie.in");
ofstream out("trie.out");
TrieNode *root = new TrieNode();
int n;
in >> n;
while (n--) {
int op;
string word;
in >> op >> word;
switch (op) {
case 0:
insert(root, word);
break;
case 1:
if (find_count(root, word) > 0) {
insert(root, word);
}
break;
case 2:
out << find_count(root, word) << endl;
break;
case 3:
out << find_longest_prefix(root, word) << endl;
break;
}
}
in.close();
out.close();
return 0;
}