hdu 1247 Hat’s Words(字典数)
http://acm.hdu.edu.cn/showproblem.php?pid=1247
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.
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.
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<iostream> 2 using namespace std; 3 struct Node 4 { 5 Node * next[26]; 6 int num; 7 Node() 8 { 9 num=0; 10 memset(next,NULL,sizeof(next)); 11 } 12 }; 13 char str[50000][50]; 14 void insert_tree(Node * head,char *tstr) 15 { 16 Node *h=head; 17 int len=strlen(tstr),i; 18 for(i=0;i<len;i++) 19 { 20 int id=tstr[i]-'a'; 21 if(h->next[id]==NULL) 22 h->next[id]=new Node; 23 h=h->next[id]; 24 } 25 h->num=1; 26 } 27 int find_tree(Node *head,char *tstr) 28 { 29 Node *h=head; 30 int len=strlen(tstr),i; 31 for(i=0;i<len;i++) 32 { 33 int id=tstr[i]-'a'; 34 if(h->next[id]==NULL) 35 return 0; 36 h=h->next[id]; 37 } 38 return h->num; 39 } 40 int main() 41 { 42 int k=0,i,j; 43 char str1[50],str2[50],tstr[50]; 44 Node *head=new Node; 45 while(gets(str[k])) 46 { 47 insert_tree(head,str[k]); 48 k++; 49 } 50 for(i=0;i<k;i++) 51 { 52 int len=strlen(str[i]); 53 strcpy(tstr,str[i]); 54 for(j=1;j<len;j++) 55 { 56 strcpy(str1,tstr); 57 str1[j]='\0'; 58 strcpy(str2,tstr+j); 59 if(find_tree(head,str1)&&find_tree(head,str2)) 60 break; 61 } 62 if(j<len) 63 puts(tstr); 64 } 65 return 0; 66 }