Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11292 Accepted Submission(s): 4033
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//看大神的代码,看了半天才看懂。。。//题意:找出所给字符串集中由两个字符串组成的字符串。//这个是用来验证的,为了能看到输出结果的,不过得先输入个整数T,#include<stdio.h> #include<string.h> #include<algorithm> #define N 50010 using namespace std; char s[N][110]; int ch[N][110]; int word[N]; int val[N];//标记是否为单词节点 int sz; int init() { sz=1; memset(ch[0],0,sizeof(ch[0])); memset(word,0,sizeof(word)); } void insert(char s[]) { int i,j,l=strlen(s); int k=0; for(i=0;i<l;i++) { j=s[i]-'a'; if(!ch[k][j]) { memset(ch[sz],0,sizeof(ch[sz])); val[sz]=0;//不是单词节点 ch[k][j]=sz++; } k=ch[k][j]; word[k]++; } val[k]=1; } bool find(char s[]))//判断该字符串 是不是 字符串集里面的一个字符串 { int i,j,l=strlen(s); int k=0; for(i=0;i<l;i++) { j=s[i]-'a'; if(!ch[k][j]) return false; k=ch[k][j]; } return val[k];//最后一个是不是单词节点 } int judge(char s[])//判断该字符串 能否由另外两个字符串构成 { int i,j,l=strlen(s); if(l==1) return 0; char ll[N],rr[N]; char lr[N]; strcpy(lr,s); strrev(lr);//将字符串颠倒(strrev函数) int k=0; for(i=0;i<l;i++) { if(i==l-1) break; ll[k++]=s[i]; ll[k]='\0'; lr[l-k]='\0'; if(find(ll))//前面一部分可以找到 { strcpy(rr,lr); strrev(rr); if(find(rr))//后面一部分可以找到 return 1; } } return 0; } int main() { init(); int n=0; while(scanf("%s",s[n])!=EOF) { insert(s[n]); n++; } for(int i=0;i<n;i++) { if(judge(s[i])) printf("%s\n",s[i]); } return 0; }
#include<stdio.h> #include<string.h> #include<algorithm> #define N 50010 using namespace std; char s[N][110]; int ch[N][110]; int val[N]; int sz; int init() { sz=1; memset(ch[0],0,sizeof(ch[0])); } void insert(char s[]) { int i,j,l=strlen(s); int k=0; for(i=0;i<l;i++) { j=s[i]-'a'; if(!ch[k][j]) { memset(ch[sz],0,sizeof(ch[sz])); val[sz]=0; ch[k][j]=sz++; } k=ch[k][j]; } val[k]=1; } bool find(char s[]) { int i,j,l=strlen(s); int k=0; for(i=0;i<l;i++) { j=s[i]-'a'; if(!ch[k][j]) return false; k=ch[k][j]; } return val[k]; } int judge(char s[]) { int i,j,l=strlen(s); if(l==1) return 0; char ll[N],rr[N]; char lr[N]; strcpy(lr,s); strrev(lr); int k=0; for(i=0;i<l;i++) { if(i==l-1) break; ll[k++]=s[i]; ll[k]='\0'; lr[l-k]='\0'; if(find(ll)) { strcpy(rr,lr); strrev(rr); if(find(rr)) return 1; } } return 0; } int main() { int t,i; while(scanf("%d",&t)!=EOF) { for(i=0;i<t;i++) { getchar(); scanf("%s",s[i]); insert(s[i]); } for(i=0;i<t;i++) { if(judge(s[i])) printf("%s\n",s[i]); } } return 0; }