分析:这道题WA点很多。。并且需要判重。
弱鸡看了大佬题解才get了string类的replace()函数用法。
str.replace(position,length,the other string);
一个WA了好几次才意识到的地方 :在主串中找到第一个与子串匹配的位置后,应该继续往下查找其他可匹配位置,直到主串结束。
代码
#include<bits/stdc++.h>
using namespace std;
vector<pair<string,string> >st;
map<string,int>vis;
string A,B;
typedef struct node
{
string s;
int num=0;
}node;
int bfs()
{
queue<node>q;
node d;
d.s=A,d.num=0;
q.push(d);
while(!q.empty())
{
node f=q.front();
q.pop();
string x=f.s;
if(f.num>10) return 0;
for(int i=0; i<st.size(); i++)
{
int k=x.find(st[i].first);
if(k!=-1)
{
for(k=x.find(st[i].first); k<x.length(); k=x.find(st[i].first,k+1))
{
string ss=x;
ss.replace(k,st[i].first.length(),st[i].second);
if(ss==B) return f.num+1;
if(!vis[ss]) //判重
{
vis[ss]=1;
node g;
g.s=ss,g.num=f.num+1;
q.push(g);
}
}
}
}
}
return 0;
}
int main()
{
cin>>A>>B;
string p,q;
while(cin>>p>>q)
st.push_back(make_pair(p,q));
int k=bfs();
if(!k) cout<<"NO ANSWER!\n";
else cout<<k<<endl;
return 0;
}