Pagini recente » Cod sursa (job #857787) | Cod sursa (job #430745) | Cod sursa (job #2921285) | Cod sursa (job #1528551) | Cod sursa (job #1448427)
#include <cstdio>
#include <cassert>
#include <cstring>
#include <algorithm>
#include <list>
using namespace std;
#define _submit
#ifdef _submit
#define InFile "trie.in"
#define OtFile "trie.out"
#else
#define InFile "fis.in"
#define OtFile "fis.out"
#endif
class trie {
private:
int c;
list<trie*> next;
public:
trie() {
c = 0;
next.clear();
}
trie(int ch) {
c = ch;
next.clear();
}
void insert(char* word) {
int ch = (int)*word;
if (ch == 0) {
for (auto i = next.begin(); i != next.end(); ++i)
if ((*i)->c & 0x8000) {
(*i)->c++;
return;
}
trie* T = new trie(0x8001);
next.push_back(T);
}
else {
for (auto i = next.begin(); i != next.end(); ++i)
if ((*i)->c == ch) {
(*i)->insert(word + 1);
return;
}
trie* T = new trie(ch);
next.push_back(T);
T->insert(word + 1);
}
}
bool remove(char* word) {
int ch = (int)*word;
if (ch == 0) {
for (auto i = next.begin(); i != next.end(); ++i)
if ((*i)->c & 0x8000) {
(*i)->c--;
if ((((*i)->c) & 0x7FFF) == 0) {
next.erase(i);
if (next.size() == 0)
return true;
}
return false;
}
return false;
}
else {
for (auto i = next.begin(); i != next.end(); ++i)
if ((*i)->c == ch) {
bool tmp = (*i)->remove(word + 1);
if (tmp) {
next.erase(i);
if (next.size() == 0)
return true;
}
return false;
}
return false;
}
return false;
}
int nrap(char* word) {
int ch = (int)*word;
if (ch == 0) {
for (auto i = next.begin(); i != next.end(); ++i)
if ((*i)->c & 0x8000) {
return (((*i)->c) & 0x7FFF);
}
}
else {
for (auto i = next.begin(); i != next.end(); ++i)
if ((*i)->c == ch) {
return (*i)->nrap(word + 1);
}
}
return 0;
}
int longestPrefxLength(char* word) {
int ch = (int)*word;
if (ch == 0)
return 0;
else {
for (auto i = next.begin(); i != next.end(); ++i)
if ((*i)->c == ch) {
return 1 + (*i)->longestPrefxLength(word + 1);
}
}
return 0;
}
};
int main() {
assert(freopen(InFile, "r", stdin));
assert(freopen(OtFile, "w", stdout));
int op;
char w[25];
trie* T = new trie;
while (scanf("%d%s", &op, w) != EOF) {
switch (op)
{
case 0:
T->insert(w);
break;
case 1:
T->remove(w);
break;
case 2:
printf("%d\n", T->nrap(w));
break;
default:
printf("%d\n", T->longestPrefxLength(w));
break;
}
}
return 0;
}