【NOIP提高组 】单词接龙
💖The Begin💖点点关注,收藏不迷路💖
|
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如beast和astonish,如果接成一条龙则变为
beastonish,另外相邻的两部分不能存在包含关系,例如at和atide间不能相连。
输入:
输入的第一行为一个单独的整数n (n< =20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
输出:
只需输出以此字母开头的最长的“龙”的长度
样例输入:
5
at
touch
cheat
choose
tact
a
样例输出:
23
提示:
连成的“龙”为atoucheatactactouchoose
#include <stdio.h>
#include <string.h>
#define MAX_N 21 // 单词数最大值
#define MAX_LEN 21 // 单词长度最大值
char words[MAX_N][MAX_LEN]; // 存储输入的单词
int used[MAX_N]; // 记录单词是否已经被使用过
int n; // 单词数
int start_index; // 开始的单词索引
int max_length = 1; // 最长龙的长度
void dfs(int current_index, int length) {
if (length > max_length) {
max_length = length; // 更新最长龙的长度
}
for (int i = 1; i <= n; i++) {
if (used[i] < 2) { // 判断单词是否已经被使用过(最多使用两次)
for (int j = 0; j < strlen(words[current_index]); j++) {
if (words[i][0] == words[current_index][j]) { // 找到以当前单词某个字母开头的单词
int x = j, y = 0;
while (words[i][y] == words[current_index][x] && x < strlen(words[current_index])) {
x++;
y++;
}
if (x >= strlen(words[current_index])) { // 判断两个单词是否可以接龙
used[i]++;
dfs(i, length + strlen(words[i]) - y); // 递归连接下一个单词
used[i]--;
}
}
}
}
}
}
int main() {
scanf("%d", &n); // 读取单词数
for (int i = 1; i <= n; i++) {
scanf("%s", words[i]); // 读取每个单词
}
char start;
scanf(" %c", &start); // 读取龙开头的字母
for (int i = 1; i <= n; i++) {
if (words[i][0] == start) { // 找到以开头字母开始的单词
start_index = i;
used[i]++; // 标记当前单词已经被使用过
dfs(i, strlen(words[i])); // 使用该单词作为起点进行深度优先搜索
used[i]--; // 恢复当前单词的状态,以便在其他路径中使用
}
}
printf("%d\n", max_length); // 输出最长龙的长度
return 0;
}
💖The End💖点点关注,收藏不迷路💖
|