Pagini recente » Cod sursa (job #1551964) | Cod sursa (job #1832971) | Cod sursa (job #611360) | Cod sursa (job #2831282) | Cod sursa (job #2757217)
#include <cstdio>
#include <memory.h>
using namespace std;
class Trie{
public:
Trie() {
memset(children, 0, sizeof(children));
childrenCount = 0;
wordCount = 0;
}
void Add(char *p) {
if (*p == 0) {
++wordCount;
return;
}
if (children[getIndex(p)] == 0) {
children[getIndex(p)] = new Trie();
++childrenCount;
}
children[getIndex(p)]->Add(p + 1);
}
int Count(char *p) {
if (*p == 0) {
return wordCount;
}
if (children[getIndex(p)] == 0)
return 0;
return children[getIndex(p)]->Count(p+1);
}
int Prefix(char *p) {
if (*p == 0 || children[getIndex(p)] == 0) {
return 0;
}
return 1 + children[getIndex(p)]->Prefix(p + 1);
}
void Delete(char *p) {
if (*p == 0) {
--wordCount;
return;
}
children[getIndex(p)]->Delete(p+1);
if (children[getIndex(p)]->wordCount == 0 &&
children[getIndex(p)]->childrenCount == 0) {
delete children[getIndex(p)];
children[getIndex(p)] = 0;
}
}
private:
int getIndex(char *p) {
return *p - 'a';
}
Trie *children[26];
int childrenCount;
int wordCount;
};
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
int op;
char word[30];
Trie T;
while (scanf("%d%s", &op, word) == 2) {
if (op == 0)
T.Add(word);
if (op == 1)
T.Delete(word);
if (op == 2)
printf("%d\n", T.Count(word));
if (op == 3)
printf("%d\n", T.Prefix(word));
}
return 0;
}