• 单词接龙


    题目描述 Description
        单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at和atide间不能相连。
    
    输入描述 Input Description
       输入的第一行为一个单独的整数n(n<=20)表示单词数,以下n行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
    
    输出描述 Output Description
       只需输出以此字母开头的最长的“龙”的长度
    
    样例输入 Sample Input
    5
    
    at
    
    touch
    
    cheat
    
    choose
    
    tact
    
    a
    
     
    
    样例输出 Sample Output
    23   
    
    
    
    #include<iostream>
    
    #include<cstring>
    using namespace std;
    int n,maxl;
    struct ss
    {
        char word[10000];
        int len;
        int v;
    };
    struct ss s[21];
    void dfs(int x,int len)
    {
        int i,j,k;
        for(i=1;i<=n;i++)//遍历所有单词
        {
            if(s[i].v<2)// 检查是否用过
            for(j=0;j<s[x].len;j++)
            {
                if(s[x].word[j]==s[i].word[0])// 当待接的单词的头等于龙的某一个时,开始循环
                {
                    int a=j+1,b=1;
                    bool flag=true;
                    for(;a<s[x].len&&b<s[i].len;b++,a++)
                    {
                        if(s[i].word[b]!=s[x].word[a])
                        {
                            flag=false;
                            break;
                        }
    
                    }
                    if(flag)
                    {
                        s[i].v++;
                        dfs(i,len+s[i].len-b);
                        s[i].v--;//回溯
                    }
                }
            }
        }
        if(len>maxl)
            maxl=len;
    
    }
    
    
    int main()
    {
        int i;
        cin>>n;
        for( i=1;i<=n;i++)
        {
            cin>>s[i].word;
            s[i].len=strlen(s[i].word);
        }
         cin>>s[0].word;
         s[0].len=strlen(s[0].word);
        dfs(0,s[0].len);
        cout<<maxl;
        return 0;
    }


  • 相关阅读:
    EasyARM-Linux工具
    EasyARM-Linux文件系统
    EasyARM-Linux使用
    公差-PCBA
    novoton-USBDevice使用
    novoton-RTC使用
    novoton-ADC使用
    novoton-I2C使用
    novoton-timer使用
    novoton-usart使用
  • 原文地址:https://www.cnblogs.com/37kiazz73/p/10316874.html
Copyright © 2020-2023  润新知