HDU 1247 Hat’s Words
题意:输入一些字符串,遍历这些字符串,如果它是由这些字符串中另外两个字符串组合而成,输出这个串。
做法:将所有字符串插入Trie树中,然后分割字符串,遍历所有可能性。
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247
题目:
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8598 Accepted Submission(s): 3098
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<algorithm> 2 #include<iostream> 3 #include<cstdio> 4 #include<cmath> 5 #include<cstring> 6 using namespace std; 7 struct node 8 { 9 bool k; //标记 10 node *next[26]; //26个方向表示26个字母 11 node() //构造函数实现结构体初始化 12 { 13 int i; 14 for(i=0; i<26; i++) //将26个方向初始化为NULL 15 next[i] = NULL; 16 k = false; //终止标记标记为未出现字符串终止 17 } 18 }; 19 node *head; //头指针 20 void insert_ch(char *ch) //插入函数,将字符串插入字典树 21 { 22 int i; 23 node *p=head,*t; 24 for(i=0; i<ch[i]; i++) 25 { 26 if(p->next[ch[i]-'a']==NULL) //发现未拓展的方向 27 { 28 t=new node; //new函数产生新的节点 29 p->next[ch[i]-'a']=t; 30 } 31 p = p->next[ch[i]-'a']; //用p迭代向下取节点 32 } 33 p -> k = true; //标记此处有一个字符串终止 34 } 35 bool find_ch(char *ch) //查找函数 36 { 37 int i; 38 node *p=head; 39 for(i=0; i<ch[i]; i++) 40 { 41 if(p->next[ch[i]-'a']==NULL) 42 return false; 43 p = p -> next[ch[i]-'a']; 44 } 45 return p -> k; //返回终止处是否有终止标记 46 } 47 char s[50001][101]; 48 char a[105],b[105],x; 49 int main() 50 { 51 int i,n=0,j; 52 head = new node; 53 while(~scanf("%s%*c",s[n])) 54 { 55 insert_ch(s[n]); //保存字符串并插入字典树 56 n++; 57 } 58 for(i=0; i<n; i++) 59 { 60 for(j=1; j<strlen(s[i]); j++) //遍历所有拆分的组合 61 { 62 x=s[i][j]; 63 s[i][j]='\0'; 64 strcpy(a,s[i]); 65 s[i][j]=x; 66 strcpy(b,s[i]+j); 67 if(find_ch(a) && find_ch(b)) 68 { 69 printf("%s\n ",s[i]); 70 break; //遍历到出现字符串,退出防止出现重复 71 } 72 } 73 } 74 return 0; 75 }
小结:这是一道字典树水题,由于没有注意到重复问题,WA了一次。代码写的不是很好看,如有错误请各位大牛指点出来,谢谢~