HDU 1247 Hat’s Words 字典树

来源:互联网 发布:尽人事知天命 编辑:程序博客网 时间:2024/06/16 10:51

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


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
aahathathatwordhzieeword
 

Sample Output
ahathatword

题意:寻找由其它单词组合得到的单词

思路:对所有的单词建立字典树,然后,对每一个单词暴力分割,将分割得到的两部分           放入字典树中搜索,根据搜索结果判断。

坑点:1.建立字典树的时候,需要标记每一个单词的结束节点

        2.如果搜索到一个单词符合条件,需要跳出循环,防止多次输出


#include <iostream>#include <stdio.h>#include <string.h>#define MAX 26using 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;}





0 0