Pagini recente » Cod sursa (job #693290) | Cod sursa (job #3133834) | Cod sursa (job #2555427) | Cod sursa (job #709690) | Cod sursa (job #2499001)
#include <fstream>
#include <vector>
#include <string>
using namespace std;
char const in_file[] = "trie.in";
char const out_file[] = "trie.out";
uint8_t const Sigma = 26;
ifstream Read(in_file);
ofstream Write(out_file);
struct Node {
Node *sons[26];
uint32_t count_ends;
uint8_t count_sons;
Node();
};
#include <cstring>
Node::Node() {
memset(sons, 0, sizeof(sons));
//sons.resize(Sigma, nullptr);
count_ends = 0;
count_sons = 0;
}
Node root;
void Insert(
Node &node,
string const &word,
uint8_t const index
) {
if (index == word.size()) {
++node.count_ends;
return;
}
uint8_t ch = word[index] - 'a';
if (node.sons[ch] == nullptr) {
node.sons[ch] = new Node;
++node.count_sons;
}
Insert(*(node.sons[ch]), word, index + 1);
}
void Delete(
Node &node,
string const &word,
uint8_t const index
) {
if (index == word.size()) {
--node.count_ends;
return;
}
uint8_t ch = word[index] - 'a';
Delete(*(node.sons[word[index] - 'a']), word, index + 1);
if (node.sons[ch]->count_ends == 0)
if (node.sons[ch]->count_sons == 0) {
delete node.sons[ch];
node.sons[ch] = nullptr;
--node.count_sons;
}
}
uint32_t Count(
Node &node,
string const &word,
uint8_t const index
) {
if (index == word.size()) {
return node.count_ends;
}
if (node.sons[word[index] - 'a'] != nullptr) {
return Count(*(node.sons[word[index] - 'a']), word, index + 1);
}
return 0;
}
uint16_t PrefixLength(
Node &node,
string const &word,
uint8_t const index
) {
if (index == word.size()) {
return index;
}
if (node.sons[word[index] - 'a'] == nullptr) {
return index;
}
return PrefixLength(*(node.sons[word[index] - 'a']), word, index + 1);
}
int main() {
uint16_t query;
string word;
while (Read >> query >> word) {
if (query == 0) {
Insert(root, word, 0);
}
else if (query == 1) {
Delete(root, word, 0);
}
else if (query == 2) {
Write << Count(root, word, 0) << '\n';
}
else {
Write << PrefixLength(root, word, 0) << '\n';
}
}
Read.close();
Write.close();
return 0;
}