【字典树】 hdu1247 Hat’s Words

Hat’s Words

http://acm.hdu.edu.cn/showproblem.php?pid=1247



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


题意:给你一个字典,问里面那些单词可以由两个字典中单词拼接而成。

PS:我开始理解的题目是单词是要以两个出现过的单词拼接起来才算是hat's word,比如a,a,aa,aa=a+a,如果是a,aa就不行了。

但是最后发现只要是出现过的就行了,数目无所谓,而且单词相同也可以(那two other words是什么意思啊)

题解:字典树,发现有匹配的前缀再去判断剩下的一段是不是有匹配就行了。



#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
struct node
{
    node *next[26];
    int id,num;
    node()
    {
        memset(next,0,sizeof(next));
        id=0;
        num=0;
    }
}*head;
char s[50005];
vector<string> mat,out;
void build(char *s,node *head,int id)
{
    int len=strlen(s),k;
    for(int i=0; i<len; ++i)
    {
        k=s[i]-'a';
        if(head->next[k]==NULL)
            head->next[k]=new node();
        head=head->next[k];
    }
    head->id=id;
    head->num++;
}
bool bfs(char *s,node *head)
{
    int len=strlen(s),j,k,h;
    node *p=head,*q;
    for(int i=0; i<len; ++i,p=p->next[k])
    {
        k=s[i]-'a';
        if(p->next[k]==NULL) return false;
        if(p->next[k]->id)
        {
            q=head;
            for(j=i+1; j<len; ++j,q=q->next[h])
            {
                h=s[j]-'a';
                if(q->next[h]==NULL) break;
            }
            if(j==len&&q->id)
                //if((q->id!=p->next[k]->id)||(q->num>1))
                    return true;
        }
    }
    return false;
}
int main()
{
    head=new node();
    for(int i=1; ~scanf("%s",s); ++i)
    {
        build(s,head,i);
        mat.push_back(string(s));
    }
    for(int i=0; i<mat.size(); ++i)
    {
        strcpy(s,mat[i].c_str());
        if(bfs(s,head))
            out.push_back(mat[i]);
    }
    sort(out.begin(),out.end());
    for(int i=0; i<out.size(); ++i)
        printf("%s\n",out[i].c_str());
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值