hdu 1247 Hat’s Words

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
 
思路:將每個單詞進行拆分爲兩部分,看一下是否能在字典樹裏找到他。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXNUM 26
using namespace std;
char words[50005][100];

typedef struct Trie
{
	bool flag;
	Trie *next[MAXNUM];
}Trie;

Trie *root;

void init()
{
	root = (Trie *)malloc(sizeof(Trie));
	root->flag = false;
	for (int i = 0;i<MAXNUM;i++)
		root->next[i] = NULL;
}

void insert(char *word)
{
	Trie *tem = root;
	while (*word != '\0')
	{
		if (tem->next[*word - 'a'] == NULL)
		{
			Trie *cur = (Trie *)malloc(sizeof(Trie));
			for (int i = 0;i<MAXNUM;i++)
				cur->next[i] = NULL;
			cur->flag = false;
			tem->next[*word - 'a'] = cur;
		}
		tem = tem->next[*word - 'a'];
		word++;
	}
	tem->flag = true;
}

bool search(char *word)
{
	Trie *tem = root;
	for (int i = 0;word[i] != '\0';i++)
	{
		if (tem == NULL || tem->next[word[i] - 'a'] == NULL)
			return false;
		tem = tem->next[word[i] - 'a'];
	}
	return tem->flag;
}


int main()
{
	init();
	int t = 0;
	char w[100];
	while (scanf("%s", words[t]) != EOF)
	{

		insert(words[t]);
		t++;
	}
	for (int i = 0;i<t;i++)
	{
		memset(w, '\0', sizeof(w));
		for (int j = 0;words[i][j] != '\0';j++)
		{
			*(w + j) = *(words[i] + j);
			if (search(w) && search((words[i] + j + 1)))
			{
				printf("%s\n", words[i]);
				break;
			}
		}

	}
	return 0;
}


發佈了88 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章