前言
传送门 :
顾名思义,不过是多了点东西罢了
思路
双向广搜 无非就是 终点和起点 一起搜索罢了(本质上还是 B F S BFS BFS)
这题 起点是 A A A 终点是 B B B
对于搜索 我们还需要记录两个量 :
- 是否枚举过当前状态
- 当前状态已经走了多少步
我们可以使用
unordered_map<string, int> da, db
来同时记录 步数 和 是否被遍历
对于当前的 B F S BFS BFS
我们需要对于队头元素进行枚举,从每一个下标枚举所有的修改情况
然后我们做普通的 B F S BFS BFS即可
CODE
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
#define unmpsi unordered_map<string,int>
const int N = 10;
string A,B;
string a[N],b[N];
int n;
int extend(queue<string>& q,unmpsi& da,unmpsi& db,string a[],string b[])
{
string t = q.front();
q.pop();
int len = t.size();
for(int i= 0 ;i<len;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;
if(da.count(state))
continue;
da[state] = da[t] +1;
q.push(state);
}
}
}
return 11;
}
int bfs()
{
if(A == B)
return 0;
queue<string> qa,qb;
unmpsi da,db;
qa.push(A),qb.push(B);
da[A] = db[B] = 0 ;
int step = 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;
}
void solve()
{
cin>>A>>B;
while(cin>>a[n]>>b[n]) n++;
int t = bfs();
if(t > 10)
cout<<"NO ANSWER!"<<endl;
else
cout<<t<<endl;
}
int main()
{
ios::sync_with_stdio(false);
solve();
return 0;
}