Pagini recente » Cod sursa (job #295421) | Cod sursa (job #2729230) | Cod sursa (job #1272014) | Cod sursa (job #3233926) | Cod sursa (job #2142210)
#include<iostream>
#include<algorithm>
#include<vector>
#include<unordered_map>
using namespace std;
struct Trie {
int count;
unordered_map<char, Trie*> children;
Trie() {
count = 0;
}
};
void add(Trie *&node, const string& word, int word_index) {
if (word_index == word.size()) {
node->count++;
return;
}
char c = word[word_index];
if (node->children.find(c) == node->children.end()) {
node->children[c] = new Trie();
}
add(node->children[c], word, word_index + 1);
}
bool remove(Trie *&node, const string& word, int word_index) {
if (word_index == word.size()) {
node->count--;
return node->count == 0 && node->children.size() == 0;
}
char c = word[word_index];
bool rm = remove(node->children[c], word, word_index + 1);
if (rm) {
node->children.erase(c);
return node->count == 0 && node->children.size() == 0;
}
return false;
}
int search(Trie *&node, const string& word, int word_index) {
if (word_index == word.size()) {
return node->count;
}
char c = word[word_index];
if (node->children.find(c) == node->children.end()) {
return 0;
}
return search(node->children[c], word, word_index + 1);
}
int query(Trie *&node, const string& word, int word_index, int depth) {
if (word_index == word.size()) {
return depth;
}
char c = word[word_index];
if (node->children.find(c) == node->children.end()) {
return depth;
}
return query(node->children[c], word, word_index + 1, depth + 1);
}
int main() {
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
Trie* root = new Trie();
int op, ret;
string word;
while(cin >> op) {
cin >> word;
if (op == 0) add(root, word, 0);
else if (op == 1) remove(root, word, 0);
else if (op == 2) cout << search(root, word, 0) << endl;
else cout << query(root, word, 0, 0) << endl;
}
return 0;
}