HDU 1247 Hat’s Words 字典树
2015-10-30 19:56
429 查看
Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 11324 Accepted Submission(s): 4044
[align=left]Problem Description[/align]
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.
[align=left]Input[/align]
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.
[align=left]Output[/align]
Your output should contain all the hat’s words, one per line, in alphabetical order.
[align=left]Sample Input[/align]
a
ahat
hat
hatword
hziee
word
[align=left]Sample Output[/align]
ahat
hatword
题意:寻找由其它单词组合得到的单词
思路:对所有的单词建立字典树,然后,对每一个单词暴力分割,将分割得到的两部分 放入字典树中搜索,根据搜索结果判断。
坑点:1.建立字典树的时候,需要标记每一个单词的结束节点
2.如果搜索到一个单词符合条件,需要跳出循环,防止多次输出
#include <iostream>
#include <stdio.h>
#include <string.h>
#define MAX 26
using namespace std;
struct trie
{
bool is_end;//标记该节点所表示的是不是完整的单词
trie* next[MAX];
};
trie* root=new trie;
char words[50000][100];
void insert_node(char* str)
{
trie *p,*newnode;
p=root;
for(int i=0;str[i]!='\0';i++)
{
if(p->next[str[i]-'a']==NULL)
{
newnode=new trie;
newnode->is_end=false;
for(int j=0;j<MAX;j++)
newnode->next[j]=NULL;
p->next[str[i]-'a']=newnode;
p=newnode;
}
else
{
p=p->next[str[i]-'a'];
}
}
p->is_end=true;
}
int find_str(char *str)
{
trie *p=root;
for(int i=0;str[i]!='\0';i++)
{
if(p->next[str[i]-'a']!=NULL)
p=p->next[str[i]-'a'];
else
return 0;
}
if(p->is_end==true)
return 1;
else
return 0;
}
void get_sub(char *dst,char *src, int s,int l)
{
int i;
for(i=s;i<s+l;i++)
dst[i-s]=src[i];
dst[i-s]='\0';
}
int main()
{
char temp[20];
int flag1,flag2,len;
int p=0;
for(int i=0;i<MAX;i++)
root->next[i]=NULL;
while(gets(words[p]))
{
if(words[0]=='\0')
break;
insert_node(words[p]);
p++;
}
for(int i=0;i<p;i++)
{
len=strlen(words[i]);
for(int j=1;j<len;j++)
{
get_sub(temp,words[i],0,j);
flag1=find_str(temp);
get_sub(temp,words[i],j,len-j);
flag2=find_str(temp);
if(flag1&&flag2)
{
printf("%s\n",words[i]);
break;//注意需要跳出,防止重复输出
}
}
}
return 0;
}
相关文章推荐
- 字典树的基本知识及使用C语言的相关实现
- Trie树_字典树(字符串排序)简介及实现
- HDU 1568
- HDU1290
- HDU1568(Fobonacci公式)
- HDU ACM Step 2.2.2 Joseph(约瑟夫环问题)
- HDU 1405
- HDU 1297
- hdu 1205
- hdu 2087
- hdu 1016
- HDU 4898 The Revenge of the Princess’ Knight ( 2014 Multi-University Training Contest 4 )
- HDU 5240 Exam (好水的题)
- HDU5237 Base64 大模拟
- HDU 1000
- HDU 1001
- hdu-5385
- hdu-5405
- hdu-5490
- HDU 1622 Trees On The Level