Pagini recente » Cod sursa (job #3357813) | Monitorul de evaluare | Cod sursa (job #3357834) | Profil contesSa_girL | Cod sursa (job #3357832)
#include <fstream>
#include <string>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
const int lit = 26;
struct node {
node() {
ap = 0;
pref = 0;
for (int i = 0; i < lit; i++) {
next[i] = nullptr;
}
}
int ap;
int pref;
node* next[lit];
};
void add_word(node* root, const string& word) {
node* curr = root;
for (char c : word) {
int idx = c - 'a';
if (curr->next[idx] == nullptr) {
curr->next[idx] = new node();
}
curr = curr->next[idx];
curr->pref++;
}
curr->ap++;
}
void delete_word(node* root, const string& word) {
node* curr = root;
for (char c : word) {
int idx = c - 'a';
curr = curr->next[idx];
curr->pref--;
}
curr->ap--;
}
int ap_word(node* root, const string& word) {
node* curr = root;
for (char c : word) {
int idx = c - 'a';
if (curr->next[idx] == nullptr) {
return 0;
}
curr = curr->next[idx];
}
return curr->ap;
}
int pref_word(node* root, const string& word) {
node* curr = root;
int lung = 0;
for (char c : word) {
int idx = c - 'a';
if (curr->next[idx] == nullptr || curr->next[idx]->pref == 0) {
return lung;
}
curr = curr->next[idx];
lung++;
}
return lung;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int test;
string word;
node* root = new node();
while (cin >> test >> word) {
if (test == 0) {
add_word(root, word);
} else if (test == 1) {
delete_word(root, word);
} else if (test == 2) {
cout << ap_word(root, word) << '\n';
} else if (test == 3) {
cout << pref_word(root, word) << '\n';
}
}
return 0;
}