Pagini recente » Cod sursa (job #1134168) | Statistici Ceausu Bogdan Constantin (b0by_ceausu) | Numere Sprague-Grundy | Profil usureluflorian | Cod sursa (job #679056)
Cod sursa(job #679056)
#include<fstream>
#include<string.h>
#define dmax 22
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
class trieNode
{
public:
int words;
int prefixes;
trieNode* next[26];
trieNode();
};
trieNode::trieNode()
{
words = 0;
prefixes = 0;
for(int i=0; i<26; i++)
next[i] = NULL;
}
void addWord(char* word, trieNode* trie)
{
int length = strlen(word);
//out<<word<<'\n';
for(int i=0; i<length; i++)
{
int position = word[i] - 'a';
//out<<word[i]<<" ";
if(trie->next[position] != NULL )
{
trie = trie->next[position];
}
else
{
trie->next[position] = new trieNode();
trie = trie->next[position];
}
trie->prefixes++;
//out<<trie->prefixes<<'\n';
}
trie->words++;
}
void deleteWord(char* word, trieNode* trie)
{
int length = strlen(word);
for(int i=0; i<length; i++)
{
int position = word[i] - 'a';
if(trie->next[position] != NULL)
trie = trie->next[position];
trie->prefixes--;
}
trie->words--;
}
int count(char* word, trieNode* trie)
{
//out<<word<<'\n';
int length = strlen(word);
for(int i=0; i<length; i++)
{
int position = word[i] - 'a';
if(trie->next[position] != NULL)
trie = trie->next[position];
else return 0;
}
return trie->words;
}
int prefix(char* word, trieNode* trie)
{
int length = strlen(word);
int i=0;
int position = word[0]-'a';
while(i < length && trie->next[position] != NULL && trie->next[position]->prefixes != 0)
{ if(trie->next[position] != NULL)
trie = trie->next[position];
i++;
position = word[i]-'a';
}
return i;
}
int main()
{
trieNode trie;
while(!in.eof() )
{
int operation;
char word[dmax];
in>>operation>>word;
if(operation == 0)
addWord(word, &trie);
else if(operation == 1)
{
deleteWord(word, &trie);
}
else if(operation == 2)
out<<count(word, &trie)<<'\n';
else if(operation == 3)
out<<prefix(word, &trie)<<'\n';
operation = 4;
}
in.close();
out.close();
return 0;
}