单词接龙

                                                  单词接龙 (NOIP提高组2000
描述

单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定 一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast 和 astonish,如果接成一条龙则变为 beastonish。另外,相邻的两部分不能存在真包含关系,例如 at 和 atide 间不能相连,但 america 可以与自身连接成为 americamerica。

格式

输入格式

输入的第一行为一个单独的整数n (n<=20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.

输出格式

只需输出以此字母开头的最长的“龙”的长度

样例

 

5
at
touch
cheat
choose
tact
a

 

23

    先用个数组保存两个单词的可加长度,即把单词b接在a的后面, 如 at 和  touch, 可加长为 4, 这里我用string 的 substr函数解决, 省了不少事情。然后暴力搜索可加长 > 0的单词 而且还要出现的次数少于两次, 不断更新最大值即可。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
const int MAXN = 22;
string s[MAXN];
int con[MAXN][MAXN], n;
int vis[MAXN];
char start;
int ans = 0, t;

int connect(string a, string b){
    int aL = a.size(), bL = b.size();
    for(int i = 1; i < min(aL, bL); i++){
        if(a.substr(aL - i, aL) == b.substr(0, i)){
            return (bL - i);
        }
    }
    return 0;
}
typedef pair<int, int>P;
void dfs(P p){
    for(int i = 0; i < n; i++){
        if(con[p.first][i] > 0 && vis[i] < 2){
            vis[i]++;
            ans = max(ans, (t =  p.second + con[p.first][i]));
            dfs(P(i, t));
            vis[i]--;
        }
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 0; i < n; i++) cin >> s[i];
    cin >> start;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            con[i][j] = connect(s[i], s[j]);
        }
    }
    for(int i = 0; i < n; i++){
        if(s[i][0] == start){
            memset(vis, 0, sizeof(vis));
            vis[i]++;
            ans = max(ans, (t = s[i].size()));
            dfs(P(i, t));
        }
    }
    cout << ans << endl;
    return 0;
}
View Code

 



原文地址:https://www.cnblogs.com/cshg/p/5721266.html