A145.单词接龙
2024-02-25 21:26:34
发布于:江苏
26阅读
0回复
0点赞
#include <bits/stdc++.h>
using namespace std;
vector<string> words;
int visited[25];
string head;
int n;
int ans;
bool modify(string& head, string& tail, string& extra) {
int i;
int hsize = strlen(head.c_str());
int tsize = strlen(tail.c_str());
for (i = 1; i < min(hsize, tsize); i++) {
if (head.substr(hsize - i, hsize) == tail.substr(0, i)) {
break;
}
}
if (i == min(hsize, tsize)) {
return false;
} else {
extra = tail.substr(i, tsize);
head = head + extra;
return true;
}
}
void unmodify(string& head, string& tail, string& extra) {
head = head.substr(0, head.length() - extra.length());
}
void dfs(string head) {
for (int i = 0; i < n; i++) {
if (visited[i] < 2) {
string tail = words[i];
if (head.length() == 1) {
if (tail[0] == head[0]) {
head = tail;
if (head.length() >= ans) {
ans = head.length();
}
visited[i]++;
dfs(head);
visited[i]--;
head = tail[0];
}
} else if (head.length() > 1) {
string extra = "";
if (modify(head, tail, extra)) {
if (head.length() >= ans) {
ans = head.length();
}
visited[i]++;
dfs(head);
visited[i]--;
unmodify(head, tail, extra);
}
}
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
string word;
cin >> word;
words.push_back(word);
}
cin >> head;
dfs(head);
cout << ans;
return 0;
}
这里空空如也
有帮助,赞一个