Pagini recente » Cod sursa (job #1377022) | Cod sursa (job #553062) | Cod sursa (job #1976982) | Cod sursa (job #2390369) | Cod sursa (job #1766209)
#include <fstream>
#include <string>
#define f(a) ((a) - 'a')
using namespace std;
typedef struct Trie * Arbore;
const int SIGMA = 27;
struct Trie
{
int count; /// cate se opresc in nod
int count_fii[SIGMA];
Arbore fii[SIGMA];
Trie()
{
for (int i = 0; i < SIGMA; i++)
count_fii[i] = 0, fii[i] = 0;
count = 0;
}
~Trie()
{
for (int i = 0; i < SIGMA; i++)
if (fii[i])
delete fii[i];
}
};
inline void add(string &s);
inline void erase(string &s);
inline int count(string &s);
inline int l_pref(string &s);
Arbore k;
int main()
{
k = new Trie();
string s;
char op;
ifstream in("trie.in");
ofstream out("trie.out");
while (in >> op >> s) {
switch (op) {
case '0':
add(s);
break;
case '1':
erase(s);
break;
case '2':
out << count(s) << '\n';
break;
default:
out << l_pref(s) << '\n';
}
}
return 0;
}
void add(string & s)
{
Arbore x = k;
int p;
for (const char &c : s) {
p = f(c);
if (!x->fii[p])
x->fii[p] = new Trie();
x->count_fii[p]++;
x = x->fii[p];
}
x->count++;
}
void erase(string & s)
{
Arbore x = k;
int p;
for (const char &c : s) {
p = f(c);
if (x->count_fii[p] == 1) {
delete x->fii[p];
x->fii[p] = 0;
x->count_fii[p] = 0;
return;
}
if (!x->fii[p])
return;
x->count_fii[p]--;
x = x->fii[p];
}
x->count--;
}
int count(string & s)
{
Arbore x = k;
int p;
for (const char &c : s) {
p = f(c);
if (!x->fii[p])
return 0;
x = x->fii[p];
}
return x->count;
}
int l_pref(string & s)
{
Arbore x = k;
int l = 0, p;
for (const char &c : s) {
p = f(c);
if (x->fii[p]) {
l++;
x = x->fii[p];
}
else
break;
}
return l;
}