hdu 1251

hdu 1251
#include < stdio.h >
#include
< string .h >
#include
< ctype.h >
const   int  maxN  =   12 ;
char  word[ 4 =   " hat " ;

struct  TreeNode  // 结点
{
    
// char EN_word[maxN];
    TreeNode  * next[ 26 ];
    
int  count;
    TreeNode()
// 构造函数做初始化
    {
        
// EN_word[0]='\0';
        count  =   0 ;
        
for ( int  i = 0 ;i < 26 ;i ++ ) next[i] = NULL;
    }
    
~ TreeNode() // 析构函数做善后工作
    {
        
for ( int  i = 0 ;i < 26 ;i ++ )
            
if (next[i] != NULL) delete next[i];
    }
};
void  insert(TreeNode  *& root, const   char   *  MA_word) // 插入结点
{
    TreeNode 
*  loca = root;
    
int  i = 0 ,ban = 0 ;
    
if (loca == NULL){loca  =   new  TreeNode();root = loca;}
    
int  len = strlen(MA_word);
    
while (MA_word[i])
    {
        ban
= MA_word[i] - ' a ' ;
        
if ( ! loca -> next[ban])
        {
            loca
-> next[ban] = new  TreeNode();
        }
        loca
-> count  ++ ;
        i
++ ;
        loca
= loca -> next[ban];
    }
    loca
-> count  ++ ;
}

void  count(TreeNode  *& root, int   & data)
{
    TreeNode 
*  loca = root;
    
int  i;
    data 
+=  loca -> count;
    
for (i  =   0  ; i  < 26 ; i  ++ )
        
if (loca -> next[i])
            count(loca
-> next[i],data);

}
int  search(TreeNode  *& root, const   char   * keyWord)
{
    TreeNode 
*  loca = root;
    
int  ban = 0 ,j,len  =  strlen(keyWord),data  =   0 ,flag;
    
char  ans[maxN];
    
for (flag  =   0 ,j  =   0  ; j  <  len ; j  ++ ) // 测定前面的len深度 是否有keyword
    {
        ban 
=  keyWord[j] - ' a ' ;
        
if (loca -> next[ban])
         loca 
=  loca -> next[ban];
        
else  
        {
            flag 
=   1 ;
            
break ;
        }/*

 else loca = NULL 以前这里是这样做的 很清楚 这为后来出现内存错误 埋下隐患 
*/
    }
    
if (flag == 0 )
    {
        
         
return  loca -> count;
    }
    
return   0 ;
    
}
int  main()
{
    
// freopen("in.txt","r",stdin);
     int  n,i;
    
char  c;
    
char  str1[maxN],str2[maxN];
    
struct  TreeNode  * headNode  =  NULL;
    
while ( 1 )
    {
        gets(str1);
        
if (strcmp(str1, "" ) == 0 )
            
break ;
        insert(headNode,str1);
    }
    
while (scanf( " %s " ,str1) != EOF)
    {
        printf(
" %d\n " ,search(headNode,str1));
    }
    
return   0 ;
}

你可能感兴趣的:(hdu 1251)