hdu 1251 字典树

开始的时候没有用字典树WA了好多次,学了之后马上就A了,哈哈哈哈爽!

#include <iostream>
 #include"stdio.h"
 #include"string.h"
 #include"stdlib.h"
 
 using namespace std;
 
 const int MAX = 26;
 
 struct Tree{
     struct Tree *next[MAX];
     int number;
 };
 
 void init( struct Tree *t ){
     for( int j = 0; j < MAX; j++ ){
         t->next[j] = 0;
     }
     t->number = 0;
 }
 
 void add( struct Tree *t, char a[] ){
     int length = strlen( a );
     struct Tree *p = t;
     for( int i = 0; i < length; i++ ){
         if( p->next[a[i]-'a'] == 0 ){
             p->next[a[i]-'a'] = (struct Tree*)malloc( sizeof( struct Tree ) );
             p = p->next[a[i]-'a'];
             for( int j = 0; j < MAX; j++ ){
                 p->next[j] = 0;
             }
             p->number = 1;
         }else{
             p = p->next[a[i]-'a'];
             p->number++;
         }
     }
 }
 
 int find( struct Tree *t, char a[] ){
     int length = strlen( a );
     struct Tree *p = t;
     for( int i = 0; i < length; i++ ){
         if( p->next[a[i]-'a'] == 0 ){
             return 0;
         }else{
             p = p->next[a[i]-'a'];
         }
     }
     return p->number;
 }
 
 int main(){
     struct Tree t;
     char a[111];
     init(&t);
     for( int i = 0; ; i++ ){
         gets(a);
 
         if( strcmp( a, "" ) == 0 ){
             break;
         }
         add( &t, a );
     }
     for( ;; ){
         if( gets(a) == 0 ){
             break;
         }
         printf( "%d\n", find( &t, a ) );
     }
 
 }


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值