Pagini recente » Cod sursa (job #1154964) | Cod sursa (job #1471772) | Cod sursa (job #966896) | Cod sursa (job #718976) | Cod sursa (job #3201841)
#include <bits/stdc++.h>
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
#define SIZE 26
struct TrieNode
{
TrieNode *childrens[SIZE];
int nr_of_letters = 0;
int nr_of_word = 0;
};
TrieNode *create_trie_node()
{
TrieNode *node = new TrieNode;
for (size_t i = 0; i < SIZE; ++i)
node->childrens[i] = nullptr;
return node;
}
void insert(TrieNode *root, std::string word)
{
TrieNode *copy_root = root;
for (char c : word)
{
int index = c - 'a';
if (!copy_root->childrens[index])
copy_root->childrens[index] = create_trie_node();
copy_root->childrens[index]->nr_of_letters++;
copy_root = copy_root->childrens[index];
}
copy_root->nr_of_word++;
}
void erase(TrieNode *root, std::string word)
{
TrieNode *copy_root = root;
for (char c : word)
{
int index = c - 'a';
copy_root->childrens[index]->nr_of_letters--;
copy_root = copy_root->childrens[index];
}
copy_root->nr_of_word--;
}
int search(TrieNode *root, std::string word)
{
TrieNode *copy_root = root;
for (char c : word)
{
int index = c - 'a';
if (!copy_root->childrens[index])
return 0;
copy_root = copy_root->childrens[index];
}
return copy_root->nr_of_word;
}
int search_prefix(TrieNode *root, std::string word)
{
TrieNode *copy_root = root;
int cnt = 0;
for (size_t i = 0; i < word.length(); ++i)
{
int index = word[i] - 'a';
if (!copy_root->childrens[index])
return cnt;
if (copy_root->childrens[index]->nr_of_letters > 0)
cnt = i + 1;
copy_root = copy_root->childrens[index];
}
return cnt;
}
TrieNode *root = create_trie_node();
int main()
{
int x;
std::string s;
while (fin >> x >> s)
{
switch (x)
{
case 0:
insert(root, s);
break;
case 1:
erase(root, s);
break;
case 2:
fout << search(root, s) << "\n";
break;
case 3:
fout << search_prefix(root, s) << "\n";
break;
}
}
return 0;
}