洛谷 P1019 单词接龙

深搜 DFS

解释在注释里都有
不多说什么了

//P1019 单词接龙
//2017.4.26

#include 
#include 
using namespace std;

const int MAXN = 24;
int n, ans, book[MAXN], connect[MAXN][MAXN];
string word[MAXN];
char start;

int check(int x, int y){   //将x接在y后
    int l1 = word[x].size(), l2 = word[y].size();
    bool flag;
    for (int k = 1; k < min(l1, l2); k++){
        flag = true;
        int i = l1 - k, j = 0;
        while (i < l1 && j < k){
            if (word[x][i] != word[y][j]){
                flag = false;
                break;
            }
            i++, j++;
        }
        if (flag) return k;
    }
    return 0;
}

void dfs(int pre, int len){   //当前构成的“龙”的结尾字符串word[pre] 当前构成的字符串的长度
    ans = max(ans, len);
    for (int i = 1; i <= n; i++){
        if (book[i] > 1) continue;   //每个单词都最多在“龙”中出现两次
        if (connect[pre][i] == 0) continue;
        book[i]++;
//      cout << len << " + " << word[pre] << " + " << word[i] << " = " << len + word[i].size() - connect[pre][i] << endl;
        dfs(i, len + word[i].size() - connect[pre][i]);
        book[i]--; 
    }
}

int main(){
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        cin >> word[i];
    cin >> start;

    //预处理:任意两个单词是否可连接 若可则返回连接部分的长度 
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++){
            connect[i][j] = check(i, j);
//          cout << word[i] << " - " << word[j] << " : " << connect[i][j] << endl;
        }

    for (int i = 1; i <= n; i++){
        if (word[i][0] == start){   //每次从可以作为起始的单词开始搜 
            book[i]++;
            dfs(i, word[i].size());
            book[i]--;
        }
    }

    cout << ans;

    return 0;
}

O(∩_∩)O哈!

你可能感兴趣的:(洛谷)