您的位置:首页 > 其它

hdu 1247 Hat’s Words

2016-04-05 19:13 344 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: