CodeVS 1018 单词接龙(DFS)

题目大意:

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

 注意每个单词可以用两次,因为一个单词用一遍只取到了头,还要再用一遍单词取到尾。

代码:

#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;
}

 

posted @ 2017-10-09 16:13  prog123  阅读(328)  评论(0编辑  收藏  举报