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
#define debug(x) cout << "[" << #x <<": " << (x) <<"]"<< endl
#define pii pair
#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 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;
}

 

你可能感兴趣的:(#,字典树)