Pagini recente » Cod sursa (job #1430718) | Cod sursa (job #2480912) | Cod sursa (job #2680566) | Cod sursa (job #2197945) | Cod sursa (job #3217548)
#include <iostream>
#include <fstream>
#include <stdint.h>
const int32_t MAX_LEN = 20;
const int32_t MAX_OP_COUNT = 100000;
const int32_t MAX_NODE_COUNT = 500000;
struct Node {
int32_t count;
int32_t childCount;
Node* children[26];
};
Node nodeList[MAX_NODE_COUNT];
Node* tree;
Node* freeList;
void Insert(char* str) {
Node* node = tree;
for(; *str; ++str) {
int32_t ind = *str - 'a';
if(!node->children[ind]) {
Node* newNode = freeList;
freeList = newNode->children[0];
newNode->children[0] = nullptr;
node->children[ind] = newNode;
++node->childCount;
}
node = node->children[ind];
}
++node->count;
}
void Erase(char* str) {
Node* node = tree;
Node* stack[MAX_LEN + 1];
int32_t inds[MAX_LEN + 1];
int32_t top = 1;
stack[top] = tree;
inds[top] = -1;
for(; *str; ++str) {
int32_t ind = *str - 'a';
node = node->children[ind];
stack[top] = node;
inds[top] = ind;
++top;
}
--node->count;
--top;
for(; top; --top) {
if(stack[top]->count || stack[top]->childCount)
break;
stack[top - 1]->children[inds[top]] = nullptr;
--stack[top - 1]->childCount;
for(int32_t i = 1; i != 26; ++i)
stack[top]->children[i] = nullptr;
stack[top]->children[0] = freeList;
freeList = stack[top];
}
}
int32_t Find(char* str) {
Node* node = tree;
for(; *str; ++str) {
int32_t ind = *str - 'a';
if(!node->children[ind])
return 0;
node = node->children[ind];
}
return node->count;
}
int32_t Prefix(char* str) {
Node* node = tree;
int32_t len = 0;
for(; str[len]; ++len) {
int32_t ind = str[len] - 'a';
if(!node->children[ind])
break;
node = node->children[ind];
}
return len;
}
int main() {
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
tree = nodeList;
freeList = nodeList + 1;
for(int32_t i = 1; i != MAX_NODE_COUNT - 1; ++i)
nodeList[i].children[0] = nodeList + i + 1;
nodeList[MAX_NODE_COUNT - 1].children[0] = nullptr;
int32_t c;
char str[MAX_LEN + 1];
while(fin >> c) {
fin >> str;
switch(c) {
case 0:
Insert(str);
break;
case 1:
Erase(str);
break;
case 2:
fout << Find(str) << '\n';
break;
case 3:
fout << Prefix(str) << '\n';
break;
}
}
fin.close();
fout.close();
return 0;
}