Description–
单词接龙:与成语接龙相类似。
现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分:例如 beast 和 astonish,如果接成一条龙则变为 beastonish。另外相邻的两部分不能存在包含关系:例如 at 和 atide 间不能相连。
对于给定的 N个单词和一个开头的字母,完成这个最长的单词接龙。
洛谷传送
Input–
输入的第一行为一个单独的整数 n 表示单词数。
以下 n 行每行有一个单词。
输入的最后一行为一个单个字符,表示“龙”开头的字母。(以此字母开头的“龙”一定存在。)
Output–
输出以此字母开头的最长的“龙”的长度。
Sample Input–
5
at
touch
cheat
choose
tact
a
Sample Output–
23
说明–
(连成的“龙”为 atoucheatactactouchoose)
n<=20
解题思路–
hhh
代码–
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int n, ans, pd[25];
char a;
string s[25];
void msy(string x, int l)
{
ans = max(ans, l);
string v, w;
for (int i = 1; i < (int)x.size(); ++i) //s1的后i位和s2的前i位相同
{
v = x.substr((int)x.size() - i, i);
for (int j = 1; j <= n; ++j)
if ((int)s[j].size() > (int)v.size() && pd[j] < 2) //不包含且出现次数小于2
{
w = s[j].substr(0, i);
if (v == w)
{
pd[j]++;
msy(s[j], l + (int)s[j].size() - i);
pd[j]--;
}
}
}
}
int main()
{
freopen("english.in", "r", stdin);
freopen("english.out", "w", stdout);
scanf("%d", &n);
for (int i = 1; i <= n;++i)
cin >> s[i];
cin >> a;
for (int i = 1; i <= n; ++i)
if (s[i][0] == a)
{ pd[i]++; msy(s[i], (int)s[i].size()); pd[i]--; }
printf("%d", ans);
return 0;
}