一道折磨了我两个小时的字典树发现原来是字符串拆分…
HDU传送门
Vjudgge传送门
题目 Hat’s Words
Problem Description
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
题目大意
按照字典序给你一堆字符串。
如果其中有一个字符串可以由另外两个串组成,输出那个被组成的串。
输出要字典序输出。
代码
//#include<bits/stdc++.h>杭电不能用万能头,可恶啊。
#include<iostream>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<vector>
using namespace std;
#define IOS ios::sync_with_stdio(false)
const int N = 1e5 + 10;
int tr[N][26], tot = 0, End[N];
vector<string>t, ans;
//数据结构^.^
void insert(string s) {
int pos = 0, len = s.length();
for (int i = 0; i < len; i++) {
int c = s[i] - 'a';
if (tr[pos][c] == 0) {
tr[pos][c] = ++tot;
}
pos = tr[pos][c];
}
End[pos] = 1;
}
int query(string s) {
int pos = 0, len = s.length();
for (int i = 0; i < len; i++) {
int c = s[i] - 'a';
if (tr[pos][c] == 0) return 0;
pos = tr[pos][c];
}
return End[pos];
}
int main(int argc, char** argv) {
string str;
while(cin >> str) {
insert(str);
t.push_back(str);
}
for(int i = 0; i < t.size(); i++){
for(int j = 0; j < t[i].length(); j++){
string a = t[i].substr(0, j+1);
string b = t[i].substr(j+1);
//这里拆分字符串~
//其中空串是不会在字典树里面找到的所以->
//不用担心一个单词由他本身与空串这样的组合可以被找到。
if(query(a) && query(b)){
ans.push_back(t[i]);
break;
}
}
}
sort(ans.begin(), ans.end());//字典序输出,排个序。
for(int i = 0; i < ans.size(); i++) cout << ans[i] << endl;
return 0;
}
至此。