Pagini recente » Cod sursa (job #1329837) | Cod sursa (job #1650086) | Cod sursa (job #1685160) | Cod sursa (job #2949206) | Cod sursa (job #2292540)
//
// main.cpp
// Trie
//
#include <iostream>
#include <string>
#include <exception>
using namespace std;
#define CHAR_TO_INDEX(x) (x - 'a')
#define INDEX_TO_CHAR(x) (x + 'a')
class ITrie {
public:
virtual void add(string word) = 0;
virtual void remove(string word) = 0;
virtual int occurences(string word) = 0;
virtual int longestPrefixLength(string word) = 0;
virtual ~ITrie() { }
};
class Trie : public ITrie {
public:
void add(string word) {
auto current = &root;
for (int i = 0; i < word.length(); i++) {
auto pNext = &(current->nodes[CHAR_TO_INDEX(word[i])]);
if(*pNext == nullptr) {
*pNext = new Node(current);
current->allocs += 1;
}
current = *pNext;
}
current->count += 1;
}
void remove(string word) {
auto current = &root;
bool found = true;
for (int i = 0; i < word.length(); i++) {
auto pNext = &(current->nodes[CHAR_TO_INDEX(word[i])]);
if(*pNext == nullptr) {
found = false;
break;
}
current = *pNext;
}
if(!found) {
return;
}
current->count -= 1;
while((current->count == 0) && (current->allocs == 0)) {
auto prev = current->parent;
delete current;
prev->allocs -= 1;
current = prev;
}
}
int occurences(string word) {
auto current = &root;
bool found = true;
for (int i = 0; i < word.length(); i++) {
auto next = current->nodes[CHAR_TO_INDEX(word[i])];
if(next == nullptr) {
found = false;
break;
}
current = next;
}
return found ? current->count : 0;
}
int longestPrefixLength(string word) {
auto current = &root;
int len = 0;
for (int i = 0; i < word.length(); i++) {
auto pNext = &(current->nodes[CHAR_TO_INDEX(word[i])]);
if(*pNext == nullptr) {
break;
}
len += 1;
current = *pNext;
}
return len;
}
~Trie() {
}
private:
struct Node {
int count = 0;
int allocs = 0;
Node* nodes[26] = { nullptr };
Node* parent = nullptr;
Node(Node* parent) {
this->parent = parent;
}
};
Node root = Node(nullptr);
};
int main(int argc, const char * argv[]) {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
ITrie* t = new Trie();
int op; string word;
while((cin >> op >> word))
{
switch (op) {
case 0:
t->add(word);
break;
case 1:
t->remove(word);
break;
case 2:
cout << t->occurences(word) << '\n';
break;
case 3:
cout << t->longestPrefixLength(word) << '\n';
break;
default:
break;
}
}
delete t;
return 0;
}