题目 链接
题目大意
给出一个原始串和一个终止串,求最少需要转移几步。
实际上这就跟走迷宫差不多,而却权重是1的,暴力走就行,加上map优化会快很多,实际上不加的话有可能会T。
参考代码
#include <bits/stdc++.h>
using namespace std;
const int N = 2E2 + 10;
int n;
string a[N];
int ans = 0;
int main() {
// freopen("in.txt", "r", stdin);
string a, b;
cin >> a >> b;
int cnt = 0;
vector <pair<string, string>> v;
string a1, b1;
while (cin >> a1 >> b1) {
v.push_back({ a1,b1 });
}
map<string, int> m;
queue<pair<string, int>> q;
q.push({ a,1 });
int ans = -1;
while (ans < 0 && q.size()) {
auto x = q.front();
q.pop();
if (x.second > 10) break;
for (int i = 0; i < v.size(); i++) {
string t = x.first;
string &a1 = v[i].first;
string &b1 = v[i].second;
int pos = -1;
while ((pos = t.find(a1, pos + 1)) >= 0) {
string h = t.substr(0, pos) + b1 + t.substr(pos + a1.length(), t.length() - pos - a1.length());
if (h == b) {
ans = x.second;
break;
}
if (m[h]) continue;
m[h]++;
q.push({ h,x.second + 1 });
}
}
}
if (ans < 0) cout << "NO ANSWER!" << endl;
else cout << ans << endl;
return 0;
}