hdu1247 Hat's words trie树

本文介绍了一个有趣的问题:如何找出由字典中恰好两个其他单词拼接而成的单词。通过使用Trie树数据结构来高效地解决这个问题,并给出了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

题意很好理解,就是说给一组字符串,问哪些字符串是由其他正好两个字符串组成的,输出这些字符串。

就是trie树嘛,先把所有字符串存进去,标记结束点,然后每个字符串扫一遍。

唔,对了,一定要记住int型函数在没有规定返回值的时候返回的值会很奇怪(至少肯定不是零,排查了有半天)

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
const int N=100010;
char s[50005][30];
struct node
{
	node* next[26];
	int cnt;
	node()
	{
		memset(next,NULL,sizeof(next));
		cnt=0;
	}
};
node *root=new node();
void build(char str[])
{
	node *p=root;
	int len=strlen(str);
	for(int i=0;i<len;i++)
	{
		int index=str[i]-'a';
		if(p->next[index]==NULL)
		{
			p->next[index]=new node();
		}
		p=p->next[index];
	}
	p->cnt=1;
}
int search(char str[],bool flag)
{
	node* p=root;
	int len=strlen(str);
	//printf(":%s:\n",str);
	if(len==0) return 0;
	for(int i=0;i<len;i++)
	{
		int index=str[i]-'a';
		if(p->next[index]==NULL) return 0;
		p=p->next[index];
		if(p->cnt)
		{
			/*printf("fuk");
			for(int j=0;j<=i;j++)
			printf("%c",str[i]);
			printf("fuk");
			printf("\n");*/
			if(flag==0)
			{
				if(search(&str[i+1],1)) return 1;
			}
			else
				if(i==len-1) return 1;
		}
	}
	return 0;
}
int main()
{
    int m,n=0;
    while(scanf("%s",s[n])!=EOF)
	{
		build(s[n]);
		++n;
	}
	for(int i=0;i<n;i++)
	{
		if(search(s[i],0))
			puts(s[i]);
	}
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值