Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11664 Accepted Submission(s): 4160
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
题解:首先把所有字符串存进Trie里,然后暴力每个字符串.....
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std;
struct Trie
{
Trie *ch[30];
int val;
};
Trie *root;
char s[50005][30],c1[30],c2[30];
void buildtrie(char *s)
{
int l=strlen(s),k;
Trie *p=root,*q;
for (int i=0;i<l;i++)
{
k=s[i]-97;
if (p->ch[k]==NULL)
{
q=(Trie*)malloc(sizeof(Trie));
for (int j=0;j<26;j++) q->ch[j]=NULL;
q->val=0;
p->ch[k]=q;
p=p->ch[k];
}
else p=p->ch[k];
}
p->val=1;
}
int intrie(char *s)
{
int l=strlen(s),k;
Trie *p=root;
for (int i=0;i<l;i++)
{
k=s[i]-97;
if (p->ch[k]!=NULL) p=p->ch[k];
else return 0;
}
if (p->val==1) return 1;
}
void solve(int j,int k,int l)
{
int i=0;
memset(c1,0,sizeof(c1));
memset(c2,0,sizeof(c2));
for (i=0;i<=k;i++) c1[i]=s[j][i];
i=0;
for (int z=k+1;z<l;i++,z++) c2[i]=s[j][z];
}
int main()
{
int i=0; root=(Trie*)malloc(sizeof(Trie));
for (i=0;i<26;i++) root->ch[i]=NULL;
root->val=0;
i=0;
while (scanf("%s",s[i])!=EOF)
{
buildtrie(s[i]);
i++;
}
for (int j=0;j<i;j++)
{
int l=strlen(s[j]),f=0;
while (f<l-1)
{
solve(j,f,strlen(s[j]));
if (intrie(c1) && intrie(c2))
{
printf("%s\n",s[j]);
break;
}
f++;
}
}
return 0;
}