字典树裸题

 1 #include<stdio.h>
 2 #include<string.h>
 3 int next[5000][26];
 4 bool is_e[5000];
 5 int cnt;
 6 int ans;
 7 
 8 void Insert(char *word,int s1){
 9     int root=0;
10     for(int i=0;i<s1;i++){
11         if(next[root][word[i]-'a']<0){
12             next[root][word[i]-'a']=++cnt;
13             memset(next[cnt],-1,sizeof(next[cnt]));
14         }
15         root=next[root][word[i]-'a'];
16     }
17     if(is_e[root]!=true&&root!=0){
18         ans++;
19         is_e[root]=true;
20     }
21 }
22 
23 int main(){
24     char word[500];
25     while(1){
26 
27         int s1=0;
28         ans=0;
29         cnt=0;
30         memset(is_e,false,sizeof(is_e));
31         memset(next[0],-1,sizeof(next[0]));
32         gets(word);
33         if(word[0]=='#')return 0;
34         int l=strlen(word);
35         char *p=word;
36         for(int i=0;i<l;i++){
37             if(word[i]!=' '){
38                 s1++;
39             }
40             else{
41                 Insert(p,s1);
42                 s1=0;
43                 p=(word+i+1);
44             }
45         }
46         Insert(p,s1);
47         printf("%d\n",ans);
48     }
49 }
View Code