HDU 1247 trie树 + 暴力查询

来源:互联网 发布:淘宝怎么取消开店认证 编辑:程序博客网 时间:2024/06/13 01:39

传送门:HDU 1247

题意

按字典序给出单词, 找出其中可有可由其他两个单词组成的单词输出


题解

更开始想的是倒序插入字典树然后dfs搜索回溯输出, wa, 不过应该也能出来可能我写的太挫….
这题没给具体的单词长度限制, 但是数据不是很大, 就想到了把单词暴力拆分成两部分分开在字典树中查找, A了


AC code:

/** Author : adrui* Language : C++* Result : Accepted* Love : yy* Favorite : Dragon Balls* Standing in the Hall of Fame*/#include<cstdio>#include<cstring>#include<queue>#include<algorithm>#include<iostream>using namespace std;#define debug 0#define LL long long#define inf 0x7f7f7f7f#define mod 10003#define mid ((l + r) >> 1)#define ls rt << 1, l, mid#define rs rt << 1|1, mid + 1, r#define M(a, b) memset(a, b, sizeof(a))const int maxn = 50000 + 5;int n;int ch[maxn][26], val[maxn];int idx(char p) {    return p - 'a';}struct trie {    int sz;    trie() {        sz = 1;        M(ch, 0);        M(val, 0);    }    bool query(char *s) {           //查询        int len = strlen(s), u = 0;        for (int i = 0; i < len; ++i) {            int c = idx(s[i]);            if (!ch[u][c]) {                return false;            }            u = ch[u][c];        }        return val[u] == 1;    }    void dfs(char *s) {        int len = strlen(s);        if (len < 2) return;           //暴力拆分查找        char tmp1[40], tmp2[40];        for (int i = 0; i < len - 1; i++) {                for (int j = 0; j <= i; ++j)                    tmp1[j] = s[j];                tmp1[i + 1] = '\0';                for (int j = i + 1; j < len; ++j)                     tmp2[j - i - 1] = s[j];                tmp2[len - i - 1] = '\0';                 if (query(tmp1) && query(tmp2)) {                    cout << s << endl;                    return;                }        }    }    void insert(char *s) {           //建树        int len = strlen(s), u = 0;        int c;        for (int i = 0; i < len; ++i) {            c = idx(s[i]);            if (!ch[u][c]) {                ch[u][c] = sz;                ++sz;            }            u = ch[u][c];                                    }        val[u] = 1;                                        }};int main() {#if debug    freopen("in.txt", "r", stdin);#endif //debug    cin.tie(0);    cin.sync_with_stdio(false);    char s[maxn][30];    trie root;    int cnt = 0;    while (cin >> s[cnt++]) {        root.insert(s[cnt - 1]);    }    for (int i = 0; i < cnt; i++) {        root.dfs(s[i]);    }    return 0;}
0 0
原创粉丝点击