标签:
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247
题意:输入一些单词,输出这些单词中可以由其他2个单词构成的单词。
思路:暴力+字典树
代码
#include <iostream> #include <stdio.h> #include <string.h> #include <math.h> #include <algorithm> #include <string> #include <vector> using namespace std; #define lson l, m, rt << 1 #define rson m + 1, r, rt << 1 | 1 #define ceil(x, y) (((x) + (y) - 1) / (y)) const int SIZE = 30; const int N = 5e4 + 10; const int INF = 0x7f7f7f7f; struct Trie { int val[SIZE]; bool e; }; int sz; Trie pn[N]; string str[N]; string ans[N]; int newnode() { memset(pn[sz].val, 0, sizeof(pn[sz].val)); return sz++; } void init() { sz = 0; newnode(); } void insert(string s) { int u = 0; for (int i = 0; i < s.size(); i++) { int idx = s[i] - 'a'; if (!pn[u].val[idx]) { pn[u].val[idx] = newnode(); pn[pn[u].val[idx]].e = false; } u = pn[u].val[idx]; } pn[u].e = true; } bool findpre(string s, int st, int ed) { int u = 0; for (int i = st; i <= ed; i++) { int idx = s[i] - 'a'; if (!pn[u].val[idx]) return false; u = pn[u].val[idx]; } if (pn[u].e) return true; return false; } int main() { int n = 0; while (cin >> str[n]) { insert(str[n++]); } int k = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < str[i].size() - 1; j++) if (findpre(str[i], 0, j) && findpre(str[i], j + 1, str[i].size() - 1)) { ans[k++] = str[i]; break; } } sort(ans, ans + k); for (int i = 0; i < k; i++) cout << ans[i] << endl; return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/u014357885/article/details/47702263