Pagini recente » Cod sursa (job #2415622) | Cod sursa (job #3265485) | Cod sursa (job #3260765) | Cod sursa (job #2724100) | Cod sursa (job #3250279)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
#define CH (*s - 'a')
// Trie structure
struct Trie {
int cnt, numberOfChildren;
Trie *child[26];
Trie() {
cnt = numberOfChildren = 0;
memset(child, 0, sizeof(child));
}
};
Trie *T = new Trie;
void ins(Trie *nod, const char *s) {
while (*s != '\0') {
if (nod->child[CH] == 0) {
nod->child[CH] = new Trie;
nod->numberOfChildren++;
}
nod = nod->child[CH];
s++;
}
nod->cnt++;
}
int del(Trie *nod, const char *s) {
if (*s == '\0') {
nod->cnt--;
} else if (del(nod->child[CH], s + 1)) {
nod->child[CH] = 0;
nod->numberOfChildren--;
}
if (nod->cnt == 0 && nod->numberOfChildren == 0 && nod != T) {
delete nod;
return 1;
}
return 0;
}
int que(Trie *nod, const char *s) {
if (*s == '\0') {
return nod->cnt;
}
if (nod->child[CH]) {
return que(nod->child[CH], s + 1);
}
return 0;
}
int pre(Trie *nod, const char *s, int k) {
while (*s != '\0') {
if (nod->child[CH] == 0) break;
nod = nod->child[CH];
s++;
k++;
}
return k;
}
int main() {
ifstream in ("trie.in");
ofstream out ("trie.out");
char operation;
string word;
while (in >> operation >> word) {
switch (operation) {
case '0':
ins(T, word.c_str());
break;
case '1':
del(T, word.c_str());
break;
case '2':
out << que(T, word.c_str()) << '\n';
break;
case '3':
out << pre(T, word.c_str(), 0) << '\n';
break;
}
}
return 0;
}