Pagini recente » Monitorul de evaluare | Cod sursa (job #622745) | Clasament simulareoji_2010_11-12_miercuri | Cod sursa (job #2305853) | Cod sursa (job #2987564)
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
struct TrieNode
{
int counter = 0;
int is_in_words = 0;
TrieNode *children[30] = { NULL };
};
void Push(TrieNode *&root, string word)
{
TrieNode *curr = root;
int len = word.length();
for (int i = 0; i < len; i++)
{
int index = word[i] - 'a';
if (curr -> children[index] == NULL)
{
curr -> children[index] = new TrieNode;
}
curr = curr -> children[index];
curr -> is_in_words++;
}
curr -> counter++;
}
void decrease(TrieNode *root, string word) {
TrieNode *node = root;
for(char c : word) {
if(node->children[c - 'a'] == NULL) {
return;
}
node = node->children[c - 'a'];
node->is_in_words --;
}
if(node->counter > 0)
node->counter --;
}
int search(TrieNode *root, string word) {
TrieNode *node = root;
for(char c : word) {
if(node->children[c - 'a'] == NULL) {
return 0;
}
node = node->children[c - 'a'];
}
return node->counter;
}
int maxPrefixWord(TrieNode *root, string word) {
TrieNode *node = root;
int current_size = 0, maximum = 0;
for(auto c : word) {
if(node->children[c - 'a'] == NULL) {
return maximum;
}
node = node->children[c - 'a'];
current_size ++;
if(node->is_in_words > 0)
maximum = current_size;
}
return maximum;
}
int main()
{
TrieNode *root = new TrieNode;
int query;
while(f >> query) {
string word;
f >> word;
if(query == 0) {
Push(root, word);
} else if(query == 1) {
decrease(root, word);
} else if(query == 2) {
g << search(root, word) << '\n';
} else {
g << maxPrefixWord(root, word) << '\n';
}
}
return 0;
}