Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8343 Accepted Submission(s): 3004
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
Author 戴帽子的 简述题意: 给你很多单词,查找能够由其中的两个单词拼合而成的单词,并按字典序输出..... 代码:
1 #include<cstdio>
2 #include<cstring>
3 #include<cstdlib>
4 typedef struct node
5 {
6 struct node *child[26];
7 bool tail;
8 }Trie;
9 char mat[50005][15];
10 void Insert(char *s,Trie *root)
11 {
12 int i,pos,j;
13 Trie *cur=root,*curnew;
14 for(i=0;s[i]!='\0';i++){
15 pos=s[i]-'a';
16 if(cur->child[pos]==NULL)
17 {
18 curnew=(Trie *)malloc(sizeof(Trie));
19 for(j=0;j<26;j++)
20 curnew->child[j]=NULL;
21 curnew->tail=false;
22 cur->child[pos]=curnew;
23 }
24 cur=cur->child[pos];
25 }
26 cur->tail=true;
27 }
28 bool check(char *s,Trie *root)
29 {
30 int i,pos;
31 Trie *cur=root;
32 for(i=0;s[i]!='\0';i++)
33 {
34 pos=s[i]-'a';
35 if(cur->child[pos]==NULL) return 0;
36 cur=cur->child[pos];
37 }
38 if(cur->tail==1)return 1;
39 return 0;
40 }
41 bool query(char *s,Trie *root)
42 {
43 int i,pos;
44 Trie *cur=root;
45 for(i=0;s[i]!='\0';i++)
46 {
47 pos=s[i]-'a';
48 if(cur->child[pos]==NULL) return 0;
49 else
50 if(cur->tail==1&&check(s+i,root))
51 return 1;
52 cur=cur->child[pos];
53 }
54 return 0;
55 }
56 int main()
57 {
58 int i=0,j;
59 #ifdef LOCAL
60 freopen("test.in","r",stdin);
61 #endif
62 Trie *root=(Trie *)malloc(sizeof(Trie));
63 root->tail=0;
64 for(j=0;j<26;j++)
65 root->child[j]=NULL;
66 while(scanf("%s",mat[i])!=EOF){
67 Insert(mat[i],root);
68 i++;
69 }
70 for(j=0;j<i;j++)
71 {
72 if(query(mat[j],root))
73 printf("%s\n",mat[j]);
74 }
75 return 0;
76 }
View Code
编程是一种快乐,享受代码带给我的乐趣!!!