单词接龙是一个与我们经常玩的成语接龙相类似的游戏。
现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”,每个单词最多被使用两次。
在两个单词相连时,其重合部分合为一部分,例如 beast 和 astonish ,如果接成一条龙则变为 beastonish。
我们可以任意选择重合部分的长度,但其长度必须大于等于1,且严格小于两个串的长度,例如 at 和 atide 间不能相连。
输入格式
输入的第一行为一个单独的整数 nn 表示单词数,以下 nn 行每行有一个单词(只含有大写或小写字母,长度不超过20),输入的最后一行为一个单个字符,表示“龙”开头的字母。
你可以假定以此字母开头的“龙”一定存在。
输出格式
数据范围
输入样例:
5 at touch cheat choose tact a
输出样例:
提示
连成的“龙”为 atoucheatactactouchoose。
#include <iostream>#include <cstring>#include <algorithm>using namespace std;const int N = 21;int n;string word[N];int g[N][N]; //g[i][j] = k 表示i单词的后缀k长度与 j单词的前缀k长度重合int used[N]; //一个单词只能用两次int res;//last表示连接的最后一个单词下标void dfs(string dragon, int last) {//每次先更新resres = max((int)dragon.size(), res);used[last] ++;for (int i = 0; i < n; ++i) {if (used[i] < 2 && g[last][i]) //当使用次数小于2 并且能重合长度大于1dfs(dragon + word[i].substr(g[last][i]), i); //截取word[i]后半段,传入i}used[last] --;}int main() {cin >> n;for (int i = 0; i < n; ++i) cin >> word[i];char start;cin >> start;//预处理单词匹配重合问题for (int i = 0; i < n; ++i)for (int j = 0; j < n; ++j) {string a = word[i], b = word[j];//长度大于一且小于两个单词短的长度for (int k = 1; k < min(a.size(), b.size()); ++k) {if (a.substr(a.size() - k, k) == b.substr(0, k)) {g[i][j] = k;break; //重合的部分越短越好,这样连起来的词才会越来越长}}}for (int i = 0; i < n; ++i)if (word[i][0] == start)dfs(word[i], i);cout << res << endl;return 0;}
