Pagini recente » Cod sursa (job #825097) | Cod sursa (job #1424667) | Cod sursa (job #872597) | Cod sursa (job #2283339) | Cod sursa (job #2142186)
#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, string word) {
if (word.size() == 0) {
node->count++;
return;
}
char c = word[0];
if (node->children.find(c) == node->children.end()) {
node->children[c] = new Trie();
}
add(node->children[c], word.substr(1));
}
bool remove(Trie* node, string word) {
if (word.size() == 0) {
node->count--;
return node->count == 0 && node->children.size() == 0;
}
char c = word[0];
bool rm = remove(node->children[c], word.substr(1));
if (rm) {
node->children.erase(c);
return node->count == 0 && node->children.size() == 0;
}
return false;
}
int search(Trie *node, string word) {
if (word.size() == 0) {
return node->count;
}
char c = word[0];
if (node->children.find(c) == node->children.end()) {
return 0;
}
return search(node->children[c], word.substr(1));
}
int query(Trie *node, string word, int depth) {
if (word.size() == 0) {
return depth;
}
char c = word[0];
if (node->children.find(c) == node->children.end()) {
return depth;
}
return query(node->children[c], word.substr(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);
else if (op == 1) remove(root, word);
else if (op == 2) cout << search(root, word) << endl;
else cout << query(root, word, 0) << endl;
}
return 0;
}