Hat’s Words(字典树)

G - Hat’s Words
Time Limit:1000MS    Memory Limit:32768KB    64bit IO Format:%I64d & %I64u
Appoint description:

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

题意: 题目给出不超过50,000个英文单词表,问在这些单词中,是否有一类单词是由两个单词组合而成的,且这些单词都在单词表中.

题解:简单的字典树问题,按字符串长度大小从小到大排序,再建字典树.在插入操作时,如果发现当前单词的前缀是一个完整的单词,则dfs搜索,看是否后半部分是不是一个完整的单词就可以了. 最后把所有符合条件的单词按字典树排序输出就行.

AC代码:
#include <iostream>
#include <cstring>
#include <sstream>
#include <cstdio>
#include <cmath>
#include <bitset>
#include <map>
#include <queue>
#include <vector>
#include <cstdlib>
#include <algorithm>

#define ls u << 1
#define rs u << 1 | 1
#define lson l, mid, u << 1
#define rson mid + 1, r, u << 1 | 1
#define INF 0x3f3f3f3f
#define MAX 26

using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int M = 5e4 + 100;
const int mod = 1e9 + 7;
bool flag;
string s[M],res[M];
struct Trie {
    int index;
    Trie *next[MAX];
    Trie() {
        index = 0;
        memset(next,0,sizeof(next));
    }
};

Trie *root = new Trie;

bool cmp(string a,string b) {
    //if(a.size() == b.size()) return a < b;
    return a.size() < b.size();
}

bool cmp1(string a,string b) {
    return a < b;
}


void dfs(Trie *tr,int len,int i) {
    int u = s[i][len] - 'a';
    if(tr->index && !s[i][len]) {
        flag = true;
        return;
    }
    if(!s[i][len]) return;
    if(tr->next[u]) dfs(tr->next[u],len + 1,i);
}

void Trie_insert(Trie *tr,int len,int i) {
    if(s[i][len]) {
        int u = s[i][len] - 'a';
        if(tr->next[u] == 0) tr->next[u] = new Trie;
        else if(tr->next[u]->index) {
            if(!flag) dfs(root,len + 1,i);
        }
        Trie_insert(tr->next[u],len + 1,i);
    } else tr->index = 1;
}

int main() {
    //freopen("in","r",stdin);
    ios::sync_with_stdio(false);
    int n = 0;
    while(cin>>s[n]) {
        n++;
    }
    sort(s,s + n,cmp);
    int to = 0;
    for(int i = 0; i < n; i++) {
        flag = false;
        Trie_insert(root,0,i);
        if(flag) res[to++] = s[i];
    }
    sort(res,res + to,cmp1);
    for(int i = 0; i < to; i++) cout<<res[i]<<endl;
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值