HDU 1247 Hat’s Words 字典树

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
  
  
a ahat hat hatword hziee word
 

Sample Output
  
  
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;
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值