HDU 1251 统计难题

  
    
/*
用指针写的最基本的字典树
最基本的字典树
释放内存也没写,第一题字典树
*/

#include
< stdio.h >
#include
< stdlib.h >
#include
< string .h >
const int MAXN = 100000 ;
struct Trie
{
int n; // 记录走过这条路径的单词数量
struct Trie * next[ 26 ];
};
Trie
* root;
void init(Trie * t){ // 初始化函数 所有孩子节点置为空
for ( int i = 0 ; i < 26 ; i ++ ){
t
-> next[i] = NULL;
}
t
-> n = 0 ;
}
void insert( char * str){
Trie
* t = root;
while ( * str){
int i = * str - ' a ' ;
if (t -> next[i] == NULL){
t
-> next[i] = (Trie * )malloc( sizeof (Trie));
init(t
-> next[i]);
t
-> next[i] -> n ++ ;
}
else {
t
-> next[i] -> n ++ ;
}
t
= t -> next[i];
str
++ ;
}
}
int find( char * s){
Trie
* t = root;
while ( * s){
int i = * s - ' a ' ;
if (t -> next[i] == NULL)
return 0 ;
t
= t -> next[i];
s
++ ;
}
return t -> n;
}
int main(){
root
= (Trie * )malloc( sizeof (Trie));
for ( int i = 0 ; i < 26 ; i ++ )
root
-> next[i] = NULL;
root
-> n = 0 ;
char str[ 11 ];
while (gets(str),strcmp(str, "" ) != 0 ){
insert(str);
}
while (gets(str)){
printf(
" %d\n " ,find(str));
}
return 0 ;
}

你可能感兴趣的:(HDU)