已知有两个字串 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’
共进行了三次变换,使得 A 变换为B。
输入格式
输入格式如下:
A B
A1 B1
A2 B2 |-> 变换规则
… … /
所有字符串长度的上限为 20。
输出格式
若在 10 步(包含 10步)以内能将 A 变换为 B ,则输出最少的变换步数;否则输出”NO ANSWER!”
输入样例:
abcd xyz
abc xu
ud y
y yz
输出样例:
3
分析,如果直接从一端进行广搜,则时间复杂度最大为O(610),非常的大,会tle,或mle
解决办法:双向bfs,从两端进行bfs搜索,当搜索到重复元素是停止,最坏时间复杂度为O(6^5)。
优化:每次选择元素中数量较少的方向进行扩展
#include<iostream>
#include<queue>
#include<cstring>
#include<string>
#include<map>
#include<algorithm>
using namespace std;
const int N = 10;
string a[N],b[N];
string starts,endss;//初始串和目标串
int n = 0;
map<string,int> m1;
map<string,int> m2;
int extend(queue<string> &q,map<string,int> &m1,map<string,int> &m2,string a[],string b[]){
string s = q.front();q.pop();
for(int i = 1;i<n;i++){
//n种变换规则
int t = s.find(a[i],0);
while(t!=-1){
string s1 = s;
s1.replace(t,a[i].size(),b[i]);
t = s.find(a[i],t+1);
//寻找是否相遇
if(m2.count(s1) == 1){
return m2[s1]+m1[s]+1;
}
if(m1.count(s1) == 1) continue;
m1[s1] = m1[s]+1;
q.push(s1);
// cout<<s1<<" "<<m1[s1]<<" 数量"<<endl;
if(m1[s1]>10) return -1;
}
}
return 0;
}
int bfs(){
queue<string> q1;
queue<string> q2;
q1.push(starts);q2.push(endss);
m1[starts] = 0;m2[endss] = 0;
while(!q1.empty() && !q2.empty()){
int t ;
//哪个队列中的元素少扩展哪个
if(q1.size() < q2.size()){
//正向扩展
t = extend(q1,m1,m2,a,b);
}else{
t = extend(q2,m2,m1,b,a);
}
if(t == 0)continue;
if(t == -1) return -1;
if(t>0) return t;
}
return -1;
}
int main(){
int i,j;
cin>>starts>>endss;
n = 0;
while(cin>>a[++n]){
cin>>b[n];
}
int t = bfs();
if(t == -1) cout<<"NO ANSWER!"<<endl;
else
cout<<t<<endl;
return 0;
}