Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Hat’s Words
Total Submission(s): 11687 Accepted Submission(s): 4165
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#include <iostream> #include <cstdio> #include <cstring> using namespace std; const int maxnode = 5000000; const int sigma_size = 26; char str1[100],str2[100]; char s[50005][100]; struct Trie { int ch[maxnode][sigma_size]; int val[maxnode]; int sz; Trie() { sz = 1; memset(ch[0],0,sizeof(ch[0])); } int idx(char c) { return c - 'a'; } void Insert(char ss[100]) { int u = 0 ,n = strlen(ss); for(int i = 0 ; i < n ; i++) { int c = idx(ss[i]); if(!ch[u][c]) { memset(ch[sz],0,sizeof(ch[sz])); val[sz] = 0; ch[u][c] = sz++; } u = ch[u][c]; } val[u] = 1; } int Inquire(char sa[100]) { int u = 0; for(int i = 0;i < strlen(sa);i++) { int c = idx(sa[i]); if(ch[u][c]) u = ch[u][c]; else return 0; } if(val[u]) return 1; else return 0; } void tackle(char s[50005][100],int n) { int i,j; for(i = 0 ;i < n ; i++) { int m = strlen(s[i]); if(m != 1) for(j = 1; j < strlen(s[i]); j++) { memset(str1,'\0',sizeof(str1)); memset(str2,'\0',sizeof(str2)); strncpy(str1,s[i],j); //对每个字符串进行分解,然后判断这个字符串是否在字典树中 strcpy(str2,s[i]+j); if(Inquire(str1) && Inquire(str2)){ printf("%s\n",s[i]); break; } } } } }; Trie tree; int main() { int i = 0; while(scanf("%s",s[i])!=EOF) { tree.Insert(s[i]); i++; } tree.tackle(s,i); return 0; }