开始的时候没有用字典树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 }