#include<bits/stdc++.h>
using namespace std;
const int N=200;
string a[N],b[N];
string _state,_end;
int n;
map<string,int>mp1,mp2;
int main()
{
cin>>_state>>_end;
while(cin>>a[n]>>b[n]) n++;
mp1[_state]=1,mp2[_end]=1;
queue<string>q1,q2;
q1.push(_state);
q2.push(_end);
for(int step=1;step<=5;step++)
{
while(q1.size())
{
string top1=q1.front();
q1.pop();
for(int i=0;i<n;i++){
for(int j=0;j<top1.length();j++)
{
if(a[i] == top1.substr(j,a[i].length()))
{
string _next=top1;
_next.replace(j,a[i].length(),b[i]);
if(mp1[_next]) continue;
if(mp2[_next])
{
cout<<mp1[top1]-1+mp2[_next]<<endl;
return 0;
}
mp1[_next]=mp1[top1]+1;
q1.push(_next);
}
}
}
}
while(q2.size())
{
string top1=q2.front();
q2.pop();
for(int i=0;i<n;i++){
for(int j=0;j<top1.length();j++)
{
if(b[i] == top1.substr(j,b[i].length()))
{
string _next=top1;
_next.replace(j,b[i].length(),a[i]);
if(mp2[_next]) continue;
if(mp1[_next])
{
cout<<mp2[top1]-1+mp1[_next]<<endl;
return 0;
}
mp2[_next]=mp2[top1]+1;
q2.push(_next);
}
}
}
}
}
puts("NO ANSWER!");
return 0;
}
字串变换
最新推荐文章于 2024-06-30 08:52:24 发布