hdu1075What Are You Talking About(trie树)

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

难得的1A 把对应的英语单词存在 火星文字最后一个字母的结构体字符串中 挨个找

View Code
  1 #include <iostream>

  2 #include<cstdio>

  3 #include<string.h>

  4 #include<stdlib.h>

  5 using namespace std;

  6 int flag;

  7 struct node

  8 {

  9     int flag;

 10     char s[21];

 11     node *next[27];

 12     node()

 13     {

 14         flag = 0;

 15         memset(next,NULL,sizeof(next));

 16     }

 17 };

 18 void trie(node *head,char *c1,char *c2)

 19 {

 20     int k1 = strlen(c2),i,d;

 21     node *p = head;

 22     for(i =0 ; i < k1 ; i++)

 23     {

 24         d = c2[i]-'a';

 25         if(p->next[d]==NULL)

 26         {

 27             p->next[d] = new node;

 28         }

 29         p = p->next[d];

 30     }

 31 

 32     p->flag = 1;

 33     strcpy(p->s,c1);

 34 }

 35 void search(node *head,char *c)

 36 {

 37     int i,j,k = strlen(c),d;

 38     node *p = head;

 39     for(i = 0 ; i < k ; i++)

 40     {

 41         d = c[i]-'a';

 42         if(p->next[d]==NULL)

 43         {

 44             flag = 0;

 45             return;

 46         }

 47         p=p->next[d];

 48     }

 49     if(p->flag == 1)

 50     {

 51         flag = 1;

 52         printf("%s",p->s);

 53     }

 54 }

 55 int main()

 56 {

 57     int i,j,k,n,g,w;

 58     char c1[20],c2[20],str[3001],s[21];

 59     node *head = new node;

 60     scanf("%s",c1);

 61     while(scanf("%*c%s",c1)!=EOF)

 62     {

 63         if(strcmp(c1,"END")==0)

 64         break;

 65         scanf("%s",c2);

 66         trie(head,c1,c2);

 67     }

 68     scanf("%s",c1);

 69     getchar();

 70     while(gets(str)!=NULL)

 71     {

 72         if(strcmp(str,"END")==0)

 73         break;

 74         k = strlen(str);

 75         int f = 0;

 76         g= 0;

 77         for(i =0 ; i < k ; i++)

 78         {

 79             if(str[i]>='a'&&str[i]<='z')

 80             {

 81                 s[g++] = str[i];

 82                 f = 1;

 83             }

 84             else

 85             {

 86                 if(f)

 87                 {

 88                     f = 0;

 89                     flag = 0;

 90                     s[g]='\0';

 91                     g = 0;

 92                     search(head,s);

 93                     if(!flag)

 94                     printf("%s",s);

 95                     printf("%c",str[i]);

 96                 }

 97                 else

 98                 printf("%c",str[i]);

 99             }

100         }

101         if(str[k-1]>='a'&&str[k-1]<='z')

102         {

103             s[g] = '\0';

104             flag = 0;

105             search(head,s);

106             if(!flag)

107             printf("%s",s);

108         }

109         puts("");

110     }

111     return 0;

112 }

 

你可能感兴趣的:(trie)