Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11841 Accepted Submission(s): 4216
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
Author
戴帽子的
思路:简单题目,字典树的模板题目,先将所有的串都保存到树上,并且对单词进行标记,然后对每个单词进行查找,先查找前半部分,一旦找到了,就找下半部分,注意,下半部分要找到结束。
AC代码如下:
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
const int seg_size=26;
char str[50000+5][20];
struct tries{
tries *next[seg_size];
bool sign;
tries(){
memset(next,NULL,sizeof(next));
sign=false;
}
}* root;
tries * create(){
tries *tmp=new tries();
return tmp;
}
void Insert(char *p,tries * root){
while(*p){
int id=*p-'a';
if(root->next[id]==NULL){
root->next[id]=create();
}
root=root->next[id];
p++;
}
root->sign=true;
}
bool searchTwo(char *p){
tries *tmp=root;
while(*p){
int id=*p-'a';
if(tmp->next[id]!=NULL){
p++;
tmp=tmp->next[id];
}
else return false;
}
if(tmp->sign) return true;
return false;
}
bool searchOne(char *p){
tries *tmp=root;
while(*p){
int id=*p-'a';
if(tmp->next[id]!=NULL){
if(tmp->sign){
if(searchTwo(p))return true;
}
p++;tmp=tmp->next[id];
}
else return false;
}
return false;
}
int main(){
int cnt;
root=new tries();
while(scanf("%s",str[cnt])!=EOF){
Insert(str[cnt],root);
cnt++;
}
for(int i=0;i<cnt;i++){
if(searchOne(str[i]))
puts(str[i]);
}
return 0;
}