Pagini recente » Cod sursa (job #523311) | Cod sursa (job #3154647) | Cod sursa (job #3288054) | Cod sursa (job #266982) | Cod sursa (job #3245547)
#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;
}