Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 9872 Accepted Submission(s): 3536
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
戴帽子的
题意:
给一堆单词,找出其中有多少个由另外两个单词组成的单词。
分析:
Trie的应用,先将所有的单词保存到树中,再将每个单词分为两段,如果这两段都在树中,那么这个单词满足条件。
代码:
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
char str[50000][50];
struct Trie //字典树
{
int IsWord; //判断该节点是否为单词
Trie* next[26];
Trie() { //构造函数,每创建一棵字典树时自动调用
IsWord = 0;
for(int i = 0; i < 26; i++) next[i] = NULL;
}
} *Root;
void Insert(char ch[]) //插入一个单词
{
Trie* p = Root;
for(int i = 0; ch[i]; i++) {
int k = ch[i] - 'a';
if(p->next[k] == NULL) {
Trie* temp = new Trie;
p->next[k] = temp;
}
p = p->next[k];
}
p->IsWord = 1;
}
bool Search(char ch[]) //查找单词是否在树中
{
Trie* p = Root;
for(int i = 0; ch[i]; i++) {
int k = ch[i] - 'a';
if(p == NULL || p->next[k] == NULL) return false;
p = p->next[k];
}
return p->IsWord;
}
void Delete(Trie* root) //递归释放内存空间
{
for(int i = 0; i < 26; i++) {
if(root->next[i] != NULL)
Delete(root->next[i]);
}
delete root;
}
int main()
{
Root = new Trie;
int s = 0;
while(~scanf("%s", str[s])) {
Insert(str[s]);
s++;
}
for(int i = 0; i < s; i++) {
int len = strlen(str[i]);
for(int j = 1; j < len; j++) {
char t1[50] = "\0", t2[50] = "\0";
strncpy(t1, str[i], j); //将单词截断为两部分
strncpy(t2, str[i] + j, len - j);
if(Search(t1) && Search(t2)) {
printf("%s\n", str[i]);
break;
}
}
}
Delete(Root);
return 0;
}