Pagini recente » Cod sursa (job #822955) | Cod sursa (job #285967) | Monitorul de evaluare | Istoria paginii utilizator/tudorfrent | Cod sursa (job #2052546)
#include <iostream>
#include <stdio.h>
using namespace std;
class Trie
{
private:
Trie *Edge[27];
int words;
int cEdge;
public:
Trie()
{
for (size_t i = 0; i < 27; i++)
this->Edge[ i ] = 0;
this->words = 0;
this->cEdge = 0;
}
~Trie()
{
}
public:
inline int AlphaToInt(char chr)
{
return chr - 'a';
}
inline void Push(char *str)
{
//printf("[%s]->[%c]->[%d]\n", str, *str, AlphaToInt(*str));
if (*str == 0)
{
this->words++;
return;
}
if (this->Edge[ AlphaToInt(*str) ] == 0)
{
this->Edge[ AlphaToInt(*str) ] = new Trie();
this->cEdge++;
}
this->Edge[ AlphaToInt(*str) ]->Push( str + 1 );
}
inline void Erase(char *str)
{
if (*str == 0)
this->words--;
else if (this->Edge[ AlphaToInt(*str) ])
{
this->Edge[ AlphaToInt(*str) ]->Erase( str + 1);
//Sterg muchia doar daca ea nu mai leaga o alta muchie.
if (this->Edge[ AlphaToInt(*str) ]->cEdge == 0 && this->Edge[ AlphaToInt(*str) ]->words == 0)
{
delete this->Edge[ AlphaToInt(*str) ];
this->Edge[ AlphaToInt(*str) ] = 0;
this->cEdge--;
}
}
}
inline int Query(char *str)
{
if (*str == 0)
return this->words;
if (this->Edge[ AlphaToInt(*str) ])
return this->Edge[ AlphaToInt(*str) ]->Query( str + 1 );
return 0;
}
inline int PrefixLength(char *str)
{
if (*str == 0)
return 0;
if (this->Edge[ AlphaToInt(*str) ])
return 1 + this->Edge[ AlphaToInt(*str) ]->PrefixLength( str + 1 );
return 0;
}
};
int main()
{
FILE * f = fopen("trie.in", "r");
FILE * g = fopen("trie.out", "w");
if (f && g)
{
Trie *T = new Trie();
int p;
char w[30];
fscanf(f, "%d %s", &p, &w);
while (!feof(f))
{
if (p == 0) T->Push(w);
else if (p == 1) T->Erase(w);
else if (p == 2) fprintf(g, "%d\n", T->Query(w));
else if (p == 3) fprintf(g, "%d\n", T->PrefixLength(w));
fscanf(f, "%d %s", &p, &w);
}
fclose(f);
fclose(g);
}
return 0;
}