Pagini recente » Cod sursa (job #3334070) | Cod sursa (job #2463764) | Cod sursa (job #3339260) | Cod sursa (job #3149164) | Cod sursa (job #3321535)
#include <iostream>
#include <fstream>
#include <cstring>
// #include <memory>
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
const int alphabet_size = 30;
class nod{
public:
nod * next[alphabet_size];
int ct, end;
nod() : ct(0), end(0)
{
for(int i = 0; i < alphabet_size; i++)
this->next[i] = NULL;
}
};
void add(nod *nod_trie, std::string &s, int poz)
{
nod_trie->ct ++;
if(poz == s.size())
{
nod_trie->end ++;
return;
}
int letter = s[poz] - 'a';
if(nod_trie->next[letter] == NULL)
{
nod *new_nod = new nod;
nod_trie->next[letter] = new_nod;
}
add(nod_trie->next[letter], s, poz + 1);
}
void del(nod *nod_trie, std::string &s, int poz)
{
nod_trie->ct --;
if(poz == s.size())
{
nod_trie->end--;
return;
}
int letter = s[poz] - 'a';
del(nod_trie->next[letter], s, poz + 1);
if(nod_trie->next[letter]->ct == 0)
{
delete nod_trie->next[letter];
nod_trie->next[letter] = NULL;
}
}
int count_word(std::string &word, int index, nod *current_node)
{
if(current_node == NULL)
return 0;
if(index == word.size())
return current_node->end;
int letter = word[index] - 'a';
return count_word(word, index + 1, current_node->next[letter]);
}
int longest_common_prefix_for_word(std::string &word, int index, nod *current_node)
{
if( current_node == NULL or index == word.size())
return 0;
int letter = word[index] - 'a';
if(current_node->next[letter] != NULL)
return 1 + longest_common_prefix_for_word(word, index + 1, current_node->next[letter]);
return 0;
}
int main()
{
nod *start_trie = new nod;
int op;
std::string s;
while(fin >> op >> s)
{
op++;
if(op == 1)
add(start_trie, s, 0);
else if(op == 2)
del(start_trie, s, 0);
else if(op == 3)
fout << count_word(s, 0, start_trie) << "\n";
else
fout << longest_common_prefix_for_word( s, 0, start_trie) << "\n";
}
fin.close();
fout.close();
return 0;
// execpt
}