首页 > 代码库 > HDU 1247 简单字典树

HDU 1247 简单字典树

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7359    Accepted Submission(s): 2661


Problem Description
A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary.
You are to find all the hat’s words in a dictionary.
 

 

Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words.
Only one case.
 
Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
 
Sample Input
a
ahat
hat
hatword
hziee
word
 
Sample Output
ahat
hatword
 
 
题目意思是给多个单词,如果单词满足前缀和后缀都是其他单词,那么输出该单词。
赤裸裸的字典树。
把每一个单词存入字典树中,然后枚举所有单词,对每个单词分成两份,查找这两份,如果查找成功,输出该单词,否则分成其他的两份,进行上述操作,直到无法分成两份为止。依次枚举所有单词。
 
代码不解释:
 1 #include <stdio.h> 2 #include <string.h> 3 #include <algorithm> 4 using namespace std; 5  6 char a[50005][15]; 7  8 struct node{ 9     int flag;10     struct node *next[26];11     node(){12         flag=0;13         memset(next,0,sizeof(next));14     }15 }root;16 17 void insert(char *s)18 {19     struct node *p=&root;20     int k=0;21     while(s[k])22     {23         if(!p->next[s[k]-a]){24             p->next[s[k]-a]=new node;25             p=p->next[s[k]-a];26         }27         else p=p->next[s[k]-a];28         k++;29     }30     p->flag=1;31 }32 33 34 int find(char *s)35 {36     struct node *p=&root;37     int k=0;38     while(s[k]&&p->next[s[k]-a])39     {40          p=p->next[s[k]-a];41          k++;42     }43     if(!s[k]&&p->flag) return 1;44     return 0; 45 }46 47 main()48 {49     char b[15], c[15];50     int i, j, k=0;51     while(scanf("%s",a[k])!=EOF)52     {53         insert(a[k]);54         k++;55     }56     for(i=0;i<k;i++)57     {58         for(j=1;j<strlen(a[i]);j++)59         {60             strcpy(b,a[i]);61             b[j]=\0;62             strcpy(c,a[i]+j);63             if(find(b)&&find(c))64             {65                 printf("%s\n",a[i]);66                 break;67             }68         }69     }70 }