Hat’s Words HDU - 1247 (字典树经典题目-拼单词)

Hat’s Words

 HDU - 1247 

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<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<utility>
#include<set>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#define maxn 50005
#define INF 0x3f3f3f3f
#define LL long long
#define ULL unsigned long long
#define E 1e-8
#define mod 1000000007
#define P pair<int,int>
using namespace std;

int tree[maxn][26];
int idx(char c){return c-'a';}
int tot = 1;
bool is_word[maxn];
void Insert(char s[],int u) //插入字符串s
{
    for(int i=0;s[i];++i){
        int c = idx(s[i]);
        if(!tree[u][c])
            tree[u][c] = ++tot;
        u = tree[u][c];
    }
    is_word[u] = true; //标记这个单词结束
}
bool Find(char s[],int u) //查询s是否是前缀
{
    for(int i=0;s[i];++i){
        int c = idx(s[i]);
        if(!tree[u][c])
            return false;
        u = tree[u][c];
    }
    return is_word[u];
}
char s[maxn][20],ns[20];
int main()
{
    int n = 0;
    while(scanf("%s",s[n])!=EOF){
        Insert(s[n++],1);
    }
    for(int i=0;i<n;++i){
        for(int j=1;s[i][j];++j){
            memcpy(ns,s[i],sizeof(s[i])); //将s[i]复制到ns中
            ns[j] = 0;
            if(Find(ns,1)&&Find(s[i]+j,1)){ //s[i]+j:从s[i]的第j个开始
                //将s分成两部分进行分别查找
                printf("%s\n",s[i]);
                break;
            }
        }
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值