Cod sursa(job #2845011)

Utilizator Langa_bLanga Radu Langa_b Data 6 februarie 2022 23:16:18
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#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;
}