Pagini recente » Cod sursa (job #490503) | Cod sursa (job #17872) | Cod sursa (job #115412) | Cod sursa (job #2812066) | Cod sursa (job #1415235)
#include <fstream>
#include <cstring>
typedef struct _trie {
int numberOfWords;
int numberOfPasses;
_trie* nodes[26];
_trie() {
numberOfWords = 0;
numberOfPasses = 0;
for (int i = 0; i<26; i++)
{
nodes[i] = NULL;
}
}
}trie;
using namespace std;
int numberOfWordsGlobal;
void add(trie* root, char* s) {
if (*s == 0) {
root->numberOfWords += 1;
return;
}
if (root->nodes[s[0]-'a'] == NULL)
{
root->nodes[s[0] - 'a'] = new trie;
}
root->nodes[s[0] - 'a']->numberOfPasses += 1;
add(root->nodes[s[0] - 'a'],s+1);
}
void sterge(trie* root, char* s)
{
if (*s == NULL)
{
root->numberOfWords -= 1;
}
else
{
root->nodes[s[0] - 'a']->numberOfPasses -=1;
sterge(root->nodes[s[0] - 'a'],s+1);
}
}
int searchAparitie(trie* root, char*s)
{
if (*s == NULL)
{
return root->numberOfWords;
}
else if (root->nodes[s[0] -'a'] != NULL)
{
return searchAparitie(root->nodes[s[0] - 'a'],s+1);
}
else
{
return 0;
}
}
int getMaxNumber(trie* root,char* s)
{
int rez = 0;
trie t = *root;
for (int i = 0; i<strlen(s); i++)
{
if (t.nodes[s[i] - 'a'] != NULL && t.nodes[s[i]-'a']->numberOfPasses != 0)
{
rez += 1;
t = *(t.nodes[s[i]-'a']);
}
else
{
break;
}
}
return rez;
}
int main() {
int type;
char s[25];
trie* root;
ifstream f("trie.in");
ofstream g("trie.out");
root = new trie;
numberOfWordsGlobal = 0;
while (! f.eof())
{
f>>type>>s;
if (type == 0)
{
++numberOfWordsGlobal;
add(root,s);
}
else if (type == 1)
{
--numberOfWordsGlobal;
sterge(root,s);
}
else if (type == 2)
{
g<<searchAparitie(root,s)<<"\n";
}
else
{
g<<getMaxNumber(root,s)<<"\n";
}
}
return 0;
}