您的位置:首页 > 其它

算法训练 单词接龙

2016-04-19 17:28 316 查看
问题描述

  单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法