题目链接!
题目描述
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at 和 atide 间不能相连。
输入输出格式
输入格式:
输入的第一行为一个单独的整数n (n<=20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
输出格式:
只需输出以此字母开头的最长的“龙”的长度
输入输出样例
输入样例#1:
5
at
touch
cheat
choose
tact
a
输出样例#1:
23 (连成的“龙”为atoucheatactactouchoose)
思路:
DFS解字符串,大暴力,主义回溯和代码中给的提示,现在开始补习搜索知识。
#pragma comment(linker, "/STACK:1024000000,1024000000") //进行手动扩栈,这样就不会引起爆栈
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <map>
#define maxn 25
using namespace std;
typedef long long LL;
map<string, int> ma; //标记出现的串
map<string, int> ma1; //每个串用的次数
char str[25][maxn];
int res = 0, n;
void dfs(char * s, int L) {
res = max(L, res);
char s1[maxn], s2[maxn], s3[maxn];
int len = strlen(s);
for(int i = 0; i < len; i++) {
for(int j = 0; j < n; j++) {
int cnt = strlen(str[j]);
if(cnt < i || ma1[str[j]] > 1) continue;
for(int p = 0; p <= i; p++) {
s1[p] = s[len - i + p - 1];
}
s1[i + 1] = '\0'; //切记本处
for(int p = 0; p <= i; p++) {
s2[p] = str[j][p];
}
s2[i + 1] = '\0';
if(strcmp(s2, s1)) continue;
if(ma[s3]) continue;
L = L + cnt - i - 1;
ma1[str[j]]++;
dfs(str[j], L);
L = L - cnt + i + 1;
ma1[str[j]]--;
}
}
}
int main() {
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%s", str[i]);
ma[str[i]]++;
}
char ch[maxn];
scanf("%s", ch);
dfs(ch, 1);
printf("%d\n", res);
return 0;
}