Pagini recente » Cod sursa (job #1757882) | Cod sursa (job #3281269) | Cod sursa (job #66063) | Cod sursa (job #51743) | Cod sursa (job #2681766)
#include <bits/stdc++.h>
using namespace std;
struct Node {
Node* childs[26];
int counter;
Node() {
counter = 0;
for (int i = 0; i < 26; ++i) {
childs[i] = nullptr;
}
}
};
void insert(Node* node, string s) {
node->counter += 1;
for (auto x : s) {
int pos = x - 'a';
if (node->childs[pos] == nullptr) {
node->childs[pos] = new Node();
}
node = node->childs[pos];
node->counter += 1;
}
}
void erase(Node* node, string s) {
node->counter -= 1;
for (auto x : s) {
int pos = x - 'a';
node = node->childs[pos];
node->counter -= 1;
}
}
int getCounter(Node* node, string s) {
for (auto x : s) {
int pos = x - 'a';
node = node->childs[pos];
}
int answer = node->counter;
for (int i = 0; i < 26; ++i) {
if (node->childs[i] != nullptr) {
answer -= node->childs[i]->counter;
}
}
return answer;
}
int getPrefix(Node* node, string s) {
int length = 0;
for (auto x : s) {
int pos = x - 'a';
if (node->childs[pos] == nullptr or node->childs[pos]->counter == 0) {
return length;
}
node = node->childs[pos];
length += 1;
}
return length;
}
int main()
{
ifstream fin ("trie.in");
ofstream fout ("trie.out");
Node *root = new Node();
int type;
string s;
while (fin >> type >> s) {
if (type == 0) {
insert(root, s);
} else if (type == 1) {
erase(root, s);
} else if (type == 2) {
fout << getCounter(root, s) << '\n';
} else {
fout << getPrefix(root, s) << '\n';
}
}
}