题目:http://acm.hdu.edu.cn/showproblem.php?pid=1251
1 #include<stdio.h> 2 #include<math.h> 3 #include<string.h> 4 #include<stdlib.h> 5 #include<iostream> 6 using namespace std; 7 8 struct tree{//建立字典树 9 int n; 10 tree *next[26];//一个节点拥有26个指针分支节点,有字母时才分配空间 11 }; 12 tree *root;//建根 13 14 void insert(char *p) 15 { 16 tree *now,*cur; 17 cur=root; 18 int len=strlen(p); 19 for(int i=0;i<len;i++) 20 { 21 if(cur->next[p[i]-'a']==0)//判断该节点的p[i]分支是否开辟空间 22 { 23 now=(struct tree*)malloc(sizeof(struct tree)); 24 now->n=1; 25 for(int j=0;j<26;j++) 26 { 27 now->next[j]=0; 28 } 29 cur->next[p[i]-'a']=now;//指向空间 30 cur=cur->next[p[i]-'a'];//指针下移 31 } 32 else 33 { 34 cur=cur->next[p[i]-'a'];//已有前缀,指针下移 35 cur->n++; 36 } 37 } 38 } 39 40 int find(char *p) 41 { 42 tree *cur; 43 cur=root; 44 int len=strlen(p); 45 for(int i=0;i<len;i++) 46 { 47 if(cur->next[p[i]-'a']==0) 48 { 49 return 0; 50 } 51 else 52 cur=cur->next[p[i]-'a'];//存在前缀,指针下移 53 } 54 return cur->n; 55 } 56 57 int main() 58 { 59 //freopen("in.txt","r",stdin); 60 char p[15]; 61 root = (struct tree*)malloc(sizeof(struct tree));//开辟空间 62 for(int i=0;i<26;i++) 63 { 64 root->next[i]=0;//初始化0 65 } 66 root->n=0; 67 68 while(gets(p)) 69 { 70 if(strlen(p)==0) 71 break; 72 insert(p); 73 } 74 while(~scanf("%s",p)) 75 { 76 int n=find(p); 77 printf("%d ",n); 78 } 79 return 0; 80 }