链接:https://www.luogu.org/problemnew/show/P1032
题意:给一个初始字符串和一个目标字符串,然后有最多6个规则,从前一个字符串可以变到后一个字符串。询问初始字符转能否经过这些规则的变换最终变为目标字符串。可以的话输出最小的步数,否则输出“"NO ANSWER!”。
思路:因为规则很少,直接暴力bfs所有可能的状态就好了,然后用一个map来判重。偷点懒,直接用string的find来找字串。
#include<bits/stdc++.h>
using namespace std;
map<string,bool>mp;
string s1,s2;
string t1[6],t2[6];
int tot=0;
struct node
{
string ss;
int step;
node(){}
node(string ss,int step):ss(ss),step(step){}
};
bool ff;
void bfs()
{
queue<node>q;
q.push(node(s1,0));
mp[s1]=true;
while(!q.empty())
{
node now=q.front();
q.pop();
if(now.ss==s2)
{
ff=true;
printf("%d\n",now.step);
return;
}
string nxt;
for(int i=0;i<tot;i++)
{
for(int k=0;k<now.ss.length();k++)
{
nxt="";
int xb=now.ss.find(t1[i],k);
if(xb==-1)continue;
nxt+=now.ss.substr(0,xb);
nxt+=t2[i];
for(int j=xb+t1[i].length();j<now.ss.length();j++)nxt+=now.ss[j];
if(mp[nxt])continue;
mp[nxt]=true;
q.push(node(nxt,now.step+1));
}
}
}
}
int main()
{
cin>>s1>>s2;
while(cin>>t1[tot]>>t2[tot])tot++;
ff=false;
bfs();
if(!ff)printf("NO ANSWER!\n");
return 0;
}