Pagini recente » Cod sursa (job #1307850) | Cod sursa (job #1544489) | Cod sursa (job #1283146) | Cod sursa (job #2004968) | Cod sursa (job #2137409)
#include <fstream>
#include <cstring>
#define CH (*word - 'a')
using namespace std;
ofstream fout("trie.out");
ifstream fin("trie.in");
struct Node{
int cnt;
Node* next[26];
Node(){
cnt = 0;
memset(next, 0, sizeof(next));
}
};
char word[30];
int op;
int lg;
Node* root = new Node();
void add(char* word){
Node* it = root;
while(*word){
if(it -> next[*word - 'a'] == NULL){
it -> next[*word - 'a'] = new Node();
}
it = it -> next[*word - 'a'];
word++;
}
it -> cnt++;
}
bool del(char* word, Node* it){
if (*word == NULL) {
if (it -> cnt == 0) {
return false;
}
else {
it -> cnt--;
return true;
}
}
if (it->next[*word - 'a'] == NULL) {
return false;
}
bool aux = del(word + 1, it->next[*word - 'a']);
if (aux) {
Node* son = it->next[*word - 'a'];
bool toDelete = (son->cnt == 0);
if (toDelete)
for (int i = 0; i < 26; i++) {
toDelete &= (son->next[i] == NULL);
}
if (toDelete) {
delete son;
it->next[*word - 'a'] = NULL;
}
}
}
int aparitii(char* word){
Node* it = root;
while(*word){
if(it -> next[*word - 'a'] == NULL){
return 0;
}
it = it -> next[*word - 'a'];
word++;
}
return it -> cnt;
}
int prefix(char* word, Node* it){
if(*word == NULL){
return lg;
}
if(it -> next[*word - 'a'] == NULL){
return lg;
}
lg++;
return prefix(word + 1, it -> next[*word - 'a']);
lg--;
}
int main()
{
while(fin >> op >> word){
lg = 0;
switch(op){
case 0: add(word); break;
case 1: del(word, root); break;
case 2: fout << aparitii(word) << '\n'; break;
case 3: fout << prefix(word, root) << '\n'; break;
}
}
return 0;
}