Time limit 1000 ms
Memory limit 32768 kB
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
WA了好几发,带着疑问查看了别人的题解,发现是自己题目意思理解错了。其实就是字典树的变形!!!
解题思路来自:https://blog.csdn.net/u012860063/article/details/39022747
#include<bits/stdc++.h>
using namespace std;
const int maxn=26;
char str[50017][117];
char x[117],y[117];
struct trie
{
trie *next[maxn];
int v;
}*a;
void init()
{
a=new trie;
for(int i=0;i<maxn;i++)
a->next[i]=NULL;
}
void trie_insert(char *s)
{
int n=strlen(s);
trie *p=a,*q;
for(int i=0;i<n;i++)
{
int id=s[i]-'a';
if(p->next[id]==NULL)
{
p->next[id]=new trie;
p=p->next[id];
p->v=1;
for(int j=0;j<maxn;j++)
p->next[j]=NULL;
}
else p=p->next[id];
}
p->v=-1;//单词结尾
}
int Findtrie(char *s)
{
int n=strlen(s);
trie *p=a;
for(int i=0;i<n;i++)
{
int id=s[i]-'a';
if(p->next[id]==NULL) return 0;
p=p->next[id];
}
if(p->v==-1) return -1;
else return 0;
}
int deletetrie(trie *T)
{
if(!T) return 0;
for(int i=0;i<maxn;i++)
if(T->next[i]) deletetrie(T->next[i]);
delete T;
return 0;
}
int main()
{
init();
int cnt=0;
while(scanf("%s",str[cnt])==1)
{
trie_insert(str[cnt]);
cnt++;
}
for(int i=0;i<cnt;i++)
{
int n=strlen(str[i]);
for(int j=1;j<n;j++)
{
strncpy(x,str[i],j);
x[j]='\0';
strncpy(y,str[i]+j,n-j);
y[n-j]='\0';
if(Findtrie(x)==-1&&Findtrie(y)==-1)
{
printf("%s\n",str[i]);
break;
}
}
}
}