HDU 1247 Hat’s Words ( Trie树

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.

输入

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.

输出

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 <bits/stdc++.h>
using namespace std;

#define LL long long
#define CLR(a,b) memset(a,(b),sizeof(a))
#define lson  st<<1
#define rson st<<1|1

const int MAXN = 1e6+10;
int trie[MAXN][26];  // trie[i][j] = k// 表示i的节点的第j个孩子是编号为k的节点
int sum[MAXN];
int tot, n;
bool vis[MAXN];
void sert(string s, int root) {
    for(int i = 0; i < s.size(); i++) {
        int x = s[i]-'a';
        if(trie[root][x]==0)
            trie[root][x] = ++tot;
        root = trie[root][x];

    }
    vis[root] = true;
}

bool find(string s, int root) {
    for(int i = 0; i < s.size(); i++) {
        int x = s[i]-'a';
        if(trie[root][x]==0)
            return 0;
        root = trie[root][x];
    }
    return vis[root];
}
vector<string> v, vv;
int main() {
    tot = 1;
    bool flag = false;
    int root = 1;
    string s;
    while(cin >> s) {
        sert(s,root);
        v.push_back(s);
        s.clear();
    }
    for(int i = 0; i < v.size(); i++) {
        for(int j  = 0; j < v[i].size(); j++) {
            string s1 = v[i].substr(0,j+1), s2 = v[i].substr(j+1);
            if(find(s1,root) && find(s2,root)) {
                vv.push_back(v[i]); break;
            }
        }
    }
    sort(vv.begin(), vv.end());
    for(int i = 0; i < vv.size(); i++) cout << vv[i] << endl;
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值