HDU 1247 Hat’s Words(字典树)

36 篇文章 0 订阅
24 篇文章 1 订阅

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247

Hat’s Words

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13822 Accepted Submission(s): 4961

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

【中文题意】问你哪个单词可以由词库中的其他单词连接组成。
【思路分析】创建一棵字典树,然后对每一个单词暴力处理就好了。
【AC代码】

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<string.h>
#include<cmath>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
#define maxn 50005//字典树的总层数
#define trsize 26//字典树每一层需要26个空间

struct Trie
{
    int ch[maxn][trsize];
    bool isEnd[maxn];
    int size;
    void init()
    {
        size=1;
        memset(ch[0],0,sizeof(ch[0]));
        memset(isEnd,0,sizeof(isEnd));
    }
    int index(char c)
    {
        return c-'a';
    }
    void insert(char *s)//插入一个单词
    {
        int i,rt;
        for(i=rt=0; s[i]!='\0'; i++)
        {
            int c=index(s[i]);
            if(!ch[rt][c])
            {
                memset(ch[size],0,sizeof(ch[size]));
                ch[rt][c]=size++;
            }
            rt=ch[rt][c];
        }
        isEnd[rt]=1;
    }
    bool find(char *s)//查找一个单词是否存在
    {
        int i,rt;
        for(i=rt=0; s[i]!='\0'; i++)
        {
            int c=index(s[i]);
            if(!ch[rt][c])
                return false;
            rt=ch[rt][c];
        }
        return isEnd[rt];
    }
} trie;

char s[maxn][50];//输入的单词
char str[50];//充当临时变量的作用
int main()
{
    int n;
    trie.init();
    for(n=0; scanf("%s",s[n])!=EOF; n++)
    {
        trie.insert(s[n]);
    }
    for(int i=0; i<=n; i++)
    {
        int len=strlen(s[i]);
        for(int j=1; j<len; j++)
        {
            memset(str,0,sizeof(str));
            strncpy(str,s[i],j);
            if(trie.find(str)&&trie.find(s[i]+j))
            {
                printf("%s\n",s[i]);
                break;
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值