Hdu 1247 Hat's Words(Trie树)

本文介绍了一个算法问题,即找出所有由字典中两个单词拼接而成的单词,并提供了一种解决方案,利用Trie树进行单词查找与验证。

Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14083 Accepted Submission(s): 5049
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
Author
戴帽子的
Recommend
Ignatius.L

/*
这题询问Trie树上是否存在一个单词,
满足拆成两部分,使得两部分单词都在树上.
然后其实直接从树上找一个单词
把是单词结尾的位置压栈
然后暴力枚举断点检验即可.
*/
#include<iostream>
#include<cstdio>
#include<cstring>
#define MAXN 300001
#define MAXM 50001
using namespace std;
int tot;
char s[MAXM][27];
struct data{int next[27];bool b;bool w;}
tree[MAXN];
void Add_tree(int l,char s[])
{
    int now=0;
    for(int i=0;i<l;i++)
    {
        int x=s[i]-96; 
        if(tree[now].next[x]) now=tree[now].next[x];
        else tot++,tree[now].next[x]=tot,now=tot;
    }
    tree[now].b=true;
}
bool jd(int l,char s[])
{
    int i=0,top=0,stack[1001],now=0;
    while(s[i])
    {
        if(tree[now].next[s[i]-96]) now=tree[now].next[s[i]-96];
        else return 0;
        if(tree[now].b&&s[i])//所谓割点
          stack[top++]=i+1;
        i++;
    }
    while(top)//检验 
    {
        int now=0;
        bool flag=1;
        int x=stack[--top];
        while(s[x])
        {
            if(!tree[now].next[s[x]-96]){flag=false;break;}
            now=tree[now].next[s[x]-96];
            x++;
        }
        if(tree[now].b&&flag)//该结点是单词的结尾
          return 1;
    }
    return 0;
}
int main()
{
    int i=1;
    while(gets(s[i])&&strlen(s[i]))
    {
        int l=strlen(s[i]);
        Add_tree(l,s[i]);
        i++;
    }
    for(int j=1;j<=i;j++)
    {
        int l=strlen(s[j]);
        if(jd(l,s[j]))
          cout<<s[j]<<endl;
    }
    return 0;
}

转载于:https://www.cnblogs.com/nancheng58/p/10068131.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值