每一个字符串可能存在可以使用同一种替换规则多次比如
初始串: aaa
变换规则:a→b
这种情况一个串可以三次使用变换规则,所以当我们find初始串是否存在可变换的子串时,每次查找一次将find()查找起始位置更新即可
这里有一个坑点:在我们需要改变原始字符串是,不能用替换,否则原始字符串改变会影响其他变换规则的变换,这里我们只能使用拼接压入队列中
#include<cstdio>
#include<string>
#include<map>
#include<iostream>
#include<queue>
#include<map>
using namespace std;
map<string,string>mp;
int main(){
string A,B;
string x[10],y[10];//记录起始,与结束的状态
cin>>A>>B;
int n=1;
while(cin>>x[n]>>y[n]){//将规则存入数组当中
n++;
}
n--;
queue<string>A0;//起始状态压入队列
queue<int>p;
A0.push(A);
p.push(0);
while(!A0.empty()){
//cout<<A0.front()<<p.front()<<endl;
if(A0.front()==B){//当找到时输出
cout<<p.front();
return 0;
}
if(p.front()==10){//当次数大于10次直接弹出不需要继续搜索
A0.pop();
p.pop();
}
string t=A0.front();;
if(mp.count(t)){//检测当前字符串有没有出现过
A0.pop();
p.pop();
continue;
}
mp[t]=1;
for(int i=1;i<=n;i++){//依次按规则作出几种变换
int L=0;
while(t.find(x[i],L)!=-1){//如果找得到
L=t.find(x[i],L);
//A0.push(t.replace(L,x[i].length(),y[i]));
A0.push(t.substr(0,L)+y[i]+t.substr(L+x[i].length()));//改变字符串压入队里中
p.push(p.front()+1);//次数加一
//cout<<t<<" "<<p.front()<<endl;
L++;
}
}
A0.pop();//当前字符串完成了任务
p.pop();
}
printf("NO ANSWER!\n");
return 0;
}
我还有一种写法,将规则存成映射关系,但是只能AC百分之60的数据
希望有人指正
#include<cstdio>
#include<string>
#include<map>
#include<iostream>
#include<queue>
#include<set>
using namespace std;
int main(){
string A,B;
string x,y;
cin>>A>>B;
map<string,string>s;
set<string>pp;
while(cin>>x>>y){
s[x]=y;
}
queue<string>A0;
queue<int>p;
A0.push(A);
p.push(0);
while(!A0.empty()){
if(A0.front()==B){//当找到时输出
cout<<p.front();
return 0;
}
if(p.front()>=10){
A0.pop();
p.pop();
}
int kai,len=0;
string t=A0.front();
if(pp.count(t)){
A0.pop();
p.pop();
continue;
}
pp.insert(t);
map<string,string>::iterator it;
for(it=s.begin();it!=s.end();it++){
if(t.find(it->first,0)!=-1){
kai=t.find(it->first,0);
len=it->first.size();
//t.replace(kai,len,it->second);
//cout << kai << len <<it->first<<" "<< it->second << endl;
A0.push(t.substr(0,kai)+it->second+t.substr(kai+len));
p.push(p.front()+1);
}
}
A0.pop();
p.pop();
}
printf("NO ANSWER!\n");
return 0;
}