算法训练 单词接龙
2016-04-19 17:28
363 查看
问题描述
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at 和 atide 间不能相连。
输入格式
输入的第一行为一个单独的整数n (n<=20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
输出格式
只需输出以此字母开头的最长的“龙”的长度
样例输入
5
at
touch
cheat
choose
tact
a
样例输出
23
样例说明
连成的“龙”为atoucheatactactouchoose
单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 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 MAXN 20 #define MAXW 100 char head, w[MAXN][MAXW]; int N, vi[MAXN]={0}, length = 0; int isConnect(char str1[], char str2[]) { int i; char temp1[MAXW], temp2[MAXW]; strcpy(temp2, str2); int strEnd = strlen(str1)-1; for(i=strEnd; i>0; i--){ if(str1[i] == temp2[0]){ strcpy(temp1, &str1[i]); temp2[strEnd-i+1] = '\0'; if(strcmp(temp1,temp2) == 0){ strcat(str1, &str2[strEnd-i+1]); return 1; } } } return 0; } void connectDragon(char s[MAXW]) { int i; char temp[MAXW]; if(strlen(s) > length){ length = strlen(s); } strcpy(temp, s); for(i=0; i<N; i++){ if(vi[i] < 2 && isConnect(temp, w[i])){ vi[i] ++; connectDragon(temp); strcpy(temp, s); vi[i]--; } } } int main() { int i; scanf("%d", &N); for(i=0; i<N; i++){ scanf("%s", w[i]); } getchar(); scanf("%c", &head); length = 0; for(i=0; i<N; i++){ if(w[i][0] == head){ vi[i] ++; connectDragon(w[i]); vi[i] --; } } printf("%d", length); return 0; }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析