【洛谷】【搜索+字符串】
题目:[...] (https://www.luogu.org/problemnew/show/P1019)
[Code:]
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n, len[21];
int ans, used[21];
string s[21];
char head;
inline int pipei(string a, string b) {
int lena = a.size(), lenb = b.size();
int ret = 0, l = min(lena, lenb);
for(int i=0; i<l; ++i) {
if(a.substr(lena-i-1, i+1) == b.substr(0, i+1)) return i+1;
}
return 0;
}
void dfs(int sum, string now) {
ans = max(ans, sum);
for(int i=1; i<=n; ++i) {
if(used[i] < 2) {
int k = pipei(now, s[i]);
if(k == 0 || k == len[i]) continue;
++used[i];
int l = now.size();
string tmp = now;
for(int j=k; j<len[i]; ++j) {
now += s[i][j];
}
dfs(sum + len[i] - k, now);
--used[i];
now = tmp;
}
}
}
int main() {
cin >> n;
for(int i=1; i<=n; ++i) {
cin >> s[i];
len[i] = s[i].size();
}
cin >> head;
for(int i=1; i<=n; ++i) {
if(s[i][0] == head) {
used[i] = 1; dfs(len[i], s[i]);
used[i] = 0;
}
}
printf("%d", ans);
return 0;
}