算法训练VIP 单词接龙
由此篇博文启发:蓝桥杯 单词接龙
题目描述
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都 最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at和atide间不能相连。
样例说明
连成的“龙”为atoucheatactactouchoose
输入
输入的第一行为一个单独的整数n (n< =20)表示单词数,以下n行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
输出
只需输出以此字母开头的最长的“龙”的长度
样例输入
5
at
touch
cheat
choose
tact
a
样例输出
23
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
struct Alpha
{
string alpha;
int count = 2;
};
Alpha alphas[21];
int n;
char bc;
int ans = 0;
void getBestDragonLenth(string now_str, int sum)//当前拼接的字符串,当前龙的长度
{
ans = max(ans, sum);
for (int i = 0; i < n; i++)
{
if (alphas[i].count > 0)
{
for (int j = now_str.size() - 1; j >= 0; j--)//从当前拼接的字符串的末尾依次到首部的开始与单词首部比较
{
int temp = j;
for (int k = 0; k < alphas[i].alpha.size() && temp < now_str.size(); k++)//如果当前拼接的字符串的总长度-j(temp)位以后与单词的前k位相等则temp会等于当前拼接字符串的长度
{
if (now_str[temp] == alphas[i].alpha[k])
{
temp++;
}
else break;
}
if (temp == now_str.size())//如果能够符合连接
{
alphas[i].count--;
getBestDragonLenth(alphas[i].alpha, sum + alphas[i].alpha.size() - (now_str.size() - j));
alphas[i].count++;
break;
}
}
}
}
}
int main()
{
cin >> n;
//先寻找与给定字符复合的字符串作为龙首
for (int i = 0; i < n; i++)
{
cin >> alphas[i].alpha;
}
cin >> bc;
for (int i = 0; i < n; i++)
{
if (alphas[i].alpha[0] == bc)
{
alphas[i].count--;
getBestDragonLenth(alphas[i].alpha, alphas[i].alpha.size());
alphas[i].count++;
}
}
cout << ans;
return 0;
}