首页 > 代码库 > HDU 1247 Hat’s Words (字典树 && map)
HDU 1247 Hat’s Words (字典树 && map)
分析:一開始是用递归做的,没做出来。于是就换了如今的数组。即,把每个输入的字符串都存入二维数组中,然后创建字典树。输入和创建完成后,開始查找。
事实上一開始就读错题目了,题目要求字符串是由其它两个输入的字符串组成的前后缀,自己根本没有推断前缀是否满足。就直接推断后缀,一直想不通自己哪里错了,非常羞愧,水平还是不行。
查找分为前缀查找和后缀查找。事实上两个函数基本差点儿相同的。以下放代码。
#include <cstdio> #include <cstring> #include <iostream> using namespace std; struct trie { trie *next[26]; int v; //字符同样的个数 trie() { memset(next,NULL,sizeof(next)); v=1; } }; trie *root=new trie(); char s[50001][101]; void creat_trie(char *str) { int i,id; trie *p; for(p = root,i=0;str[i]; ++i) { id = str[i]-'a'; if(p->next[id] == NULL) { p->next[id] = new trie(); } p = p->next[id]; } p->v = -1; } int find_trie(char *str) { int i=0,j,id; trie *p = root; for(;*str != '\0';) { id= *str - 'a' ; if (p->next[id] != NULL) { p = p->next[id]; if(p->v == -1 && *(str+1) == '\0') return 1; str++; } else return 0; } return 0; } int find(char *str) { trie *p = root; int m; for (;*str != '\0';) { m = *str - 'a'; p = p->next[m]; if(p != NULL) { if (p->v == -1 && find_trie(str+1)) { return 1; } str++; } else return 0; } return 0; } int main() { int N,n,i=0,j,t,m,flag=0; int a,b,c,d,k; int sum; trie *p; while (gets(s[i]),s[i][0] != '\0')//,s[i][0] != '\0' { creat_trie(s[i++]); } for (j=0;j<i;j++) { if (find(s[j])) { puts(s[j]); } } return 0; }
代码2:map容器
#include <iostream> #include <map> #include <cstring> using namespace std; map <string,int> m; string s[50005]; int main() { int k=-1; while(cin>>s[++k]) { m[s[k]] = 1; } for(int i=0;i<=k;i++) { int len = s[i].length(); for(int j=1;j<len;j++) { string s1(s[i],0,j); //从0開始的j个数 string s2(s[i],j); //从j開始(不包含)一直到结尾 if(m[s1] == 1 && m[s2] == 1) { cout<<s[i]<<endl; break; } } } return 0; }
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9436 Accepted Submission(s): 3369
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
Author
戴帽子的
HDU 1247 Hat’s Words (字典树 && map)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。