Hat’s Words(HDU-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

题意:给出多个单词,要在这些单词中找出正好是这多个单词中另外两个单词首尾相连构成的,并按字典序输出所有找到的单词

思路:首先利用给出的单词构建字典树,然后遍历每个单词,将单词分成两段,看这两段是不是都在 Trie 中,若在则直接输出

Source Program

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define E 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD=7;
const int N=100000+5;
const int dx[]= {-1,1,0,0};
const int dy[]= {0,0,-1,1};
using namespace std;

int tot;
int trie[N][50];//trie[rt][x]=tot,root是上个节点编号,x是字母,tot是下个节点编号
bool vis[N];//查询整个单词用
void insert(char *s,int root){
    for(int i=0;s[i];i++){
        int x=s[i]-'a';
        if(trie[root][x]==0)//现在插入的字母在之前同一节点处未出现过
            trie[root][x]=++tot;//字母插入一个新的位置,否则不做处理
        root=trie[root][x];//为下个字母的插入做准备
    }
    vis[root]=true;//标志该单词末位字母的尾结点,在查询整个单词时用
}
bool find(char *s,int root){
    for(int i=0;s[i];i++){
        int x=s[i]-'a';
        if(trie[root][x]==0)
            return false;//以rt为头结点的x字母不存在,返回0
        root=trie[root][x];//为查询下个字母做准备
    }
    return vis[root];//查询整个单词时
}
char word[N][50];
int main(){
    int cnt=0;
    tot=1;
    while(scanf("%s",word[cnt])!=EOF)
        insert(word[cnt++],1);
    for(int i=0;i<cnt;i++){//枚举所有单词
        int len=strlen(word[i]);
        for(int j=1;j<len;j++){//拆分当前单词
            char str1[50],str2[50];
            strncpy(str1,word[i],j);
            str1[j]=0;
            strncpy(str2,word[i]+j,len-j);
            str2[len-j]=0;
            if(find(str1,1) && find(str2,1)){
                printf("%s\n",word[i]);
                break;
            }
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值