Pagini recente » Cod sursa (job #647387) | Cod sursa (job #1197417) | Cod sursa (job #2094024) | Cod sursa (job #2632822) | Cod sursa (job #2112870)
#include <fstream>
using namespace std;
ofstream fout("trie.out");
ifstream fin("trie.in");
class Trie {
private:
Trie * next[27];
int contor;
int max(int a, int b){
return a >= b ? a : b;
}
public:
Trie(){
contor = 0;
for (int i = 0; i <= 27; i++) {
next[i] = NULL;
}
}
void _insert(char* word) {
if (*word == NULL) {
this->contor++;
return;
}
if (this->next[*word - 'a'] == NULL) {
this->next[*word - 'a'] = new Trie;
}
this->next[*word - 'a']->_insert(word + 1);
}
int _count(char* word) {
if (*word == NULL) {
return this->contor;
}
if (this->next[*word - 'a'] == NULL) {
return 0;
}
this->next[*word - 'a']->_count(word + 1);
}
bool _erase(char* word) {
if (*word == NULL) {
if (this->contor == 0) {
return false;
}
else {
this->contor--;
return true;
}
}
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 <= 25; i++) {
toDelete &= (son->next[i] == NULL);
}
if (toDelete) {
this->next[*word - 'a'] = NULL;
delete son;
}
}
}
int lgPrefix(char* word, int lg) {
if (*word == NULL) {
if (this->contor > 1) {
return lg;
}
else return 0;
}
if (this->next[*word - 'a'] == NULL) {
return 0;
}
if (this->contor > 0) {
return max(lg, this -> next[*word - 'a'] -> lgPrefix(word + 1, lg + 1));
}
int aux = 0;
for (int i = 0; i <= 25; i++) {
if (this->next[i] != NULL)
aux++;
}
if (aux > 1) {
return max(lg, this->next[*word - 'a']->lgPrefix(word + 1, lg + 1));
}
return this->next[*word - 'a']->lgPrefix(word + 1, lg + 1);
}
};
Trie *trie = new Trie();
int main()
{
int o;
char word[30];
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, 1) << '\n'; break;
}
}
return 0;
}