Pagini recente » Cod sursa (job #1923606) | Cod sursa (job #2181561) | Cod sursa (job #2337711) | Cod sursa (job #3232037) | Cod sursa (job #1308124)
#define IA_PROB "trie"
#include <cstring>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <queue>
#include <stack>
#include <algorithm>
#include <fstream>
#include <iostream>
using namespace std;
class Trie {
private:
const char eow = 'z' + 1;
struct node {
int refcnt;
node* children[27];
node() : refcnt(0) {
memset(children, 0, sizeof(children));
}
} root;
void _remove(node *n, string &word, int i) {
n->refcnt--;
if (i < word.size()) {
node *child = n->children[word[i] - 'a'];
_remove(child, word, i + 1);
if (child->refcnt == 0) {
n->children[word[i] - 'a'] = NULL;
delete child;
}
}
}
public:
void insert(string &word) {
node *n = &root;
n->refcnt++;
word.push_back(eow);
for (char c : word) {
if (n->children[c - 'a'] == NULL) {
n->children[c - 'a'] = new node();
}
n = n->children[c - 'a'];
n->refcnt++;
}
}
void remove(string &word) {
node *n = &root;
n->refcnt--;
word.push_back(eow);
/* we're assuming that word is definitely present;
* otherwise we'd first have to look it up. */
_remove(&root, word, 0);
}
int count(string &word) {
node *n = &root;
word.push_back(eow);
for (char c : word) {
if (n->children[c - 'a'] == NULL) {
return 0;
}
n = n->children[c - 'a'];
}
return n->refcnt;
}
int max_common_prefix_len(string &word) {
int ret = 0;
node *n = &root;
for (char c : word) {
if (n->children[c - 'a'] == NULL) {
break;
}
n = n->children[c - 'a'];
ret++;
}
return ret;
}
};
int main()
{
ifstream in(IA_PROB".in");
ofstream out(IA_PROB".out");
Trie trie;
int op;
string word;
while (in>>op>>word) {
switch (op) {
case 0:
trie.insert(word);
break;
case 1:
trie.remove(word);
break;
case 2:
out<<trie.count(word)<<endl;
break;
case 3:
out<<trie.max_common_prefix_len(word)<<endl;
break;
default:
exit(1);
}
}
return 0;
}