字典树 hdu 1251

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

 1 #include <iostream>
 2 #include"stdio.h"
 3 #include"string.h"
 4 #include"stdlib.h"
 5 
 6 using namespace std;
 7 
 8 const int MAX = 26;
 9 
10 struct Tree{
11     struct Tree *next[MAX];
12     int number;
13 };
14 
15 void init( struct Tree *t ){
16     for( int j = 0; j < MAX; j++ ){
17         t->next[j] = 0;
18     }
19     t->number = 0;
20 }
21 
22 void add( struct Tree *t, char a[] ){
23     int length = strlen( a );
24     struct Tree *p = t;
25     for( int i = 0; i < length; i++ ){
26         if( p->next[a[i]-'a'] == 0 ){
27             p->next[a[i]-'a'] = (struct Tree*)malloc( sizeof( struct Tree ) );
28             p = p->next[a[i]-'a'];
29             for( int j = 0; j < MAX; j++ ){
30                 p->next[j] = 0;
31             }
32             p->number = 1;
33         }else{
34             p = p->next[a[i]-'a'];
35             p->number++;
36         }
37     }
38 }
39 
40 int find( struct Tree *t, char a[] ){
41     int length = strlen( a );
42     struct Tree *p = t;
43     for( int i = 0; i < length; i++ ){
44         if( p->next[a[i]-'a'] == 0 ){
45             return 0;
46         }else{
47             p = p->next[a[i]-'a'];
48         }
49     }
50     return p->number;
51 }
52 
53 int main(){
54     struct Tree t;
55     char a[111];
56     init(&t);
57     for( int i = 0; ; i++ ){
58         gets(a);
59 
60         if( strcmp( a, "" ) == 0 ){
61             break;
62         }
63         add( &t, a );
64     }
65     for( ;; ){
66         if( gets(a) == 0 ){
67             break;
68         }
69         printf( "%d\n", find( &t, a ) );
70     }
71 
72 }

 

转载于:https://www.cnblogs.com/hacker-hzh/archive/2013/05/29/3107082.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值