[Acwing] 190. 字串变换 双向广搜

前言

传送门 :
顾名思义,不过是多了点东西罢了

思路

双向广搜 无非就是 终点和起点 一起搜索罢了(本质上还是 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值