题目描述
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beastbeast和astonishastonish,如果接成一条龙则变为beastonishbeastonish,另外相邻的两部分不能存在包含关系,例如atat 和 atideatide 间不能相连。
输入格式
输入的第一行为一个单独的整数nn (n \le 20n≤20)表示单词数,以下nn 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
输出格式
只需输出以此字母开头的最长的“龙”的长度
输入输出样例
输入 #1复制
5 at touch cheat choose tact a
输出 #1复制
23
说明/提示
(连成的“龙”为atoucheatactactouchoose)
NOIp2000提高组第三题
深度优先搜索
#include<iostream>
#include<vector>
#include<climits>
#include<queue>
#include<string>
#include<algorithm>
#include<cmath>
using namespace std;
int a[25];
string s[25];
char ch;
int res;
int b[25][25];
int tag[25];
void dsf(int n,int p,int& count)
{
if (count > res)
res = count;
if (b[p][0] == 0)
{
return;
}
for (int i = 1; i < b[p][0];i+=2)
{
if (tag[b[p][i]] >= 2)
continue;
count += s[b[p][i]].size() - b[p][i + 1];
tag[b[p][i]]++;
dsf(n, b[p][i], count);
tag[b[p][i]]--;
count -= s[b[p][i]].size() - b[p][i + 1];
}
}
int main()
{
int n;
cin>> n;
for (int i = 1; i <= n; i++)
{
cin >> s[i];
}
cin >> s[0];
for (int i = 0; i <=n; i++)
{
for (int j = 1; j <= n; j++)
{
int h, k=0,r;
for (i==0?h =0:h=1; h < s[i].size(); h++)//不可能全部匹配
{
if (s[i][h] == s[j][0])
{
if ((int(s[i].size()) - h < s[j].size()) && s[i].substr(h, int(s[i].size()) - h) == s[j].substr(0, int(s[i].size()) - h))
{
k = int(s[i].size()) - h;
}
}
}
int tmp = b[i][0];
if (k > 0)
{
b[i][tmp + 1] = j;
b[i][tmp + 2] = k;
b[i][0] += 2;
}
}
}
int count = 1;
dsf(n,0,count);
cout << res;
//system("pause");
return 0;
}