迭代加深搜索

· · 算法·理论

壹、基础搜索

实在无话可说,简单

贰、迭代加深搜索

定义

迭代加深(IDDFS)是一种 每次限制搜索深度的深度优先搜索。

分析

迭代加深搜索的本质还是深度优先搜索,只不过在搜索的同时带上了一个深度 depth,当 depth 达到设定的深度时就返回,一般用于找最优解。

如果一次搜索没有找到合法的解,就让设定的深度+1,重新从根开始。

既然是为了找最优解,为什么不用广搜呢?我们知道 BFS 的基础是一个队列,队列的空间复杂度很大,当状态比较多或者单个状态比较大时,使用队列的 BFS 就显出了劣势。事实上,迭代加深就类似于用 DFS 方式实现的 BFS,它的空间复杂度相对较小。

当搜索树的分支比较多时,每增加一层的搜索复杂度会出现指数级爆炸式增长,这时前面重复进行的部分所带来的复杂度几乎可以忽略,这也就是为什么迭代加深是可以近似看成 BFS 的。

过程

首先设定一个较小的深度作为全局变量,进行 DFS。每进入一次 DFS,将当前深度(depth)加一,当发现 depth 大于设定的深度 max_depth 就返回。如果在搜索的途中发现了答案就可以回溯,同时在回溯的过程中可以记录路径。如果没有发现答案,就返回到函数入口,增加设定深度,继续搜索。

优劣

Code

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e7;
int INF = 1e7;
int res[N], tmp[N];
int gcd(int a, int b)
{
    return (b == 0) ? a : gcd(b, a % b);
}
int max_depth = 1;
bool dfs(int u, int a, int b, int depth)
{
    if (depth == max_depth)
    {
        if (a == 1)
        {
            if (b > INF) return 0;
            tmp[depth - 1] = b;
            if (!res[0] || b < res[depth - 1])
            {
                for (int i = 0 ; i < max_depth ; i++) res[i] = tmp[i];
                return 1;   
            } 
            return 1;
        }
        return 0;
    }
    bool flag = 0;
    for (int i = max(u, b / a) ; i <= 1ll * b / a * (max_depth - depth + 1) ; i++)
    {
        int nx = a * i - b, ny = b * i;
        if (nx < 0  || ny < 0) continue;
        int g = gcd(nx, ny);
        nx /= g, ny /= g;
        tmp[depth - 1] = i;
        if (dfs(i + 1, nx, ny, depth + 1)) flag = 1;
    }
    return flag;
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int a, b;
    cin >> a >> b;
    int Gcd = gcd(a, b);
    a /= Gcd;
    b /= Gcd;
    while(!dfs(2, a, b, 1)) max_depth++;
    for (int i = 0 ; i < max_depth ; i++) cout << res[i] << " ";
    return 0;
}