跳到正文

个人记录

双向广搜 Lv.2

IceAge约 4 分钟
原文
文章信息与版本

文章信息

发布
2021年11月9日
收录
2026年11月25日
更新
2026年11月25日
篇幅
约 4 分钟

版本

  1. v1当前

是一种 BFS\mathrm{BFS} 的优化

一、算法介绍

顾名思义,双向广搜就是从起点和终点同时开始搜。

为什么双向广搜能优化一般的广搜呢?下面这张图很形象地解释了这个问题:

2021-11-09 11-28-52 的屏幕截图.png

如果用普通的广搜,遍历到的区间将是整个蓝色区域;但是如果加上双向广搜,瞬间就降维打击,只剩下蓝色区域了。也就是说双向广搜把 O(kn)O(k^n) 优化成了 O(2×k⌈n2⌉)O(2\times k^{\lceil\frac{n}{2}\rceil}) 的复杂度。

判定无解:如果两边一旦有一边扩展完了,且还未相遇,那么起点和终点一定不连通,无解。

二、实现方式

  1. 直接从起点和终点分别扩展一步;

  2. 小小的优化——每次选择两个队列里面元素较少的一端扩展。

    很显然——比如从起点是指数级别的,从终点是一条路走到黑,那我肯定从终点扩展啊!

应当注意的是,扩展的一步是扩展完整的一层而不是一个点,对应到代码中就是每次扩展要把与队头的 distdist 值相等的点全部扩展一遍,y\mathrm{y} 总就在这里翻了车

代码实现:

C++
// AcWing 190. 字串变换
#include <bits/stdc++.h>
using namespace std;
const int N=10;
int n;
string A,B;
string a[N],b[N];
int expand(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)
    {
        auto t=qa.front();
        qa.pop();
        for (int i=1;i<=n;i++)
            for (int j=0;j<t.size();j++)
                if (t.substr(j,a[i].size())==a[i])
                {
                    auto s=t.substr(0,j)+b[i]+t.substr(j+a[i].size());
                    if (db.count(s))
                        return da[t]+1+db[s];
                    if (da.count(s))
                        continue;
                    da[s]=da[t]+1;
                    qa.push(s);
                }
    }
    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;
    int t,step;
    while (qa.size() && qb.size())
    {
        if (qa.size()<=qb.size())
            t=expand(qa,da,db,a,b);
        else
            t=expand(qb,db,da,b,a);
        if (t<=10)
            return t;
        if (++step==10)
            return 11;
    }
    return 11;
}
int main()
{
    cin>>A>>B;
    while (cin>>a[n+1]>>b[n+1])
        n++;
    int t=bfs();
    if (t>10)
        puts("NO ANSWER!");
    else
        printf("%d\n",t);
    return 0;
}
原文