Pagini recente » Borderou de evaluare (job #760896) | Autentificare | Profil Pushkin | Siruri Ordonate | Cod sursa (job #3318337)
#include <iostream>
#include <fstream>
#include <stdint.h>
const int32_t ALPHABET_SIZE = 26;
const int32_t MAX_LEN = 20;
const int32_t MAX_TOTAL = 200001;
struct Node {
int32_t count;
int32_t endCount;
int32_t children[ALPHABET_SIZE];
};
Node nodes[MAX_TOTAL];
int32_t freeListStart;
int32_t AllocNode() {
int32_t node = freeListStart;
freeListStart = nodes[node].children[0];
nodes[node].count = 0;
nodes[node].endCount = 0;
for(int32_t i = 0; i != ALPHABET_SIZE; ++i)
nodes[node].children[i] = -1;
return node;
}
void FreeNode(int32_t node) {
nodes[node].children[0] = freeListStart;
freeListStart = node;
}
int main() {
std::ifstream fin("trie.in");
std::ofstream fout("trie.out");
freeListStart = 0;
for(int32_t i = 0; i != MAX_TOTAL - 1; ++i)
nodes[i].children[0] = i + 1;
nodes[MAX_TOTAL - 1].children[0] = -1;
int32_t root = AllocNode();
int32_t c;
char w[MAX_LEN + 1];
while(fin >> c) {
fin >> w;
if(c == 0) {
int32_t ind = root;
for(int32_t i = 0; w[i]; ++i) {
if(nodes[ind].children[w[i] - 'a'] == -1)
nodes[ind].children[w[i] - 'a'] = AllocNode();
ind = nodes[ind].children[w[i] - 'a'];
++nodes[ind].count;
}
++nodes[ind].endCount;
} else if(c == 1) {
int32_t stack[MAX_LEN + 1], top = 1;
stack[0] = root;
for(int32_t i = 0; w[i]; ++i) {
if(nodes[stack[top - 1]].children[w[i] - 'a'] == -1)
nodes[stack[top - 1]].children[w[i] - 'a'] = AllocNode();
stack[top] = nodes[stack[top - 1]].children[w[i] - 'a'];
++top;
}
--nodes[stack[top - 1]].endCount;
for(int32_t i = top - 1; i; --i) {
--nodes[stack[i]].count;
if(!nodes[stack[i]].count) {
FreeNode(stack[i]);
nodes[stack[i - 1]].children[w[i - 1] - 'a'] = -1;
}
}
} else if(c == 2) {
int32_t ind = root;
for(int32_t i = 0; w[i]; ++i) {
if(nodes[ind].children[w[i] - 'a'] == -1) {
ind = -1;
break;
}
ind = nodes[ind].children[w[i] - 'a'];
}
if(ind != -1 && !nodes[ind].endCount)
ind = -1;
int32_t count;
if(ind != -1) {
count = nodes[ind].count;
} else {
count = 0;
}
fout << count << '\n';
} else if(c == 3) {
int32_t ind = root, len = 0;
for(int32_t i = 0; w[i]; ++i) {
if(nodes[ind].children[w[i] - 'a'] == -1)
break;
ind = nodes[ind].children[w[i] - 'a'];
++len;
}
fout << len << '\n';
}
}
fin.close();
fout.close();
return 0;
}