【 题目描述 】
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at 和 atide 间不能相连。
【 输入 】
输入的第一行为一个单独的整数n (n< =20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
【 输出 】
只需输出以此字母开头的最长的“龙”的长度
【 样例输入 】
5 at touch cheat choose tact a
【 样例输出 】
23
【提示】
样例说明
连成的“龙”为atoucheatactactouchoose
#include <iostream>
using namespace std;
const int N = 25;
int n, ans;
string word[N];
int g[N][N];
int used[N];
void dfs(string dragon, int last){
ans = max(ans, (int)dragon.size());
used[last] ++;
for(int i = 0; i < n; i ++){
if(used[i] < 2 && g[last][i])
dfs(dragon + word[i].substr(g[last][i]), i);
}
used[last] --;
}
int main(){
cin >> n;
for(int i = 0; i < n; i++) cin >> word[i];
char st;
cin >> st;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++){
string a = word[i], b = word[j];
for(int k = 1; k < min(a.size(), b.size()); k++){
if(a.substr(a.size() - k, k) == b.substr(0, k)){
g[i][j] = k;
break;
}
}
}
for(int i = 0; i < n; i++){
if(word[i][0] == st)
dfs(word[i], i);
}
cout << ans << endl;
return 0;
}