Cod sursa(job #2410168)

Utilizator LucaSeriSeritan Luca LucaSeri Data 19 aprilie 2019 19:49:19
Problema Trie Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
 
using namespace std;

const int SIGMA = 26;

struct nod {
	nod *fii[SIGMA];
	int cnt = 0;
	int cnt2 = 0;
	nod () {
		for(int i = 0; i < SIGMA; ++i) fii[i] = 0;
		cnt = 0;
	}
};
string s;
void modif(nod *&n, int i, int val) {
	if(i == s.size()) {
		n->cnt2 += val;
		n->cnt += val;
		return;
	}

	n->cnt += val;
	if(!n->fii[s[i]-'a']) n->fii[s[i]-'a'] = new nod();

	modif(n->fii[s[i]-'a'], i + 1, val);

	if(n->cnt == 0) {
		delete(n);
		n = 0;
	}
}

int apar(nod *&n, int i) {
	if(i == s.size()) {
		return n->cnt2;
	}

	if(!n->fii[s[i]-'a']) return 0;
	return apar(n->fii[s[i]-'a'], i + 1);
}

int lcp(nod *&n, int i) {
	if(n->cnt == 0) return i-1;
	if(i == s.size()) return i;
	if(!n->fii[s[i]-'a']) return i;
	return lcp(n->fii[s[i]-'a'], i + 1);
}

int main() {
	#ifdef BLAT
		freopen("input", "r", stdin);
	#else
		freopen("trie.in", "r", stdin);
		freopen("trie.out", "w", stdout);
	#endif
 
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	nod* root = new nod();

	int t;
	while(cin >> t) {
		cin >> s;
		if(t == 0) {
			modif(root, 0, 1);
		}
		if(t == 1) {
			modif(root, 0, -1);
		}
		if(t == 2) {
			cout << apar(root, 0) << '\n';
		}
		if(t == 3) {
			cout << lcp(root, 0) << '\n';
		}
	}
	return 0;
}