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.
题意很好理解,就是说给一组字符串,问哪些字符串是由其他正好两个字符串组成的,输出这些字符串。
就是trie树嘛,先把所有字符串存进去,标记结束点,然后每个字符串扫一遍。
唔,对了,一定要记住int型函数在没有规定返回值的时候返回的值会很奇怪(至少肯定不是零,排查了有半天)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
const int N=100010;
char s[50005][30];
struct node
{
node* next[26];
int cnt;
node()
{
memset(next,NULL,sizeof(next));
cnt=0;
}
};
node *root=new node();
void build(char str[])
{
node *p=root;
int len=strlen(str);
for(int i=0;i<len;i++)
{
int index=str[i]-'a';
if(p->next[index]==NULL)
{
p->next[index]=new node();
}
p=p->next[index];
}
p->cnt=1;
}
int search(char str[],bool flag)
{
node* p=root;
int len=strlen(str);
//printf(":%s:\n",str);
if(len==0) return 0;
for(int i=0;i<len;i++)
{
int index=str[i]-'a';
if(p->next[index]==NULL) return 0;
p=p->next[index];
if(p->cnt)
{
/*printf("fuk");
for(int j=0;j<=i;j++)
printf("%c",str[i]);
printf("fuk");
printf("\n");*/
if(flag==0)
{
if(search(&str[i+1],1)) return 1;
}
else
if(i==len-1) return 1;
}
}
return 0;
}
int main()
{
int m,n=0;
while(scanf("%s",s[n])!=EOF)
{
build(s[n]);
++n;
}
for(int i=0;i<n;i++)
{
if(search(s[i],0))
puts(s[i]);
}
return 0;
}