题目描述 Description
已知有两个字串 A
,
B
, B
,B 及一组字串变换的规则(至多6个规则):
A1$ -> B1$
A2$ -> B2$
规则的含义为:在 A$中的子串 A1$ 可以变换为 B1
、
A
2
、A2
、A2 可以变换为 B2$ …。
例如:A
=
′
a
b
c
d
′
B
='abcd' B
=′abcd′ B=’xyz’
变换规则为:
‘abc’->‘xu’ ‘ud’->‘y’ ‘y’->‘yz’
则此时,A$ 可以经过一系列的变换变为 B$,其变换的过程为:
‘abcd’->‘xud’->‘xy’->‘xyz’
共进行了三次变换,使得 A$ 变换为B$。
输入描述 Input Description
输入格式如下:
A$ B$
A1$ B1$
A2$ B2$ |-> 变换规则
… … /
所有字符串长度的上限为 20。
输出描述 Output Description
若在 10 步(包含 10步)以内能将 A$ 变换为 B$ ,则输出最少的变换步数;否则输出"NO ANSWER!"
样例输入 Sample Input
abcd xyz
abc xu
ud y
y yz
样例输出 Sample Output
3
#include<iostream>
#include<stdlib.h>
#include<cmath>
#include<algorithm>
#include<vector>
#include<string.h>
#include<cstring>
#include<stdio.h>
#include<queue>
using namespace std;
/*int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};*/
int step;
int len=0;
int flag=0;
struct Map
{
string k;
int stp;
};
int myfind(string a,string b)
{
for(int i=0;i<a.length();i++)
{
for(int j=0;j<b.length();j++)
{
if(a[i+j]!=b[j])
{
break;
}
if(j==b.length()-1)
{
return i;
}
}
}
return -1;
}
string str1[100],str2[100],str[2];
void bfs()
{
queue<Map> q;
Map temp;
temp.k=str[0];
temp.stp=step;
q.push(temp);
if(str[0]==str[1])
{
cout<<"0"<<endl;
return;
}
while(!q.empty())
{
if(flag>1000000)
{
cout<<"NO ANSWER!"<<endl;
return;
}
// cout<<"k2"<<endl;
for(int i=0;i<len;i++)
{
Map temp;
temp=q.front();
q.pop();
int z=myfind(temp.k,str1[i]);
string end;
if( z!=-1)
{
flag=1;
end= temp.k.substr(z+str1[i].length());
// cout<<"out end"<<" "<<end<<endl;
string st= temp.k.substr(0,temp.k.length()-str1[i].length()-end.length());
temp.k=st+str2[i]+end;
//
// cout<<"out"<<" "<<temp.k<<endl;
if(temp.k==str[1])
{
cout<<temp.stp+1<<endl;
return;
}
temp.stp++;
q.push(temp);
if(temp.stp>=10)
{
cout<<"NO ANSWER!"<<endl;
return;
}
}
else
{
q.push(temp);
}
//cout<<"k"<<endl;
}
flag++;
}
}
int main()
{
cin>>str[0]>>str[1];
while(cin>>str1[len++])
{
cin>>str2[len-1];
}
bfs();
return 0;
}