首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【HDU】1247 - Hat’s Words(字典树)

【HDU】1247 - Hat’s Words(字典树)

作者头像
FishWang
发布2025-08-27 09:51:58
发布2025-08-27 09:51:58
2100
举报

点击打开题目

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 13369 Accepted Submission(s): 4777

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

代码语言:javascript
复制
   a
ahat
hat
hatword
hziee
word

Sample Output

代码语言:javascript
复制
   ahat
hatword

Author

戴帽子的

记得以前好像用map + string做过吧?这次拿字典树拆也可以的。

本来还怕会超时,结果31ms就完了。

就是把每个单词暴力拆开,然后在字典树上查就行了。

代码如下:(注意strncpy的用法,不会自动在字符串后面加 ' \0 ' 的)

代码语言:javascript
复制
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define idx(x) (x-'a')
struct Trie
{
	Trie *next[26];
	bool word;
	void clear()
	{
		for (int i = 0 ; i < 26 ; i++)
			next[i] = NULL;
		word = false;
	}
}tree[100000];
int ant;
void insert(char *s)
{
	int l = strlen(s);
	Trie *p = &tree[0] , *q;
	for (int i = 0 ; i < l ; i++)
	{
		int id = idx(s[i]);
		if (p->next[id] == NULL)
		{
			q = &tree[ant++];
			q->clear();
			p->next[id] = q;
		}
		p = p->next[id];
	}
	p->word = true;
}
bool find(char *s)
{
	int l = strlen(s);
	Trie *p = &tree[0];
	for (int i = 0 ; i < l ; i++)
	{
		int id = idx(s[i]);
		if (p->next[id] == NULL)		//没有这个单词 
			return false;
		p = p->next[id];
	}
	if (p->word)
		return true;
	return false;		//如果有些单词只是 "路过" 也不算 
}
int main()
{
	ant = 1;
	tree[0].clear();
	char str[50011][30];
	int num = 0;
	while (~scanf ("%s",str[num++]))
		insert(str[num-1]);
	for (int i = 0 ; i < num ; i++)		//从第一个单词开始拆
	{
		int l = strlen(str[i]);
		for (int j = 1 ; j < l ; j++)
		{
			char a[30];
			strncpy(a,str[i],j);
			a[j] = '\0';		//strncpy函数不添加'\0' 
			char b[30];
			strcpy(b,str[i]+j);
			if (find(a) && find(b))
			{
				printf ("%s\n",str[i]);
				break;		//输出完此轮不用再搜了 
			}
		}
	}
	return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-08-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Hat’s Words
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档