190. 字串变换
已知有两个字串 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!。
输入样例:
abcd xyz
abc xu
ud y
y yz
输出样例:
3
解题思路
长度为20,每个点都有可能扩展6个,因此有120个,并且最长10步,因此最长的时间可能是120^10,因此必须采用双向广搜,一般应用于最小步数模型里面(这个里面的搜索状态可能会很大,因此采用,也就是优化)。
代码一:这个代码有问题,在扩展extend
只是扩展了一个节点,并不是扩展了一层节点,其次,A==B就不需要规则变动,直接return 0,因此需要修改,具体见代码二
#include<iostream>
#include<cstring>
#include<algorithm>
#include<unordered_map>
#include<queue>
using namespace std;
const int N=7;
int n;
string a[N],b[N];//存储规则
int extend(queue<string>& q,unordered_map<string,int>& da,unordered_map<string,int>& db,string a[],string b[]){
string t=q.front();
q.pop();
for(int i=0;i<t.size();i++)
for(int j=0;j<n;j++){
if(t.substr(i,a[j].size())==a[j]){
string state = t.substr(0,i)+b[j]+t.substr(i+a[j].size());
if(db.count(state)) return da[t]+1+db[state];
if(da.count(state)) continue;//如果在a方向上扩展过了,跳过
da[state]=da[t]+1;//两个方向都不在了,一般情况
q.push(state);
}
}
return 11;
}
int bfs(string A,string B){
queue<string> qa,qb;//双向队列,qa从A搜索,qb从B搜索
unordered_map<string,int> da,db;//存储不同点之间到A、B两点的距离
if(A==B) return 0;//相等就不需要规则变换
qa.push(A),da[A]=0;
qb.push(B),db[B]=0;
while(qa.size()&&qb.size()){//两个方向必须有值,如果某个方向上没有值了,那就说明该扩展不连通
int t;
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;
}
return 11;
}
int main(){
string A,B;
cin>>A>>B;
while(cin>>a[n]>>b[n]) n++;
int step=bfs(A,B);
if(step>10) puts("NO ANSWER!");
else printf("%d\n",step);
return 0;
}
代码二
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <unordered_map>
using namespace std;
const int N = 6;
int n;
string A, B;
string a[N], b[N];
int extend(queue<string>& q, unordered_map<string, int>&da, unordered_map<string, int>& db,
string a[N], string b[N])
{
int d = da[q.front()];
while (q.size() && da[q.front()] == d)
{
auto t = q.front();
q.pop();
for (int i = 0; i < n; i ++ )
for (int j = 0; j < t.size(); j ++ )
if (t.substr(j, a[i].size()) == a[i])
{
string r = t.substr(0, j) + b[i] + t.substr(j + a[i].size());
if (db.count(r)) return da[t] + db[r] + 1;
if (da.count(r)) continue;
da[r] = da[t] + 1;
q.push(r);
}
}
return 11;
}
int bfs()
{
if (A == B) return 0;
queue<string> qa, qb;
unordered_map<string, int> da, db;
qa.push(A), qb.push(B);
da[A] = db[B] = 0;
while (qa.size() && qb.size())
{
int t;
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;
}
return 11;
}
int main()
{
cin >> A >> B;
while (cin >> a[n] >> b[n]) n ++ ;
int t = bfs();
if (t >10) puts("NO ANSWER!");
else cout << t << endl;
return 0;
}