字典树——Hdu 1247 Hat’s Words

Hat’s Words

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


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

题目大意:

在所给的单词表中,按字典序输出符合条件的 hat's word ,条件为: hat's word 恰好由所给单词表中的另外两个单词拼接而成。
思路:
对每一个单词判断,该单词所分为的两个单词是否都在所给单词表中,由于单词的数量最大为50000,判断拆分出的单词是否在单词表中是比较耗时的,所以为了提高效率,这里把所给单词另外建立成一棵字典树。


#include <stdio.h>
#include <string.h>

#define MAX 26
#define SIZE 50005
#define LENGTH 100

typedef struct Trie_Node
{
	Trie_Node *child[MAX];
	bool flag;				//标记是否为一个单词结尾
	Trie_Node(void)
	{
		flag = false;
		memset(child, NULL, sizeof(child));
	}
}*Trie;

char wordList[SIZE][LENGTH];

void InitTrie(Trie &root)
{
	root = new Trie_Node;
}

void Insert(Trie curNode, char *word)
{
	int i, j;
	for (i = 0; word[i] != '\0'; i++)
	{
		j = word[i] - 'a';
		if (curNode->child[j] == NULL)
		{
			curNode->child[j] = new Trie_Node;
		}
		curNode = curNode->child[j];
	}
	curNode->flag = true;
}

bool LookUp(Trie curNode, char *word)
{
	int i, j;
	for (i = 0; word[i] != '\0'; i++)
	{
		j = word[i] - 'a';
		if (curNode->child[j] == NULL)
		{
			return false;
		}
		curNode = curNode->child[j];
	}
	return curNode->flag;
}

void HatsWord(Trie root, int size)
{
	int i, j, k;
	Trie curNode = NULL;
	for (i = 0; i < size; i++)
	{
		curNode = root;
		for (j = 0; wordList[i][j] != '\0'; j++)
		{
			//判断单词的前一部分所组成的单词是否已经出现在字典中
			if (curNode->flag)
			{
				//判断剩下部分所组成的单词是否也在字典中
				if (LookUp(root, &wordList[i][j]))
				{
					puts(wordList[i]); break;
				}
			}
			k = wordList[i][j] - 'a';
			if (curNode->child[k] == NULL)
			{
				break;
			}
			curNode = curNode->child[k];
		}
	}
}

int main(void)
{
	int i;
	Trie dict = NULL;
	InitTrie(dict);

	for (i = 0; scanf("%s", wordList[i]) != EOF; i++)
	{
		Insert(dict, wordList[i]);
	}
	HatsWord(dict, i);
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

庞老板

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值