Pagini recente » Cod sursa (job #1412088) | Cod sursa (job #558500) | Cod sursa (job #3235527) | Cod sursa (job #380526) | Cod sursa (job #2845011)
#include <fstream>
#include <string>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
string str;
int ans = 0;
struct trie {
int cnt, nrfii;
trie* fii[26];
trie() {
nrfii = 0;
cnt = 0;
memset(fii, NULL, sizeof(fii));
}
};
trie *t = new trie;
void ad(trie *act, int pos) {
int pozitie;
if (pos == str.size() - 1) {
if ( str[pos] >= 'a' && str[pos] <= 'z' && act->fii[str[pos] - 'a'] == NULL) {
act->fii[str[pos] - 'a'] = new trie;
act->nrfii++; //*********
}
act->fii[str[pos] - 'a']->cnt++;
return;
}
if (pos < str.size() && str[pos] >='a' && str[pos] <= 'z') {
if (act->fii[str[pos] - 'a'] == NULL) {
act->fii[str[pos] - 'a'] = new trie;
act->nrfii++;
}
}
if ((pos < str.size() - 1)) {
pozitie = str[pos] - 'a';
ad(act->fii[pozitie], pos + 1);
}
}
bool del(trie* act, int pos) {
if (pos <= str.size() - 1 && str[pos] >= 'a' && str[pos] <= 'z') {
if (del(act->fii[str[pos] - 'a'], pos + 1) == 1) {
act->nrfii--;
act->fii[str[pos] - 'a'] = NULL;
}
}
if (pos == str.size()) {
act->cnt--;
}
if (act->cnt == 0 && act->nrfii == 0 && act != t) {
delete act;
return 1;
}
return 0;
}
void fi(trie* act, int pos) {
if (pos == str.size()) {
ans = act->cnt;
}
else {
if (pos < str.size() && str[pos] >= 'a' && str[pos] <= 'z') {
if (act->fii[str[pos] - 'a'] == NULL) {
ans = -1;
return;
}
else {
fi(act->fii[str[pos] - 'a'], pos + 1);
}
}
}
}
void pre(trie* act, int pos) {
if (pos < str.size() && str[pos] >= 'a' && str[pos] <= 'z') {
if (act->fii[str[pos] - 'a'] != NULL) {
ans++;
pre(act->fii[str[pos] - 'a'], pos + 1);
}
}
}
int main() {
while (getline(cin, str)) {
if (str[0] == '0') {
ad(t, 2);
}
if (str[0] == '1') {
del(t, 2);
}
if (str[0] == '2') {
fi(t, 2);
cout << ans << '\n';
}
if (str[0] == '3') {
ans = 0;
pre(t, 2);
cout << ans << '\n';
}
}
delete t;
}