HDU Problem - 1251 統計難題

Language : c++


Standard Trie













#include<stdio.h>
#include<string.h>
#include<stdlib.h>

#define LOCAL

typedef struct node{
    int count;
    struct node *next[26];
}tree;

char str[12];
tree root;
int size;
 
void add_to_tree(char *str);
int sum_num(char *str);

int main(void){
	
#ifdef LOCAL
		freopen("datain.txt","r",stdin);
#endif

    size = sizeof(tree);
    memset(&root,0,size);
    while(gets(str) && str[0]!='\0')
            add_to_tree(str);
    while(scanf("%s",str)!=EOF)
            printf("%d\n",sum_num(str));
    return 0;
}
//add the word to the tree;
void add_to_tree(char *str){
    int len = strlen(str);
    tree *pointer = &root;
    pointer->count++;            
    int i;
    for(i=0;i<len;++i){    
        if(pointer->next[str[i]-'a'] == NULL){
            pointer->next[str[i]-'a'] = (tree *)malloc(size);
            memset(pointer->next[str[i]-'a'],0,size);
        }
        pointer = pointer->next[str[i]-'a'];            
        pointer->count++;
    }
}

//find the number of words which contain this prefix;
int sum_num(char *str){
    int len=strlen(str);
    tree *pointer = &root;
    int i;
    for(i=0;i<len;++i){
        pointer = pointer->next[str[i]-'a'];
        if(pointer==NULL)
            return 0;
    }
    return pointer->count;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章