HDU - 1247 Hat’s Words(字典树水题)

Hat’s Words

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

题意:给定若干单词,问一个单词能不能被其他两个单词拼接而成。!!题意是这样的,但实际一个单词可以重复用,比如 abab 和 ab,abab 是合法的。

思路:首先肯定先建好字典树。然后枚举每一个单词,在字典树中查询的过程中如果发现出现的单词  就再 check 一遍即可。

AC代码:

#include<bits/stdc++.h>
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair<int,int>
#define clr(a,b) memset((a),b,sizeof(a))
#define rep(i,a,b) for(int i = a;i < b;i ++)
#define pb push_back
#define MP make_pair
#define LL long long
#define ull unsigned LL
#define ls i << 1
#define rs (i << 1) + 1
#define INT(t) int t; scanf("%d",&t)

using namespace std;

const int maxn = 5e4 + 10;
int trie[maxn][26];
int color[maxn];
int k = 1;  /// 0 是根节点
char str[maxn][1000];

void add(char *s){
    int len = strlen(s);
    int p = 0;
    for(int i = 0;i < len;++ i){
        int c = s[i] - 'a';
        if(!trie[p][c]){
            trie[p][c] = k ++;
        }
        p = trie[p][c];
    }
    color[p] = 1;
}

bool check(char *s,int len){
    int p = 0;
    for(int i = 0;i < len;++ i){
        int c = s[i] - 'a';
        if(!trie[p][c])
            return false;
        p = trie[p][c];
    }
    return color[p] == 1;
}

bool solve(char *s){
    int len = strlen(s);
    int p = 0;
    for(int i = 0;i < len;++ i){
        int c = s[i] - 'a';
        if(!trie[p][c]) return false;
        p = trie[p][c];
        if(color[p] && i != len - 1){
            if(check(&s[i + 1],len - i - 1)) return true;
        }
    }
    return false;
}

int main() {
    int index = 0;
    while(~scanf("%s",str[index])){
        add(str[index]);
        ++ index;
    }
    vector<string> ans;
    for(int i = 0;i < index;++ i){
        if(solve(str[i]))
            ans.pb(str[i]);
    }
    sort(ans.begin(),ans.end());
    for(auto it : ans) cout << it << endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值