HDU 1247 Hat's Words(字典树 + 枚举,46 ms)

本文介绍了如何使用字典树和枚举方法寻找字典中由两个其他单词组成的hat's words。首先,按字母顺序读取不超过50,000个单词。然后,遍历每个单词,尝试拆分为两个子单词并在字典树中查找。正确实现字典树的结束标记以避免误判。最后,输出所有找到的hat's words。" 135302432,5564205,华为OD机试C卷:Java实现分数计算,"['华为od', 'java', '算法', '开发语言']
摘要由CSDN通过智能技术生成

一、题目描述

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值