Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
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<cstring>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<string>
using namespace std;
const int maxx=50050;
int ch[maxx][26];
int value[maxx];
int sz=0;
string ss[maxx];
void init()
{
sz=1;
memset(ch[0],0,sizeof(ch[0]));
}
void insertstr(string str)
{
int u=0,n=str.length();
for(int i=0; i<n; i++)
{
int d=str[i]-'a';
if(!ch[u][d])
{
memset(ch[sz],0,sizeof(ch[sz]));
value[sz]=0;
ch[u][d]=sz++;
}
u=ch[u][d];
}
value[u]=-1;
}
bool query(string str)
{
int u=0,n=str.length();
if(n==0)return false;
for(int i=0; i<n; i++)
{
int d=str[i]-'a';
if(ch[u][d])u=ch[u][d];
else return false;
}
if(value[u]==-1)
return true;
else return false;
}
bool findstr(string str)
{
int u=0,n=str.length();
bool flag=false;
for(int i=0; i<n; i++)
{
int d=str[i]-'a';
if(ch[u][d])
{
u=ch[u][d];
if(value[u]==-1)
{
string s=str.substr(i+1);
if(query(s))
{
flag=true;
break;
}
}
}
else return false;
}
if(flag)return true;
else return false;
}
int main()
{
int a=0;
init();
while(cin>>ss[a])
{
insertstr(ss[a]);
a++;
}
for(int i=0; i<a; i++)
{
if(findstr(ss[i]))cout<<ss[i]<<endl;
}
return 0;
}