题目描述
已知有两个字串A,B及一组字串变换的规则(至多6个规则):
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。
输入输出格式
输入格式:
输入格式如下:
A B
A1 B1
A2 B2 |-> 变换规则
所有字符串长度的上限为20。
输出格式:
输出至屏幕。格式如下:
若在10步(包含10步)以内能将A变换为B,则输出最少的变换步数;否则输出"NO ANSWER!"
输入输出样例
输入样例#1:
abcd xyz
abc xu
ud y
y yz
输出样例#1:
3
解释:很简单的bfs,但要记得排除重复状态。否则就TLE
// luogu-judger-enable-o2
#include<iostream>
#include<map>
#include<string>
#include<vector>
#include<queue>
#define N 1005
using namespace std;
map<string,vector<string> >G;
map<string,int> H;
string a,b;
struct node{
string str;
int num;
};
queue<node> q;
int ret=999;
int temp=999;
int main(){
ios::sync_with_stdio(false);
cin>>a>>b;
string tempa,tempb;
while(cin>>tempa>>tempb) G[tempa].push_back(tempb);
q.push(node{a,0});
while(q.size()){
node temp=q.front();q.pop();
if(H[temp.str]) continue;
H[temp.str]=1;
if(temp.num>10) break;
if(temp.str==b){
ret=temp.num;
break;
}
int len=temp.str.size();
string ftmp="";
for(int i=0;i<len;i++){
for(int j=i;j<len;j++){
tmp+=temp.str[j];
int size=G[tmp].size();
for(int k=0;k<size;k++){
q.push(node{ftmp+G[tmp][k]+temp.str.substr(j+1,len-j),temp.num+1});
}
}
ftmp+=temp.str[i];
}
}
if(ret!=999) cout<<ret<<endl;
else cout<<"NO ANSWER!"<<endl;
return 0;
}