Cod sursa(job #2457198)

Utilizator flibiaVisanu Cristian flibia Data 16 septembrie 2019 21:21:44
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#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);
	}
};

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) {
			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) {
			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;
	Nod *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;
}