Pagini recente » Cod sursa (job #128525) | Cod sursa (job #2553089) | Cod sursa (job #1908814) | Cod sursa (job #2685814) | Cod sursa (job #2134449)
#include <bits/stdc++.h>
using namespace std;
const int kBuffSize = 1 << 13;
struct Trie {
Trie* son[26];
int num_words, num;
Trie() {
memset(son, 0, sizeof son);
num = 0;
num_words = 0;
}
} *root;
template<class T>
void Allocate(T*& x) {
static char* buff;
static int pointer = kBuffSize;
if (pointer + sizeof(T) >= kBuffSize) {
buff = new char[kBuffSize];
pointer = 0;
}
x = reinterpret_cast<T*>(buff + pointer);
pointer += sizeof(T);
}
void Insert(const string& word, int sign) {
Trie* node = root;
for (auto&& ch : word) {
node->num += sign;
if (node->son[ch - 'a'] == nullptr) {
Allocate(node->son[ch - 'a']);
}
node = node->son[ch - 'a'];
}
node->num_words += sign;
node->num += sign;
}
int Count(const string& word) {
Trie* node = root;
for (auto&& ch : word) {
if (node->son[ch - 'a'] == nullptr) {
return 0;
}
node = node->son[ch - 'a'];
}
return node->num_words;
}
int Lcp(const string& word) {
Trie* node = root;
int lcp = -1;
for (auto&& ch : word) {
if (node != nullptr and node->num > 0) {
++lcp;
} else {
break;
}
node = node->son[ch - 'a'];
}
return lcp;
}
int main() {
ifstream cin("trie.in");
ofstream cout("trie.out");
int op_type; string word;
Allocate(root);
while (cin >> op_type >> word) {
if (op_type == 0) {
Insert(word, +1);
} else if (op_type == 1) {
Insert(word, -1);
} else if (op_type == 2) {
cout << Count(word) << '\n';
} else {
cout << Lcp(word) << '\n';
}
}
return 0;
}