Pagini recente » Cod sursa (job #1040765) | Cod sursa (job #1668992) | Cod sursa (job #1094551) | Cod sursa (job #797963) | Cod sursa (job #2457200)
#include <bits/stdc++.h>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct Nod {
int nrSon;
int nrCuv;
Nod *son[27];
Nod() {
nrCuv = 0;
nrSon = 0;
memset(son, 0, sizeof son);
}
};
Nod *root;
void add(Nod *nod, const string& s, int pos) {
if (pos == (int) s.size()) {
nod->nrCuv++;
return;
}
if (nod->son[s[pos] - 'a'] == NULL) {
nod->son[s[pos] - 'a'] = new Nod();
nod->nrSon++;
}
add(nod->son[s[pos] - 'a'], s, pos + 1);
}
bool erase(Nod *nod, const string& s, int pos) {
if (pos == (int) s.size()) {
nod->nrCuv--;
if (nod->nrSon == 0 && nod->nrCuv == 0 && nod != root) {
delete nod;
return 1;
}
return 0;
}
if (erase(nod->son[s[pos] - 'a'], s, pos + 1)) {
nod->nrSon--;
nod->son[s[pos] - 'a'] = NULL;
if (nod->nrSon == 0 && nod->nrCuv == 0 && nod != root) {
delete nod;
return 1;
}
return 0;
}
return 0;
}
int nrap(Nod *nod, const string& s, int pos) {
if (pos == (int) s.size())
return nod->nrCuv;
if (nod->son[s[pos] - 'a'] == NULL)
return 0;
return nrap(nod->son[s[pos] - 'a'], s, pos + 1);
}
int pref(Nod *nod, const string& s, int pos) {
if (pos == (int) s.size())
return 0;
if (nod->son[s[pos] - 'a'] == NULL)
return 0;
return 1 + pref(nod->son[s[pos] - 'a'], s, pos + 1);
}
int main() {
int ch;
string s;
root = new Nod();
while (in >> ch >> s) {
switch (ch) {
case 0:
add(root, s, 0);
break;
case 1:
erase(root, s, 0);
break;
case 2:
out << nrap(root, s, 0) << '\n';
break;
case 3:
out << pref(root, s, 0) << '\n';
break;
}
}
return 0;
}