Pagini recente » Cod sursa (job #1540681) | Cod sursa (job #1743752) | Cod sursa (job #2611366) | Cod sursa (job #1461957) | Cod sursa (job #794092)
Cod sursa(job #794092)
#include <cstring>
#include <fstream>
#define NUM_CHARS 26
class TrieNode {
public:
TrieNode()
: count(0)
, sonCount(0) {
memset(sons, 0, sizeof(sons));
}
~TrieNode() {
for (int i = 0; i < NUM_CHARS; ++i) {
if (sons[i])
delete sons[i];
}
}
void insert(char* w) {
if (*w == '\0') {
++count;
return;
}
int sonIndex = int(*w - 'a');
if (!sons[sonIndex]) {
sons[sonIndex] = new TrieNode();
++sonCount;
}
sons[sonIndex]->insert(w + 1);
}
void erase(char* w) {
if (*w == '\0') {
--count;
return;
}
int sonIndex = int(*w - 'a');
if (sons[sonIndex]) {
sons[sonIndex]->erase(w + 1);
if (sons[sonIndex]->sonCount == 0 && sons[sonIndex]->count == 0) {
delete sons[sonIndex];
sons[sonIndex] = NULL;
--sonCount;
}
}
}
int getCount(char* w) {
if (*w == '\0') {
return count;
}
int sonIndex = int(*w - 'a');
if (!sons[sonIndex]) {
return 0;
}
return sons[sonIndex]->getCount(w + 1);
}
int getLCP(char *w) {
if (*w == '\0') {
return 0;
}
int sonIndex = int(*w - 'a');
if (!sons[sonIndex]) {
return 0;
}
return sons[sonIndex]->getLCP(w + 1) + 1;
}
private:
TrieNode* sons[NUM_CHARS];
int count;
int sonCount;
};
int main() {
int opId;
char w[20];
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
TrieNode trie;
while (!((fin >> opId >> w).eof())) {
switch (opId) {
case 0: {
trie.insert(w);
break;
}
case 1: {
trie.erase(w);
break;
}
case 2: {
fout << trie.getCount(w) << '\n';
break;
}
case 3: {
fout << trie.getLCP(w) << '\n';
break;
}
}
}
fin.close();
fout.close();
}