HDU - 1247

· · 个人记录

题意

帽子词是指字典中恰好由另外两个现有单词拼接而成的单词。 你的任务是找出字典中所有的帽子词。

思路

对于每一个单词,我们可以枚举它的拼接位置,尝试找出两个单词可以拼成它。

可以字典树快速查找,写两个字典树,一个存正序的单词,一个存倒序的。

代码

#include <bits/stdc++.h>
#define ll long long
using namespace std;
ll read(){ ll x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-'){ f = -1; } ch = getchar(); } while(ch >= '0' && ch <= '9'){ x = x * 10 + ch - '0', ch = getchar(); } return x * f; }
void write(ll x) { if(x < 0){ putchar('-'), x = -x; } if(x > 9){ write(x / 10); } putchar(x % 10 + '0'); }

const int N = 5e4 + 3, M = 6e6 + 1;
int n;
string s[N];
int ans;

struct trie{
    string s;
    int t[M][27], tc;
    int c[M];
    int cnt[M];

    void change(){
        int p = 0;
        ///cout << "change : " << s << '\n';
        for(int i = 0; i < s.size(); i ++){
            int w = s[i] - 'a';
            if(!t[p][w]) t[p][w] = ++ tc;
            p = t[p][w];
            ///cout << p << ' ';
        }
        ///cout << '\n';
        c[p] ++;
    }

    void Find(){
        int p = 0;
        for(int i = 0; i < s.size(); i ++){
            cnt[i] = 0;
        }
        ///cout << "Find : " << s << '\n';
        for(int i = 0; i < s.size(); i ++){
            int w = s[i] - 'a';
            p = t[p][w];
            if(c[p] && i != s.size() - 1) cnt[i] = 1;
            ///if(c[p] && i != s.size() - 1) cout << p << ' ';
        }
        ///cout << '\n';
    }
}t1, t2;

int main(){

    while(cin >> s[n + 1]) n ++;

    for(int i = 1; i <= n; i ++){
        t1.s = s[i];
        t1.change();
        reverse(s[i].begin(), s[i].end());
        t2.s = s[i];
        t2.change();
        reverse(s[i].begin(), s[i].end());
    }

    for(int i = 1; i <= n; i ++){
        ans = 0;
        t1.s = s[i];
        t1.Find();
        reverse(s[i].begin(), s[i].end());
        t2.s = s[i];
        t2.Find();
        reverse(s[i].begin(), s[i].end());

        for(int j = 0; j < s[i].size() - 1; j ++){
            ans |= t1.cnt[j] & t2.cnt[s[i].size() - j - 2];
            ///cout << i << ' ' << j << ' ' << s[i].size() - j - 2 << ' ' << t1.cnt[j] << ' ' << t2.cnt[s[i].size() - j - 2] << '\n';
        }
        if(ans){
            cout << s[i] << '\n';
        }
    }

    return 0;
}