题目链接: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): 10982 Accepted Submission(s): 3937
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 <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <algorithm> 5 #include <iostream> 6 #include <cmath> 7 #include <queue> 8 #include <map> 9 #include <stack> 10 #include <list> 11 #include <vector> 12 13 using namespace std; 14 15 char str[66666][81]; 16 17 typedef struct Node { 18 Node *next[26]; 19 int cnt; 20 Node() { 21 cnt = 0; 22 for(int i = 0; i < 26; i++) { 23 next[i] = NULL; 24 } 25 } 26 }Node; 27 28 void insert(Node *p, char *str) { 29 for(int i = 0; str[i]; i++) { 30 int t = str[i] - 'a'; 31 if(p->next[t] == NULL) { 32 p->next[t] = new Node(); 33 } 34 p = p->next[t]; 35 } 36 p->cnt++; //is a word 37 } 38 39 int find(Node *p, char *str) { 40 for(int i = 0; str[i]; i++) { 41 int t = str[i] - 'a'; 42 p = p->next[t]; 43 if(!p) { 44 return 0; 45 } 46 } 47 if(p->cnt >= 1) { 48 return 1; 49 } 50 return 0; 51 // return p->cnt; 52 } 53 54 int main() { 55 int n = 0; 56 Node *root = new Node(); 57 // freopen("in", "r", stdin); 58 while(gets(str[n]) && strlen(str[n])) { 59 insert(root, str[n]); 60 n++; 61 } 62 char a[81]; 63 char b[81]; 64 for(int i = 0; i < n; i++) { 65 int len = strlen(str[i]); 66 for(int j = 1; j < len; j++) { 67 memset(a, 0, sizeof(a)); 68 memset(b, 0, sizeof(b)); 69 strncpy(a, str[i], j); 70 strncpy(b, str[i] + j, len - j); 71 if(find(root, a) && find(root, b)) { 72 printf("%s ", str[i]); 73 break; 74 } 75 } 76 } 77 return 0; 78 }