#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
struct node {
string from, to;
};
struct status {
string s;
int type;
int step;
};
vector<node> rule;
string st, ed;
queue<status> q;
int ans = 11;
unordered_map<string, int> vis[2];
void bfs(string st, string ed) {
q.push({st, 0, 0});
q.push({ed, 1, 0});
while (!q.empty()) {
auto [s, t, step] = q.front();
q.pop();
if (step >= 10 || step >= ans) continue;
if (vis[t ^ 1].find(s) != vis[t ^ 1].end()) {
ans = min(ans, vis[t ^ 1][s] + step);
continue;
}
if (vis[t].find(s) != vis[t].end()) {
continue;
}
vis[t][s] = step;
for (auto &[from, to] : rule) {
if (t == 0) {
string tmp = s;
string ns;
while (true) {
ns = s;
auto res = tmp.find(from);
if (res != string::npos) {
ns.replace(res, from.size(), to);
if (vis[t].find(ns) == vis[t].end()) {
q.push({ns, t, step + 1});
}
tmp[res] = '-';
} else {
break;
}
}
} else {
string tmp = s;
string ns;
while (true) {
ns = s;
auto res = tmp.find(to);
if (res != string::npos) {
ns.replace(res, to.size(), from);
if (vis[t].find(ns) == vis[t].end()) {
q.push({ns, t, step + 1});
}
tmp[res] = '-';
} else {
break;
}
}
}
}
}
}
signed main() {
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
cin >> st >> ed;
string from, to;
while (cin >> from) {
cin >> to;
rule.push_back({from, to});
}
bfs(st, ed);
if (ans > 10) {
cout << "NO ANSWER!" << endl;
exit(0);
}
cout << ans << endl;
return 0;
}
https://www.luogu.com.cn/record/222871081