Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 7 Accepted Submission(s) : 4
Font: Times New Roman | Verdana | Georgia
Font Size: ←→
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.
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
Author
戴帽子的
判断一个单词是否可由其他两个单词组成,要注意的是其他的单词也有可能由几个单词组成!
用字典树查询一个单词,每当碰到这个单词出现过时,就搜索单词余下的部分
这个步骤我是用递归来做的,用一个count变量控制递归的层数,但是代码很乱,没太多参考价值
#include <stdio.h>
#include <string.h>
int cnt;
int ant;
char text[50005][105];
struct Node{
int next[26];
int flag;
} tree[100000];
void Insert(char *s){
int p = 0;
while(*s){
if(tree[p].next[*s - 'a'] == -1){
tree[p].next[*s - 'a'] = cnt;
cnt++;
}
p = tree[p].next[*s - 'a'];
s++;
}
tree[p].flag = 1;
}
//用count做标志记录递归到第几层
int Query(char *s,int count){
int p = 0;
while(*s){
if(tree[p].next[*s - 'a'] == -1){
return 0;
}
p = tree[p].next[*s - 'a'];
//当遇到字典中的单词
if(tree[p].flag == 1 && *(s+1)){
//当碰到第一个单词
if(count == 1){
count++;
Query(s+1,count);//搜索余下的单词
count = 1;//注意把count还原成1,继续在第一层递归中检索
}
//在搜索余下的单词时,也有可能余下单词由两个以上单词组成
//所以需要单独判断
else if(count == 2){
s++;
continue;
}
}
s++;
}
if(tree[p].flag == 1){
//比较乱的一个地方。。。不用纠结
if(ant == 2){
return 0;
}
ant++;
}
return 0;
}
int main (){
int i,j;
int len;
cnt = 1;
for(i = 0;i < 100000;i++){
memset(tree[i].next,-1,sizeof(tree[i].next));
tree[i].flag = 0;
}
i = 0;
while(scanf("%s",text[i]) != EOF){
Insert(text[i]);
i++;
}
len = i;
for(j = 0;j < len;j++){
ant = 0;//作为判断单词是否满足条件的标志
Query(text[j],1);
if(ant == 2){
printf("%s\n",text[j]);
}
}
return 0;
}