Pagini recente » Cod sursa (job #2079951) | Cod sursa (job #1784915) | Cod sursa (job #1390936) | Cod sursa (job #3133476) | Cod sursa (job #1696358)
#include <iostream>
#include <fstream>
#define CH (*s - 'a')
using namespace std;
struct NodeTrie
{
unsigned int count = 0, noKids = 0;
NodeTrie *children[26];
};
NodeTrie *trie = new NodeTrie;
void insert(NodeTrie *root, char *s)
{
if (*s == '\0') {
++root->count;
}
else
{
if (root->children[CH] == NULL)
{
root->children[CH] = new NodeTrie;
NodeTrie *init = root->children[CH];
for (unsigned int i = 0; i <= 26; ++i) {
init->children[i] = NULL;
}
++root->noKids;
}
insert(root->children[CH], s + 1);
}
}
unsigned int getWordCount(NodeTrie *root, char *s)
{
if (*s == '\0') {
return root->count;
}
if (root->children[CH] != NULL) {
return getWordCount(root->children[CH], s + 1);
}
return 0;
}
bool erase(NodeTrie *root, char *s)
{
if (*s == '\0') {
--root->count;
}
else
{
if (erase(root->children[CH], s + 1) == true)
{
root->children[CH] = NULL;
--root->noKids;
}
}
if (root->count == 0 && root->noKids == 0 && root != trie)
{
root = NULL;
delete root;
return true;
}
return false;
}
unsigned int getGreatestPrefix(NodeTrie *root, char *s)
{
if (*s == '\0' || root->children[CH] == NULL) {
return 0;
}
return 1 + getGreatestPrefix(root->children[CH], s + 1);
}
int main()
{
ifstream fin("trie.in");
ofstream fout("trie.out");
unsigned int i;
for (i = 0; i <= 26; ++i) {
trie->children[i] = NULL;
}
char op;
char *s = new char;
while (fin >> op >> s)
{
if (op == '0') {
insert(trie, s);
}
else if (op == '1')
{
if (getWordCount(trie, s)) {
erase(trie, s);
}
}
else if (op == '2') {
fout << getWordCount(trie, s) << '\n';
}
else fout << getGreatestPrefix(trie, s) << '\n';
}
fin.close();
fout.close();
return 0;
}