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;
}
相關文章
相關標籤/搜索