题目链接:https://www.luogu.org/problemnew/show/P1032
思路:使用bfs,遍历所有替换的情况,值得注意的一点是,对同一个字符串可能在不同位置都能替换,一开始没有考虑到这一点
c++代码:
#include <iostream>
#include <queue>
#include <string>
#include <map>
using namespace std;
const int maxn=12;
string fa[maxn],fb[maxn];
map <string,bool> mp;
struct node {
string s;
int x;
};
queue <node>q;
int main() {
string sa,sb;
cin >> sa >> sb;
int cnt=0;
while(cin >>fa[cnt]>>fb[cnt])cnt++;
node a;
a.s=sa;
a.x=0;
q.push(a);
int ans;
bool flag=0;
while(!q.empty()) {
node t=q.front();q.pop();
if(t.s==sb) {
ans=t.x;
flag=1;
break;
}
if(mp.count(t.s))continue;
mp[t.s]=1;
//cout << cnt <<endl;
for(int i=0;i<cnt;i++) {
node tq=t;
while(1) {
int p;
if((p=tq.s.find(fa[i]))!=(int)string::npos){
node tmp=t;
int len=fa[i].length();
tmp.s.erase(p,len);
tmp.s.insert(p,fb[i]);
//if(tmp.s=="procedure")cout << p <<endl;
tmp.x=t.x+1;
q.push(tmp);
tq.s[p]='/';
}
else break;
}
}
}
if(flag&&ans)
cout << ans<< endl;
else cout <<"NO ANSWER!" <<endl;
return 0;
}