代码:
#include <bits/stdc++.h>
using namespace std;
string a, b, a1[10], b1[10];
int l;
struct Person {
int d;
string s;
};
queue<Person> q;
unordered_map<string, int> mp;
void solve() {
q.push((Person){ 0, a });
while (!q.empty()) {
Person v = q.front();
q.pop();
string s = v.s;
int d = v.d;
if(mp[s]) {
continue;
}
if (s == b && d <= 10) {
cout << d;
exit(0);
}
if (d > 10) {
cout << "NO ANSWER!\n";
exit(0);
}
mp[s] = 1;
for (int i = 1; i <= l; ++i) {
int num = s.find(a1[i], 0);
while (num != -1) {
string s1 = s;
s1.replace(num, a1[i].size(), b1[i]);
q.push((Person){ d + 1, s1 });
num = s1.find(a1[i], num + 1);
}
}
}
}
int main() {
cin >> a >> b;
int tmp = 1;
while (cin >> a1[tmp] >> b1[tmp++])
;
l = tmp - 1;
solve();
cout << "NO ANSWER!";
return 0;
}
报replace越界了,萌新求问。