P1032 [NOIP2002 提高组] 字串变换 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
方法学自于B19 双向BFS 字串变换_哔哩哔哩_bilibili
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<map>
using namespace std;
#define ll long long
const int N=1010;
int n=0,m;
string A,B;
string a[N],b[N];int check(queue<string>&q,map<string,int>&mpa,map<string,int>&mpb,string a[N],string b[N])
{int lenq=q.size();while(lenq--){string p=q.front();q.pop();for(int i=0;i<n;i++)//枚举规则{for(int j=0;j<p.size();j++){if(p.substr(j,a[i].size())==a[i])//符合变化规则{string str=p.substr(0,j)+b[i]+p.substr(j+a[i].size());//变化字符if(mpa.count(str))//正向搜索的队列已有此字符continue;if(mpb.count(str))//反向搜索的队列中有此字符,说明搜索已经重合return mpa[p]+mpb[str]+1;mpa[str]=mpa[p]+1;//搜索次数加1q.push(str);//入队}}}}return 11;
}
int bfs()
{queue<string>qa,qb;map<string,int>mpa,mpb;//计数qa.push(A),qb.push(B);mpa[A]=0,mpb[B]=0;int step=10,t;while(step--){if(qa.size()<=qb.size())//队列长度小的进行搜索t=check(qa,mpa,mpb,a,b);elset=check(qb,mpb,mpa,b,a);if(t<=10)return t;} return 11;
}
int main()
{cin>>A>>B;while(cin>>a[n]>>b[n])//规则输入n++;if(A==B)//特判一下{printf("0\n");return 0;}if(bfs()==11)puts("NO ANSWER!");elseprintf("%d\n",bfs());return 0;
}