Hats’Worlds(字典树)

本文介绍了一个算法问题,即如何从给定的字典中找出所有由两个其他单词组成的单词(Hat's Words)。通过构建字典树来高效地解决这一问题,并提供了一段完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Hats’World

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
题目大意:
给定一组单词,让你找到一个单词,使得这个单词由这组单词中出现过的两个单词构成。
例:ahat由a和hat构成,而a和hat在这组单词中出现过。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=50010;
struct node
{
    int next[27];
    int b;
}tree[maxn];
int tot=1,sum,top,stack[maxn];
char s[maxn][27];
void build_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
        {
            tree[now].next[x]=++sum;
            now=sum;
        }
    }
    tree[now].b=true;
}
int can(int l,char s[])
{
    int i=0,now=0,top=0;
    for(int i=0;i<l;i++)
    {
        int x=s[i]-96;
        if(tree[now].next[x])
        now=tree[now].next[x];
        else return 0;
        if(tree[now].b&&s[i])
        stack[top++]=i+1;
    }
    while(top)
    {
        int now=0;
        bool flag=1;
        int x=stack[--top];
        while(s[x])
        {
            if(!tree[now].next[s[x]-96])
            {
                flag=0;
                break;
            }
            now=tree[now].next[s[x]-96];
            x++;
        }
        if(flag&&tree[now].b)
        return 1;
    }
    return 0;
}
int main()
{
    while(gets(s[tot])&&strlen(s[tot]))
    {
        int len=strlen(s[tot]);
        build_tree(len,s[tot]);
        tot++;
    }
    for(int i=1;i<=tot;i++)
    {
        int len=strlen(s[i]);
        if(can(len,s[i]))
        cout<<s[i]<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值