Pagini recente » Cod sursa (job #1974935) | Cod sursa (job #1209230) | Cod sursa (job #2626184) | Cod sursa (job #689903) | Cod sursa (job #2924754)
#include <bits/stdc++.h>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
char Word[100];
struct _trie
{
int nr_ends;
int nr_fii;
_trie *Fiu[26];
_trie () :
nr_ends(),
nr_fii(),
Fiu(),
is_root(false)
{
}
_trie (const char *s)
{
if(strcmp(s, "root") == 0)
_trie(), is_root = true;
}
void insert(const char *word)
{
if(word[0] == '\0') {
this->nr_ends++;
return;
}
const int nr = word[0] - 'a';
if(this->Fiu[nr] == NULL) {
this->Fiu[nr] = new _trie;
this->nr_fii++;
}
this->Fiu[nr]->insert(word + 1);
}
bool remove(const char *word)
{
if(word[0] == '\0') {
this->nr_ends--;
}
else {
const int nr = word[0] - 'a';
if(this->Fiu[nr]->remove(word + 1)) {
delete this->Fiu[nr];
this->nr_fii--;
this->Fiu[nr] = NULL;
}
}
if(this->nr_ends == 0 && this->nr_fii == 0 && !this->is_root) {
return true;
}
return false;
}
int nr_words(const char *word)
{
if(word[0] == '\0') {
return this->nr_ends;
}
const int nr = word[0] - 'a';
if(this->Fiu[nr] == NULL)
return 0;
this->Fiu[nr]->nr_words(word + 1);
}
int prefix_len(const char *word)
{
if(word[0] == '\0') {
return word - Word - 1;
}
const int nr = word[0] - 'a';
if(this->Fiu[nr] == NULL)
return word - Word;
this->Fiu[nr]->prefix_len(word + 1);
}
private:
bool is_root;
};
_trie *root;
void process(const int operation, const char *word)
{
if(operation == 0)
root->insert(word);
if(operation == 1)
root->remove(word);
if(operation == 2)
out << root->nr_words(word) << '\n';
if(operation == 3)
out << root->prefix_len(word) << '\n';
}
int main()
{
root = new _trie("root");
int operation;
while(in >> operation >> Word)
process(operation, Word);
return 0;
}