Pagini recente » Cod sursa (job #3362495) | Cod sursa (job #3362382) | Cod sursa (job #3362732) | Cod sursa (job #3361473) | Cod sursa (job #3362857)
#include <bits/stdc++.h>
using namespace std;
ifstream in ("trie.in");
ofstream out ("trie.out");
struct Trie
{
int words;
int cnt;
Trie* children[26];
Trie()
{
words = 0;
cnt = 0;
for (int i = 0; i < 26; i++)
{
children[i] = nullptr;
}
}
};
void adaug(Trie* root, char* s)
{
if (*s == '\0')
{
root->words++;
root->cnt++;
return;
} else
{
if (root->children[*s - 'a'] == nullptr)
{
root->children[*s - 'a'] = new Trie();
}
root->children[*s - 'a']->cnt++;
adaug(root->children[*s - 'a'], s + 1);
}
}
void sterg(Trie* root, char* s)
{
if(*s == '\0')
{
root->words--;
root->cnt--;
return;
} else
{
if (root->children[*s - 'a'] != nullptr)
{
root->children[*s - 'a']->cnt--;
sterg(root->children[*s - 'a'], s + 1);
}
}
}
int aparitii(Trie* root, char* s)
{
if(*s == '\0')
{
return root->words;
} else
{
if(root->children[*s - 'a'] == nullptr || root->children[*s - 'a']->cnt == 0)
{
return 0;
}
return aparitii(root->children[*s - 'a'], s + 1);
}
}
int val;
int prefix(Trie* root, char* s)
{
if(*s == '\0')
{
return val;
} else
{
if(root->children[*s - 'a'] == nullptr || root->children[*s - 'a']->cnt == 0)
{
return val;
}
val++;
return prefix(root->children[*s - 'a'], s + 1);
}
}
int n;
char s[25];
Trie* root = new Trie();
int main()
{
while(in >> n >> s)
{
if (n == 0)
{
adaug(root, s);
} else if (n == 1)
{
sterg(root, s);
} else if (n == 2)
{
out << aparitii(root, s) << "\n";
} else
{
val = 0;
out << prefix(root, s) << "\n";
}
}
return 0;
}