Pagini recente » Cod sursa (job #2722885) | Cod sursa (job #1728954) | Cod sursa (job #2765446) | Cod sursa (job #1203579) | Cod sursa (job #2172330)
#include <fstream>
#include <cstring>
using namespace std;
ofstream fout("trie.out");
ifstream fin("trie.in");
class Trie {
private:
Trie * next[26];
int contor;
int max(int a, int b){
return a >= b ? a : b;
}
public:
Trie(){
contor = 0;
memset(next, 0, sizeof(next));
}
void _insert(char* word) {
Trie *pos= this;
while(*word != 0){
if (pos->next[*word - 'a'] == NULL) {
pos->next[*word - 'a'] = new Trie();
}
pos = pos->next[*word - 'a'];
word++;
}
pos->contor++;
}
int _count(char* word) {
Trie *pos= this;
while(*word != 0){
if (pos->next[*word - 'a'] == NULL) {
return 0;
}
pos = pos->next[*word - 'a'];
word++;
}
return pos->contor;
}
bool _erase(char* word) {
if (*word == 0) {
if (this->contor == 0) {
return false;
}
else {
this->contor--;
return (this->contor ==0);
}
}
if (this->next[*word - 'a'] == NULL) {
return false;
}
bool aux = this->next[*word - 'a']->_erase(word + 1);
if (aux) {
Trie* son = this->next[*word - 'a'];
bool toDelete = (son->contor == 0);
if (toDelete)
for (int i = 0; i < 26; i++) {
toDelete &= (son->next[i] == NULL);
}
if (toDelete) {
delete son;
this->next[*word - 'a'] = NULL;
}
}
return aux;
}
int lgPrefix(char* word, int lg) {
if (*word == NULL) {
return lg;
}
if (this->next[*word - 'a'] == NULL) {
return lg;
}
return this->next[*word - 'a']->lgPrefix(word + 1, lg + 1);
}
};
Trie *trie = new Trie();
char word[25];
int main()
{
int o;
while (fin >> o >> word) {
switch (o) {
case 0: trie->_insert(word); break;
case 1: trie->_erase(word); break;
case 2: fout << trie->_count(word) << '\n'; break;
case 3: fout << trie->lgPrefix(word, 0) << '\n'; break;
}
}
return 0;
}