Pagini recente » Cod sursa (job #3218987) | Cod sursa (job #1077508) | Cod sursa (job #3220813) | Cod sursa (job #3212508) | Cod sursa (job #2605667)
#include <stdio.h>
#include <stdlib.h>
typedef struct TrieStruct{
int wordsEndHere;
int wordsContained;
struct TrieStruct *next[27];
}Trie;
void add_trie(Trie *crtNode, char *word){
crtNode->wordsContained ++;
if(*word == 0){
crtNode->wordsEndHere ++;
return;
}
int nextIndex = *word - 'a';
if(crtNode->next[nextIndex] == NULL)
crtNode->next[nextIndex] = calloc(1, sizeof(Trie));
add_trie(crtNode->next[nextIndex], word + 1);
}
void rmv_trie(Trie *crtNode, char *word){
crtNode->wordsContained --;
if(*word == 0){
crtNode->wordsEndHere --;
return;
}
int nextIndex = *word - 'a';
add_trie(crtNode->next[nextIndex], word + 1);
}
int appeared_trie(Trie *crtNode, char *word){
if(*word == 0){
return crtNode->wordsEndHere;
}
int nextIndex = *word - 'a';
if(crtNode->next[nextIndex] == NULL)
return 0;
return appeared_trie(crtNode->next[nextIndex], word + 1);
}
int longest_common_prefix(Trie *crtNode, char *word){
if(*word == 0){
return crtNode->wordsContained >= 1;
}
int nextIndex = *word - 'a';
if(crtNode->next[nextIndex] == NULL)
return 1;
return 1 + longest_common_prefix(crtNode->next[nextIndex], word + 1);
}
int main()
{
FILE *in = fopen("trie.in", "r");
FILE *out = fopen("trie.out", "w");
Trie *trie = calloc(1, sizeof(Trie));
int type, sol;
char word[100];
while(fscanf(in, "%d %s", &type, &word) == 2){
switch(type){
case 0:
add_trie(trie, word);
break;
case 1:
rmv_trie(trie, word);
break;
case 2:
fprintf(out, "%d\n", appeared_trie(trie, word));
break;
case 3:
sol = longest_common_prefix(trie, word);
if(sol)
sol --;
fprintf(out, "%d\n", sol);
break;
}
}
return 0;
}