Cod sursa(job #3245547)

Utilizator CosminaneBoac Mihai Cosmin Cosminane Data 29 septembrie 2024 13:16:47
Problema Trie Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <iostream>
using namespace std;
struct trie {
	int capat = 0, leaves = 0;
	trie *v[26] = {};
};
trie *insert(trie *x, string s, int poz) {
	x->leaves++;
	if (poz == s.size()) {
		x->capat++;
	}
	else {
		if (!x->v[s[poz] - 'a']) {
			x->v[s[poz] - 'a'] = new trie;
		}
		x->v[s[poz] - 'a'] = insert(x->v[s[poz] - 'a'], s, poz + 1);
	}
	return x;
}
trie* erase(trie *x, string s, int poz) {
	//cout << poz << ' ' << s.size() << ' ' << x->leaves << '\n';
	x->leaves--;
	if (poz == s.size()) {
		x->capat--;
	}
	else {
		x->v[s[poz] - 'a'] = erase(x->v[s[poz] - 'a'], s, poz + 1);
		if (x->v[s[poz] - 'a']->leaves == 0) {
			delete x->v[s[poz] - 'a'];
			x->v[s[poz] - 'a'] = nullptr;
		}
	}
	return x;
}
int find(trie *x, string s, int poz) {
	if (poz == s.size()) {
		return x->capat;
	}
	if (!x->v[s[poz] - 'a']) {
		return 0;
	}
	return find( x->v[s[poz] - 'a'], s, poz + 1 );
}
int prefix(trie* x, string s, int poz) {
	//cout << poz << ' ' << s << '\n';
	if (poz == s.size() || !x->v[s[poz] - 'a']) {
		return 0;
	}
	return 1 + prefix( x->v[s[poz] - 'a'], s, poz + 1 );
}
int main() {
	int tip;
	string s;
	trie *root = new trie;
	ifstream fin( "trie.in" );
	ofstream fout( "trie.out" );
	while (fin >> tip >> s) {
		if (tip == 0) {
			root = insert( root, s, 0 );
		}
		else if (tip == 1) {
			root = erase( root, s, 0 );
		}
		else if (tip == 2) {
			fout << find( root, s, 0 ) << '\n';
		}
		else {
			fout << prefix( root, s, 0 ) << '\n';
		}
	}
	return 0;
}