算法训练 单词接龙

问题描述

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

}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值