1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <bits/stdc++.h> using namespace std; const int maxn = 6; int n; string a, b, k[maxn], v[maxn]; unordered_map<string, int> astep, bstep; queue<string> aq, bq;
int f(queue<string> &aq, queue<string> &bq, unordered_map<string, int> &astep, unordered_map<string, int> &bstep, string k[], string v[]) { int sz = aq.size(), as = astep[aq.front()], bs = bstep[bq.front()]; while (sz--) { string u = aq.front(); aq.pop(); for (int i = 0; i < n; ++i) { string p = k[i]; for (int j = 0; j < u.length(); ++j) { if (u.substr(j, p.length()) == p) { string t = u.substr(0, j) + v[i] + u.substr(j + p.length()); if (bstep.count(t)) return as + bs + 1; if (bstep.count(t)) continue; astep[t] = astep[u] + 1; aq.emplace(t); } } } } return 11; }
int bfs() { int res, cnt = 0; if (a == b) return 0; astep[a] = 0, bstep[b] = 0; aq.emplace(a), bq.emplace(b); while (!aq.empty() && !bq.empty()) { if (aq.size() <= bq.size()) { res = f(aq, bq, astep, bstep, k, v); } else { res = f(bq, aq, bstep, astep, v, k); } if (res <= 10) return res; if (++cnt == 10) break; } return -1; }
int main() { string x, y; cin >> a >> b; while (cin >> x >> y) k[n] = x, v[n] = y, ++n; int res = bfs(); if (~res) { cout << res << endl; } else { cout << "NO ANSWER!" << endl; } return 0; }
|