アイデア:最小ステップ数モデルはBFSで記述されていますが、部分文字列変換はkタイプである可能性があるため、10ステップ、つまりスペースk ^ 10はメモリをバーストし、双方向検索最適化を使用します。AとBの変更同時に、私たちは同じですAとBが互いに到達できるポイントがあるかどうかを確認します。ある場合は、Aの距離+ Bの距離+1です。ない場合は、検索に参加します。このレイヤーで検索が完了するまで。2つのキューを同じサイズに保ちます。Aが小さい場合は、Aを検索し、その逆も同様です。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e5+5;
const int inf=0x7f7f7f7f;
int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
ll lcm(ll a,ll b)
{
return a*(b/gcd(a,b));
}
template <class T>
void read(T &x)
{
char c;
bool op = 0;
while(c = getchar(), c < '0' || c > '9')
if(c == '-')
op = 1;
x = c - '0';
while(c = getchar(), c >= '0' && c <= '9')
x = x * 10 + c - '0';
if(op)
x = -x;
}
template <class T>
void write(T x)
{
if(x < 0)
x = -x, putchar('-');
if(x >= 10)
write(x / 10);
putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
ll res=1%p;
while(b)
{
if(b&1)
res=res*a%p;
a=1ll*a*a%p;
b>>=1;
}
return res;
}
string a[10],b[10];
string A,B;
int n;
int chang(unordered_map<string,int>& da,unordered_map<string,int>& db,queue<string>& q,string a[10],string b[10])
{
int dis=da[q.front()];
while(q.size()&&dis==da[q.front()])
{
auto now=q.front();
q.pop();
for(int i=0;i<n;i++)
{
for(int j=0;j<now.size();j++)
{
if(now.substr(j,a[i].size())==a[i])
{
string t=now.substr(0,j)+b[i]+now.substr(j+a[i].size());
if(db.count(t)) return da[now]+db[t]+1;
if(da.count(t))continue;
da[t]=da[now]+1;
q.push(t);
}
}
}
}
return 11;
}
int bfs()
{
unordered_map<string,int> da,db;
queue<string> qa,qb;
qa.push(A);
qb.push(B);
da[A]=0;
db[B]=0;
int step=0;
while(qa.size()&&qb.size())
{
int res;
if(qa.size()<qb.size()) res=chang(da,db,qa,a,b);
else res=chang(db,da,qb,b,a);
if(res<=10) return res;
if(++step>10)return -1;
}
return -1;
}
int main()
{
cin>>A>>B;
while(cin>>a[n]>>b[n]) n++;
int ans=bfs();
if(ans==-1) cout<<"NO ANSWER!"<<endl;
else cout<<ans<<endl;
return 0;
}