题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247
题目大意
给你一些串,其中一些串可能会由给出的串中的两个串组成,让你求出这些串,并按字典序输出。
分析
字典序做法,先把每个串放入树中,然后把这些串排序,遍历每个串,把每个串分成两部分(所有可能都考虑),如果这两个部分都能在字典树中查询到,那么就满足条件。
map做法:直接用map标记,查询直接在map中查。
代码
// 字典树做法
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 1e5 + 5;
int k, trie[N][30];
bool vis[N];
string s[N];
bool cmp(const string a, const string b) {
return a < b;
}
void insert(string s) {
int len = s.length();
int p = 0;
for(int i = 0; i < len; i++) {
int x = s[i] - 'a';
if(!trie[p][x])
trie[p][x] = k++;
p = trie[p][x];
}
vis[p] = 1;
}
bool search(string s) {
int len = s.length();
int p = 0;
for(int i = 0; i < len; i++) {
int x = s[i] - 'a';
if(!trie[p][x]) return 0;
p = trie[p][x];
}
return vis[p] == 1;
}
int main() {
k = 1;
memset(trie, 0, sizeof trie);
memset(vis, 0, sizeof vis);
int cnt = 0;
while(cin >> s[cnt]) {
insert(s[cnt]);
cnt++;
}
sort(s, s + cnt, cmp);
for(int i = 0; i < cnt; i++) {
int len = s[i].length();
string s1, s2;
for(int j = 0; j < len - 1; j++) {
s1 = s[i].substr(0, j + 1);
s2 = s[i].substr(j + 1, len - j);
if(search(s1) && search(s2)) {
cout << s[i] << endl;
break;
}
}
}
return 0;
}
// map做法
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <tr1/unordered_map>
using namespace std;
const int N = 5e4 + 5;
string s[N];
tr1::unordered_map<string, int> mp;
bool cmp(const string a, const string b) {
return a < b;
}
int main() {
int cnt = 0;
while(cin >> s[cnt]) {
mp[s[cnt]] = 1;
cnt++;
}
sort(s, s + cnt, cmp);
for(int i = 0; i < cnt; i++) {
int len = s[i].length();
string s1, s2;
for(int j = 0; j < len - 1; j++) {
s1 = s[i].substr(0, j + 1);
s2 = s[i].substr(j + 1, len - j);
if(mp[s1] && mp[s2]) {
cout << s[i] << endl;
break;
}
}
}
return 0;
}