一、题目描述
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 21972 Accepted Submission(s): 7702
(2020/2/13 19:59)
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
戴帽子的
二、算法分析说明
全部单词都添加到字典树的同事把单词 copy 一份,然后对每个单词(设长为 l)拆成两个词并枚举,从两个单词的长度分别为 1,l - 1 到 l - 1,1,每次枚举都要在字典树中检索。如果都找到结果,就意味着这个单词可以拆成已有的两个单词。
注意:字典树的每个单词的末尾要添加结束标记,否则在部分题目中会出错:当查找的单词虽然不在字典树中存在,但是是某个已存在的单词的前缀时,如果不通过专门的标记来判定该前缀的末尾实际上并非一个单词的结束,那么就会返回查找的单词存在的错误结果。
三、AC 代码(46 ms)
#include<cstdio>
#include<map>
#include<algorithm>
#include<cstring>
#pragma warning(disable:4996)
class trie {
private:
struct node { std::map<char, node*> next; bool end = false; }; node* root;
std::map<char, node*>::iterator I; std::pair<char, node*> P;
public:
trie() { root = new node(); }
void insert(const char* const k) {
node* p = root; const char* q = k;
while (*q != 0) {
I = p->next.find(*q);
if (I == p->next.end()) {
P.first = *q; P.second = new(node)(); p->next.emplace(P); I = p->next.find(*q);
}
p = I->second, ++q;
}
p->end = true;
}
bool find(const char* const w) {
node* p = root; const char* q = w;
while (*q != 0) {
I = p->next.find(*q);
if (I == p->next.end()) { return false; }
p = I->second, ++q;
}
return p->end;
}
};
trie t; char w[50000][32], x[32], y[32]; unsigned n; unsigned long long l;
int main() {
while (scanf("%s", w[n]) != EOF) { t.insert(w[n]); ++n; }
for (unsigned i = 0; i < n; ++i) {
l = strlen(w[i]);
for (unsigned long long j = 1; j < l; ++j) {
std::fill(x, x + 32, 0); std::fill(y, y + 32, 0);
strncpy(x, w[i], j); strncpy(y, w[i] + j, l - j);
if (t.find(x) == true && t.find(y) == true) { puts(w[i]); break; }
}
}
return 0;
}