0分求助!!!
查看原帖
0分求助!!!
734730
ccc13xx楼主2023/8/17 13:03
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

int dfs(vector<string>& words, string current, int count) {
    int maxLength = count;
    for (int i = 0; i < words.size(); i++) {
        if (words[i] != "") {
            string next = words[i];
            words[i] = "";
            if (current.back() == next.front()) {
                maxLength = max(maxLength, dfs(words, next, count + next.length() - 1));
            }
            else if (current.front() == next.back()) {
                reverse(next.begin(), next.end());
                maxLength = max(maxLength, dfs(words, next, count + next.length() - 1));
            }
            words[i] = next;
        }
    }
    return maxLength;
}

int main() {
    int n;
    cin >> n;
    vector<string> words(n);
    for (int i = 0; i < n; i++) {
        cin >> words[i];
    }
    string start;
    cin >> start;

    int maxLength = 0;
    for (int i = 0; i < n; i++) {
        if (words[i].front() == start.front()) {
            string current = words[i];
            words[i] = "";
            maxLength = max(maxLength, dfs(words, current, current.length()));
            words[i] = current;
        }
        else if (words[i].back() == start.front()) {
            string current = words[i];
            reverse(current.begin(), current.end());
            words[i] = "";
            maxLength = max(maxLength, dfs(words, current, current.length()));
            words[i] = current;
        }
    }

    cout << maxLength << endl;

    return 0;
}

2023/8/17 13:03
加载中...