Pagini recente » Cod sursa (job #2381724) | Cod sursa (job #1671191) | Cod sursa (job #2362360) | Cod sursa (job #2521491) | Cod sursa (job #2224773)
#include <bits/stdc++.h>
using namespace std;
constexpr int SIGMA = 26;
class Trie{
private:
class Node{
public:
vector<Node*> children;
int cnt;
int num_kids;
Node(){
cnt = 0;
num_kids = 0;
children.resize(SIGMA);
}
};
Node* root;
public:
Trie(){
root = new Node();
}
void insert(const string& text){
Node* node = root;
for (char c: text){
int id = c - 'a';
if (node->children[id] == nullptr){
node->num_kids++;
node->children[id] = new Node();
}
node = node->children[id];
}
node->cnt++;
}
void erase(const string& text){
Node* node = root;
vector<Node*> path;
for (char c: text){
path.push_back(node);
int id = c - 'a';
if (node->children[id] == nullptr){
return;
}
node = node->children[id];
}
path.push_back(node);
node->cnt--;
int k = (int)path.size() - 1;
while (node->cnt == 0 && node->num_kids == 0){
if (node == root)
break;
auto parent = path[--k];
for (auto &c: parent->children)
if (c == node){
parent->num_kids--;
delete c;
c = nullptr;
break;
}
node = parent;
}
}
int maxPrefix(const string& text){
Node* node = root;
int k = 0;
for (char c: text){
int id = c - 'a';
if (node->children[id] == nullptr){
return k;
}
k++;
node = node->children[id];
}
return k;
}
int count(const string& text){
Node* node = root;
for (char c: text){
int id = c - 'a';
if (node->children[id] == nullptr){
return 0;
}
node = node->children[id];
}
return node->cnt;
}
};
int main() {
// ifstream cin("data.txt");
ifstream cin("trie.in");
ofstream cout("trie.out");
ios_base::sync_with_stdio(false);
int t;
string text;
Trie trie;
while (cin >> t >> text){
if (t == 0){
trie.insert(text);
}
else if (t == 1){
trie.erase(text);
}
else if (t == 2){
cout << trie.count(text) << "\n";
}
else{
cout << trie.maxPrefix(text) << "\n";
}
}
return 0;
}