题目描述
已知有两个字串 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=aa B=bb
变换规则为:a → b此时,不能将两个 a 在一步中全部转换为 b,而应当分两步完成。
输入格式
输入格式如下:
A
B
A1
B1
A2
B2
第一行是两个给定的字符串 A 和 B。
接下来若干行,每行描述一组字串变换的规则。所有字符串长度的上限为 20。
输出格式
若在 10 步(包含 10 步)以内能将 A 变换为 B ,则输出最少的变换步数;否则输出 NO ANSWER!。
样例
in:
abcd xyz
abc xu
ud y
y yz
out:
3
算法
bfs双向广搜
从起点和终点双向搜索,返回两端路径和
时间复杂度
O ( ( L N ) 5 ) O((LN)5) O((LN)5)
代码
#include<bits/stdc++.h>
using namespace std;
string a[10],b[10];
string A,B;
int n;
int extend(queue<string> &qa,unordered_map<string,int> &da,unordered_map<string,int> &db,string a[],string b[]) {
int d = da[qa.front()];
while(qa.size()&&da[qa.front()] == d) {//把这一层搜完
string te = qa.front();
qa.pop();
for(int j = 0; j <n; ++j){
for(int i = 0 ; i< te.size(); ++i) {
if(te.substr(i,a[j].size()) == a[j]) {
string tee = te.substr(0,i)+b[j] + te.substr(i+a[j].size());
if(db.count(tee)) return da[te] + 1+ db[tee];
if(da.count(tee)) continue;
da[tee] = da[te] + 1;
qa.push(tee);
}
}
}
}
return 11;
}
int bfs() {
if(A == B) return 0;
unordered_map<string,int> da,db;
queue<string> qa,qb;
qa.push(A);
qb.push(B);
da[A] = 0;
db[B] = 0;
int p = 0;
while(qa.size()&&qb.size()) {
int t = 0;
if(qa.size()<=qb.size()) t = extend(qa,da,db,a,b);
else t = extend(qb,db,da,b,a);
if(t<=10) return t;
if(++p == 10) return 11;
}
return 11;
}
int main() {
cin>>A>>B;
while(cin>>a[n],cin>>b[n]) n++;
int t = bfs();
if(t>10) cout<<"NO ANSWER!\n";
else cout<<t;
}