题目信息
解题思路:BFS
- 每次字符串入队找可以执行的操作(看一下有没有可以修改的串)。
- 修改后入队,记录修改次数。
tips:每次找处理完后要继续找这个字符串后是否有可以修改的子串。
代码实现
#include <bits/stdc++.h>
using namespace std;
string a, b;
string A[7], B[7];
struct node {
// 当前字符串
string pre;
// 以修改次数
int s;
} q[2000005];
int main() {
cin >> a >> b;
int n = 1;
while (cin >> A[n] >> B[n]) {
++n;
}
--n;
int l = 0, r = 1;
q[r].pre = a;
q[r].s = 0;
while (l < r) {
// 次数 > 10,输出无解。
if (q[++l].s > 10) {
cout << "NO ANSWER!\n";
return 0;
}
for (int i = 1; i <= n; ++i) {
int pos = q[l].pre.find(A[i], 0);
// 找可修改子串
while (true) {
if (pos == -1) {
break;
} else {
q[++r].pre = q[l].pre;
q[r].s = q[l].s + 1;
q[r].pre.replace(pos, A[i].size(), B[i]);
if (q[r].pre == b) {
cout << q[r].s;
return 0;
}
pos = q[l].pre.find(A[i], pos + 1);
}
}
}
}
return 0;
}