您的位置:首页 > 其它

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