1. 程式人生 > >HDU 1247 - Hat’s Words - [字典樹水題]

HDU 1247 - Hat’s Words - [字典樹水題]

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=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

 

題意:

“帽子單詞”是指,若字典中的某個詞,它是由其他任意兩個單詞連線起來組成的,則稱它為“帽子單詞”。

現在以字典序給出字典中的所有單詞(不超過 $5e4$ 個),讓你求出全部“帽子單詞”。

 

題解:

先把字典建成字典樹,然後對於每個單詞,暴力地分成兩個子串查詢即可。

 

AC程式碼:

#include<bits/stdc++.h>
using namespace std;
const int maxn=5e4+5;

namespace Trie
{
    const int SIZE=maxn*32;
    int sz;
    struct TrieNode{
        int ed;
        int nxt[26];
    }trie[SIZE];
    void init(){sz=1;}
    void insert(const string& s)
    {
        
int p=1; for(int i=0;i<s.size();i++) { int ch=s[i]-'a'; if(!trie[p].nxt[ch]) trie[p].nxt[ch]=++sz; p=trie[p].nxt[ch]; } trie[p].ed++; } int search(const string& s) { int p=1; for(int i=0;i<s.size();i++) { p=trie[p].nxt[s[i]-'a']; if(!p) return 0; } return trie[p].ed; } }; int tot; string s[maxn]; int main() { ios::sync_with_stdio(0); cin.tie(0), cout.tie(0); Trie::init(); tot=0; while(cin>>s[++tot]) Trie::insert(s[tot]); for(int i=1;i<=tot;i++) { bool ok=0; for(int k=1;k<s[i].size();k++) { if(Trie::search(s[i].substr(0,k)) && Trie::search(s[i].substr(k,s[i].size()-k))) { ok=1; break; } } if(ok) cout<<s[i]<<'\n'; } }