hdu 1075 What Are You Talking About(Trie树)

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1075

View Code
  1 #include<iostream>
  2 #include<cstring>
  3 #include<cstdio>
  4 #include<stdlib.h>
  5 using namespace std;
  6 struct node
  7 {
  8     int flag;
  9     char st[101];
 10     node *next[26];
 11 };
 12 node *build()
 13 {
 14     int i;
 15     node *p;
 16     p=new node;
 17     p->flag=0;
 18     for(i=0;i<26;i++)
 19     p->next[i]=NULL;
 20     return p;
 21 }
 22 void insert(node *p,char *s1,char *s2)
 23 {
 24     int i,len1,t;
 25     len1=strlen(s1);
 26     for(i=0;i<len1;i++)
 27     {
 28         t=s1[i]-'a';
 29         if(p->next[t]==NULL)
 30         p->next[t]=build();
 31         p=p->next[t];
 32     }
 33     p->flag=1;
 34     strcpy(p->st,s2);
 35 }
 36 int search(node *p,char *s)
 37 {
 38     int t,i,len;
 39     len=strlen(s);
 40     for(i=0;i<len;i++)
 41     {
 42         t=s[i]-'a';
 43         if(p->next[t]==NULL)
 44         return 0;
 45         p=p->next[t];
 46     }
 47     if(p->flag==1)
 48     {
 49         printf("%s",p->st);
 50         return 1;
 51     }
 52     return 0;
 53 }
 54 int main()
 55 {
 56     int i,j,len,len2,k;
 57     char str1[10001],str2[10005];
 58     node *p;
 59     gets(str1);
 60     if(strcmp(str1,"START")==0)
 61     {
 62         p=build();
 63         while(~scanf("%s%*c",str1))
 64         {
 65             if(strcmp(str1,"END")==0)
 66             break;
 67             scanf("%s",str2);
 68             insert(p,str2,str1);
 69         }
 70     }
 71     gets(str1);
 72     if(strcmp(str1,"START")==0)
 73     {
 74         while(gets(str1)!=NULL)
 75         {
 76             if(strcmp(str1,"END")==0)
 77             break;
 78             len=strlen(str1);
 79             j=0;
 80             for(i=0;i<len;i++)
 81             {
 82                 if(str1[i]>='a'&&str1[i]<='z')
 83                 {
 84                     str2[j]=str1[i];
 85                     j++;
 86                 }
 87                 else
 88                 {
 89                     if(j!=0)
 90                     {
 91                         str2[j]='\0';
 92                         j=0;
 93                         if(search(p,str2)==0)
 94                         printf("%s",str2);
 95                         printf("%c",str1[i]);
 96                     }
 97                     else
 98                     printf("%c",str1[i]);
 99                 }
100             }
101             if(j!=0)
102             {
103                 str2[j]='\0';
104                 if(search(p,str2)==0)
105                 printf("%s",str2);
106             }
107             puts("");
108         }
109     }
110     return 0;
111 }
原文地址:https://www.cnblogs.com/wanglin2011/p/2636969.html