CodeVS 1018 单词接龙(DFS)

题目大意:ios

http://codevs.cn/problem/1018/spa

 注意每一个单词能够用两次,由于一个单词用一遍只取到了头,还要再用一遍单词取到尾。code

代码:blog

#include <iostream>

using namespace std;

int n;
bool visit[100] = {false};
char ch;
int res = 0,maxn = 0;
string str[100];

using namespace std;

void dfs(int a){

    for(int i = 0; i < 2*n; i++){
        if(visit[i] == false){

            int step = min(str[a].length(),str[i].length());

            for(int j = 1 ; j < step; j++){
                    if(str[a].substr(str[a].length() - j, j) == str[i].substr(0,j)){
                        res = res + str[i].length()-j;
                        visit[i] = true;
                        maxn = max(res,maxn);
                        dfs(i);
                        res = res - str[i].length() + j;
                        visit[i] = false;
                    }
            }
        }

    }

}

int main(){

    cin >> n;
    for(int i = 0; i < 2*n; i+=2){
        cin >> str[i];
        str[i+1] = str[i];
    }

    cin >> ch;

    for(int i = 0; i < 2*n; i++){
        if(str[i][0] == ch){
            visit[i] = true;
            res = res + str[i].length();
            maxn = max(maxn,res);
            dfs(i);
            visit[i] = false;
            res = res - str[i].length();
        }
    }

    cout << maxn << endl;

    return 0;
}
相关文章
相关标签/搜索