hdu 1247 Hat’s Words (字典树)

问题描述:
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

大致题意:
给出若干个单词,找出其中能够由其它两个单词连接组合而成的单词。比如上面sample中的”ahat”能够由”a”和”hat”拼凑而成,”hatword”=”hat”+”word”.因此只需对每个单词进行切分,把切分得到的两个单词在原单词序列中查找,若能查到则符合条件。

思路分析:
字典树。

ac代码:

#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
#define M 50005
#define N 60
char str[M][N];
char s1[N],s2[N];
struct node
{
       int flag;
       node *next[26];
};
void insert(node *root,char s[])
{
     int i=0,j,k;
     int len=strlen(s);
     node *current=root;
     while(i<len)
     {
      k=s[i]-'a';
      if(current->next[k]==NULL)
      {
       node *p=new node;
       for(j=0;j<26;++j)
       p->next[j]=NULL;
       p->flag=0;
       if(i==len-1)
       p->flag=1;        //标记最后一个字符
       current->next[k]=p;
       current=p;
      }
      else
       current=current->next[k];
      ++i;
     }
}
bool search(node *root,char s[])
{
     int i=0,j,k;
     int len=strlen(s);
     node *current=root;
     while(i<len)
     {
      k=s[i]-'a';
      if(current->next[k]==NULL)
      return false;
      current=current->next[k];
      i++;
     }
     return current->flag;
}
int main()
{
    int i,j,k,cnt=0,temp,m,n;
    node *root=new node;
    for(i=0;i<26;++i)
    root->next[i]=NULL;
    root->flag=0;
    while(gets(str[cnt]))
    {insert(root,str[cnt]); cnt++;}
     for(i=0;i<cnt;++i)
      {
      temp=strlen(str[i]);
     for(j=1;j<temp;++j)
      {
      memset(s1,0,sizeof(s1));
      memset(s2,0,sizeof(s2));
      for(m=0;m<j;++m)
      s1[m]=str[i][m];
      for(n=j;n<temp;++n)
      s2[n-j]=str[i][n];
     if(search(root,s1)&&search(root,s2))
      { cout<<str[i]<<endl; break;}
     }
    }
   return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值