Pagini recente » Borderou de evaluare (job #2681567) | Cod sursa (job #417558) | Cod sursa (job #1553086) | Cod sursa (job #1627692) | Cod sursa (job #419259)
Cod sursa(job #419259)
#include <fstream>
#include <cstring>
#include <assert.h>
using namespace std;
const int SIGMAX = 33;
class node {
public:
node* son[SIGMAX];
int counter, nrSons;
char letter; // debug
node() {
counter = nrSons = letter = 0;
memset(son, 0, sizeof(node*) * SIGMAX);
}
};
class trie {
node root;
bool remRec(node*,const char*);
//node* nextAlpha(const node* a, const char c);
public:
trie() {root.counter = 1;};
void add(char*);
void remove(const char*);
int count(char*);
int maxPrefix(char*);
};
/*node* trie::nextAlpha(const node* a, const char c)
{
if ( !(a -> alpha[c]) ) a -> alpha[c] = new node;
return a -> alpha[c];
}*/
inline int cind1(const char x) { return x - 'a' + 1; }
void trie::add(char *w)
{
node *cn = &root;
for (; *w; ++w) {
int i = cind1(*w);
if (cn -> son[i] == NULL) {
cn -> son[i] = new node;
++ cn->nrSons;
}
cn = cn -> son[i];
cn -> letter = *w; // debug purpose
}
++(cn -> counter);
}
bool trie::remRec(node *a, const char *w)
{
if (!*w) -- a->counter;
else if (remRec(a->son[cind1(*w)], w + 1)) {
a -> son[cind1(*w)] = NULL;
-- a->nrSons;
}
if (! a->nrSons && ! a->counter) {
delete a;
return true;
} else return false;
}
void trie::remove(const char *w)
{ remRec(&root, w); }
int trie::count(char *w)
{
node *cn = &root;
for (; *w && (cn = cn -> son[cind1(*w)]); ++w);
if (cn == NULL) return 0;
else return cn -> counter;
}
int trie::maxPrefix(char *w)
{
node *cn = &root;
int ans = 0;
for (; *w && (cn = cn -> son[cind1(*w)]); ++w, ++ans);
return ans;
}
int main()
{
trie T;
int op; char w[SIGMAX];
ifstream f1("trie.in");
freopen("trie.out", "w", stdout);
while(f1 >> op >> w) {
switch (op) {
case 0: T.add(w); break;
case 1: T.remove(w); break;
case 2: printf("%d\n", T.count(w)); break;
case 3: printf("%d\n", T.maxPrefix(w)); break;
}
}
f1.close();
return 0;
}