又是尽力摆脱暴力学缠身的一天
题目链接:https://www.luogu.com.cn/problem/P1032
题目来自洛谷普及+/提高
题目描述
已知有两个字串A,BA,B及一组字串变换的规则(至多66个规则):
A1->B1
A2->B2
规则的含义为:在 A中的子串 A1 可以变换为 B1,A2可以变换为 B2 …。
例如:A=abcd,B=xyz,
变换规则为:
abc→xu,ud→y,y→yz
则此时,A可以经过一系列的变换变为B,其变换的过程为:
abcd→xud→xy→xyz。
共进行了3次变换,使得A变换为B。
输入输出:不码字了。。。。看图
反复分析
广搜模板题一道,没啥好说的,注意一下字符串编译匹配就行了。
实现
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<map>
#define maxn 20
using namespace std;
struct node {
string str;
int step;
};
string a, b;
string org[maxn];
string tra[maxn];
int n=0, ans=0;
map<string, int >ma;
//破译函数
string translate(const string &str, int i, int j) {
string ans="" ;
if(i+org[j].length() > str.length()) {
return ans;
}
for(int k=0; k<org[j].length(); k++){
if(str[i+k]!=org[j][k])
return ans;
}
ans=str.substr(0, i);
ans+=tra[j];
ans+=str.substr(i+org[j].length());
//cout<<ans<<endl;
return ans;
}
//广搜原型
void bfs(){
queue<node>q;
node s;
s.str=a;
s.step=0;
q.push(s);
//开始广搜
while(!q.empty()) {
node u=q.front();
//cout<<u.step<<endl;
q.pop();
if(ma.count(u.str)==1){
continue;
}
//一个方向完成立即结束广搜
if(u.str==b){
ans=u.step;
break;
}
ma[u.str]=1;
string temp;
//字符串任意一个位置尝试搜索
for(int i=0; i<u.str.length(); i++){
//尝试org里面的所有字符串
for(int j=0; j<n; j++){
temp=translate(u.str, i, j);
if(temp!=""){
node v;
v.str=temp;
v.step=u.step+1;
q.push(v);
}
}
}
}
}
int main()
{
cin>>a>>b;
while(cin>>org[n]>>tra[n]){
n++;
}
// cout<<a<<endl<<b<<endl;
// for(int i=0; i<n; i++){
// cout<<org[i]<<"---"<<tra[i]<<endl;
// }
bfs();
if(ans>10 || ans==0)
cout<<"NO ANSWER!";
else
cout<<ans;
return 0;
}