Pagini recente » Cod sursa (job #417981) | Cod sursa (job #898022) | Cod sursa (job #837279) | Cod sursa (job #2943058) | Cod sursa (job #1923554)
#include <fstream>
#include <cstring>
#include <cctype>
#define maxWordLength 20
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
struct node{
int occurences;
struct node *edge[26];
node(){
occurences = 0;
for(int i = 0; i < 26; i++){
edge[i] = NULL;
}
}
};
node *root = new node;
void Insert(char word[]){
node *current = root;
int len = strlen(word), index;
for(int i = 0; i < len; i++, current = current -> edge[index]){
index = tolower(word[i]) - 'a';
if(current -> edge[index] == NULL){
current -> edge[index] = new node;
}
}current -> occurences++;
}
int Search(char word[]){
node *current = root;
int len = strlen(word), index;
for(int i = 0; i < len; i++, current = current -> edge[index]){
index = tolower(word[i]) - 'a';
if(current -> edge[index] == NULL) return 0;
}
return current -> occurences;
}
int LongestPrefix(char word[]){
node *current = root;
int len = strlen(word), index, prefix = 0;
for(int i = 0; i < len; i++, current = current -> edge[index]){
index = tolower(word[i]) - 'a';
if(current -> edge[index] == NULL) break;
prefix++;
}
return prefix;
}
int Sons(node *ptr){
int children = 0;
for(int i = 0; i < 26; i++){
children += !!(ptr -> edge[i]);
}return children;
}
void Delete(char word[]){
int len = strlen(word), index, it = -1, sons;
node *pathStack[maxWordLength + 1], *current = root;
pathStack[++it] = root;
for(int i = 0; i < len; i++, current = current -> edge[index]){
index = tolower(word[i]) - 'a';
if(current -> edge[index] == NULL) return;
pathStack[++it] = current -> edge[index];
}
if(current -> occurences > 1){
current -> occurences--;
return;
}current -> occurences--;
while(it >= 1 && Sons(pathStack[it]) == 0 && pathStack[it] -> occurences == 0) {
pathStack[it - 1] -> edge[tolower(word[it - 1]) - 'a'] = 0;
delete pathStack[it];
it--;
}
}
int main(){
int task;
char word[20];
while(in >> task && in >> word){
switch(task){
case 0:
Insert(word);
break;
case 1:
Delete(word);
break;
case 2:
out << Search(word) << '\n';
break;
case 3:
out << LongestPrefix(word) << '\n';
break;
}
}
return 0;
}