代码:
#include <bits/stdc++.h>
using namespace std;
string a, b;
string A[10], B[10];
int cnt = 0;
struct node {
string s;
int t;
};
queue <node> q;
map <string, int> mp;
void bfs () {
q.push ((node){a, 0});
while (q.size()) {
mp[q.front().s] ++;
if (q.front().s == b) {
if (q.front().t > 10) cout << "NO ANSWER!\n";
else cout << q.front().t << endl;
return ;
}
for (int i = 1; i <= cnt; i ++) {
string tt = q.front().s;
int p = 0;
int c = 0;
for (int j = 0; j < q.front().s.size(); j ++) {
for (int k = j; k < q.front().s.size() && k - j + 1 <= A[i].size(); k ++) {
if (q.front().s[k] == A[i][p]) {
++ p;
} else {
break ;
}
if (p == A[i].size()) {
tt.replace(k - p + 1, p, B[i]);
if (mp[tt] == 0) q.push ((node){tt, q.front().t + (++ c)});
}
}
p = 0;
}
}
q.pop();
}
cout << "NO ANSWER!\n";
}
int main() {
ios :: sync_with_stdio();
cin.tie(0);
cout.tie(0);
cin >> a >> b;
string s1, s2;
while (cin >> s1) {
cin >> s2;
A[++ cnt] = s1;
B[cnt] = s2;
}
bfs ();
return 0;
}
测试记录
请各位大佬帮忙