Pagini recente » Cod sursa (job #3230895) | Cod sursa (job #282073)
Cod sursa(job #282073)
#include <fstream>
#include <string>
#include <cstring>
#include <iterator>
using namespace std;
ifstream fi("trie.in");
ofstream fo("trie.out");
string w;
struct trie { int apar, cuv; trie* r['z'-'a']; } *root;
inline trie *attempt(trie* &where) {
if (where == NULL) {
where = new trie;
memset(where, 0, sizeof(trie));
}
return where;
}
bool rem(trie *p, int poz) {
p->cuv --;
if (poz == w.size()) {
p->apar --;
} else if (rem(p->r[w[poz]-'a'], poz+1) == 1)
p->r[w[poz]-'a'] = NULL;
if (! p->cuv && p != root) {
delete(p);
return 1;
}
return 0;
}
int main()
{
int op, i;
attempt(root);
while (fi >> op >> w) {
trie *p = root;
if (op == 0) {
p->cuv ++;
for (i = 0; i < w.size(); ++i)
(p = attempt(p->r[w[i]-'a'])) -> cuv ++;
p->apar ++;
} else if (op == 1) {
rem(p, 0);
// (eventual p->howmanywords) - nu neaparat
// sterg recursiv ce ramane pe dinafara
} else if (op == 2) {
for (i = 0; i < w.size(); ++i)
p = attempt(p->r[w[i]-'a']);
fo << p->apar << "\n";
} else if (op == 3) {
for (i = 0; i < w.size(); ++i)
if ((p = p->r[w[i]-'a']) == NULL) {
fo << i << "\n";
break;
}
}
}
return 0;
}