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.
输入
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.
输出
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
题意
模板题 输出有点麻烦,,,
AC代码
#include <bits/stdc++.h>
using namespace std;
#define LL long long
#define CLR(a,b) memset(a,(b),sizeof(a))
#define lson st<<1
#define rson st<<1|1
const int MAXN = 1e6+10;
int trie[MAXN][26]; // trie[i][j] = k// 表示i的节点的第j个孩子是编号为k的节点
int sum[MAXN];
int tot, n;
bool vis[MAXN];
void sert(string s, int root) {
for(int i = 0; i < s.size(); i++) {
int x = s[i]-'a';
if(trie[root][x]==0)
trie[root][x] = ++tot;
root = trie[root][x];
}
vis[root] = true;
}
bool find(string s, int root) {
for(int i = 0; i < s.size(); i++) {
int x = s[i]-'a';
if(trie[root][x]==0)
return 0;
root = trie[root][x];
}
return vis[root];
}
vector<string> v, vv;
int main() {
tot = 1;
bool flag = false;
int root = 1;
string s;
while(cin >> s) {
sert(s,root);
v.push_back(s);
s.clear();
}
for(int i = 0; i < v.size(); i++) {
for(int j = 0; j < v[i].size(); j++) {
string s1 = v[i].substr(0,j+1), s2 = v[i].substr(j+1);
if(find(s1,root) && find(s2,root)) {
vv.push_back(v[i]); break;
}
}
}
sort(vv.begin(), vv.end());
for(int i = 0; i < vv.size(); i++) cout << vv[i] << endl;
return 0;
}