Pagini recente » Statistici Ionescu Nunca Mandache (UCV_Ionescu_Nunca_Mandache) | Cod sursa (job #3190340) | Istoria paginii utilizator/nikopol | Cod sursa (job #2487768) | Cod sursa (job #679040)
Cod sursa(job #679040)
#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);
for(int i=0; i<length; i++)
{
int position = word[i] - 'a';
if(trie->next[position] != NULL )
{
trie = trie->next[position];
trie->prefixes++;
}
else
{
trie->next[position] = new trieNode();
trie = trie->next[position];
trie->prefixes++;
}
}
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--;
}
void count(char* word, trieNode* trie)
{
int length = strlen(word);
for(int i=0; i<length; i++)
{
int position = word[i] - 'a';
if(trie->next[word[i] - 'a'] != NULL)
trie = trie->next[position];
}
out<<trie->words<<'\n';
}
void 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[word[i]- 'a'] != NULL)
trie = trie->next[word[i] - 'a'];
i++;
position = word[i]-'a';
}
out<<i<<'\n';
}
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)
count(word, &trie);
else if(operation == 3)
prefix(word, &trie);
operation = 4;
}
in.close();
out.close();
return 0;
}