Pagini recente » Cod sursa (job #1996230) | Cod sursa (job #401899) | Cod sursa (job #11304) | Cod sursa (job #2151971) | Cod sursa (job #2579499)
#include<fstream>
#include<iostream>
#include<vector>
using namespace std;
struct trie {
int nr_words, nr_sons;
vector <trie*> sons;
trie() {
nr_words = 0;
nr_sons = 0;
sons = vector <trie*>(26, 0);
}
};
void display_oper(vector <pair <int, string>> &oper) {
for (int i = 0; i < (int) oper.size(); i++)
cout << oper[i].first << " " << oper[i].second << "\n";
}
void add_word(trie* t, string s) {
if (s == "") {
t->nr_words++;
return;
}
int c = s[0] - 'a';
if (t->sons[c] == 0) {
t->sons[c] = new trie();
t->nr_sons++;
}
add_word(t->sons[c], s.erase(0, 1));
}
int delete_word(trie* t, string s, const trie* root) {
if (s == "") {
t->nr_words--;
} else {
int c = s[0] - 'a';
int is_total_delete = delete_word(t->sons[c], s.erase(0, 1), root);
if ( is_total_delete == 1) {
t->sons[c] = 0;
t->nr_sons--;
}
}
if (t->nr_words == 0 && t->nr_sons == 0 && t != root) {
delete t;
return 1;
}
return 0;
}
int count_word(trie* t, string s) {
if (s == "")
return t->nr_words;
int c = s[0] - 'a';
if (t->sons[c] == 0)
return 0;
return count_word(t->sons[c], s.erase(0, 1));
}
int find_prefix(trie *t, string s, int count) {
if (s == "") {
return count;
}
int c = s[0] - 'a';
if (t->sons[c] == 0) {
return count;
}
return find_prefix(t->sons[c], s.erase(0, 1), count + 1);
}
int main() {
ifstream fin("trie.in");
ofstream fout("trie.out");
vector <pair <int, string>> oper;
while(true) {
int code; fin >> code;
string word; fin >> word;
if (fin.eof())
break;
oper.push_back({code, word});
}
// display_oper(oper);
trie* t;
t = new trie();
for (int i = 0; i < (int) oper.size(); i++) {
if (oper[i].first == 0) {
add_word(t, oper[i].second);
} else if (oper[i].first == 1) {
delete_word(t, oper[i].second, t);
} else if (oper[i].first == 2) {
fout << count_word(t, oper[i].second) << "\n";
} else if (oper[i].first == 3) {
fout << find_prefix(t, oper[i].second, 0) << "\n";
}
}
return 0;
}