1595 字
8 分钟
【OI考古】基础算法 | 搜索

搜索,是Yukko首先给我介绍的几类算法之一,其对状态空间进行枚举,通过穷尽所有的可能来找到最优解,或者统计合法解的个数。

搜索有很多优化方式,如减小状态空间,更改搜索顺序,剪枝等。

搜索是一些高级算法的基础。在 OI 中,纯粹的搜索往往也是得到部分分的手段,但可以通过纯粹的搜索拿到满分的题目非常少。

DFS(深度优先搜索)#

DFS 本是图论概念,在搜索算法中,该词常常指利用递归函数方便地实现暴力枚举的算法,与图论中的 DFS 算法有一定相似之处,但并不完全相同。

DFS 框架#

#include <cstdio>
using namespace std;
const int maxn = 100;
int n;
bool vst[];
bool CheckEdge(...) // 边界条件和约束条件的判断
{
    if (...) // 满足条件
        return 1;
    else // 与约束条件冲突
        return 0;
}

void dfs(int depth)
{
    if (depth > n) // 出现目标态G
    {
        ...... // 做相应处理
        return;
    }
    for (int i = 1; i < n; i++) // 按照规则生成下一个节点
    {
        if (!CheckEdge(...)) continue; //如果不满足条件则跳过
        vst[] = 1;      // 标记该节点被访问过
        dfs(depth + 1);
        vst[] = 0;      // 回溯
    }
}
int main()
{
    ......
    return 0;
}

例题#

洛谷 P1706 | 全排列问题#

洛谷 P1219 | [USACO1.5]八皇后 Checker Challenge#

洛谷 P1092 | [NOIP2004 提高组] 虫食算#

洛谷 P1120 | 小木棍 [数据加强版] #

洛谷 P1706 | 全排列问题#

题目描述#

输出自然数 11nn 所有不重复的排列,即 nn 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。

输入格式#

一个整数 nn

输出格式#

1n1∼n 组成的所有不重复的数字序列,每行一个序列。

每个数字保留 55 个场宽。

输入输出样例#

输入 #1#
3
输出 #1#
    1    2    3
    1    3    2
    2    1    3
    2    3    1
    3    1    2
    3    2    1

说明/提示#

1n91≤n≤9

解决方案#

#include <iostream>
#include <cstdio>
using namespace std;
const int maxn = 20;
int n;
int now[maxn];
bool vis[maxn];
void dfs(int depth)
{
    if(depth > n)
    {
        for(int i=1; i<=n; i++)
        {
            printf("%5d", now[i]);
        }
        puts("");
        return;
    }
    for(int i=1; i<=n; i++)
    {
        if(vis[i]) continue;
        vis[i] = true;
        now[depth] = i;
        dfs(depth + 1);
        vis[i] = false;
    }
}
int main()
{
    scanf("%d", &n);
    dfs(1);
    return 0;
}

BFS(广度优先搜索)#

BFS 是图论中的一种遍历算法,在搜索中也很常用,将每个状态对应为图中的一个点,将状态存入队列即可。

BFS 框架#

#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 100;
bool vst[maxn][maxn];                       // 访问标记
int dir[4][2] = {0, 1, 0, -1, 1, 0, -1, 0}; // 方向向量

struct State // BFS 队列中的状态数据结构
{
    int x, y;         // 坐标位置
    int Step_Counter; // 搜索步数统计器
};

State a[maxn];

bool CheckState(State s) // 约束条件检验
{
    if (!vst[s.x][s.y] && ...) // 满足条件
        return 1;
    else // 约束条件冲突
        return 0;
}

void bfs(State st)
{
    queue<State> q;      // BFS 队列
    State now, next;     // 定义2 个状态,当前和下一个
    st.Step_Counter = 0; // 计数器清零
    q.push(st);          // 入队
    vst[st.x][st.y] = 1; // 访问标记
    while (!q.empty())
    {
        now = q.front(); // 取队首元素进行扩展
        if (now == G)    // 出现目标态,此时为Step_Counter 的最小值,可以退出即可
        {
            ...... // 做相关处理
                return;
        }
        for (int i = 0; i < 4; i++)
        {
            next.x = now.x + dir[i][0]; // 按照规则生成下一个状态
            next.y = now.y + dir[i][1];
            next.Step_Counter = now.Step_Counter + 1; // 计数器加1
            if (CheckState(next))                     // 如果状态满足约束条件则入队
            {
                q.push(next);
                vst[next.x][next.y] = 1; //访问标记
            }
        }
        q.pop(); // 队首元素出队
    }
    return;
}

int main()
{
    ......
    return 0;
}

例题#

洛谷 P1141 | 01 迷宫#

洛谷 P1126 | 机器人搬重物#

洛谷 P1312 | [NOIP2011 提高组] Mayan 游戏#

洛谷 P1514 | [NOIP2010 提高组] 引水入城#

P1141 01 迷宫#

题目描述#

有一个仅由数字 0011 组成的 n×nn \times n 格迷宫。若你位于一格 00 上,那么你可以移动到相邻 44 格中的某一格 11 上,同样若你位于一格 11 上,那么你可以移动到相邻 44 格中的某一格 00 上。

你的任务是:对于给定的迷宫,询问从某一格开始能移动到多少个格子(包含自身)。

输入格式#

11 行为两个正整数 n,mn, m

下面 nn 行,每行 nn 个字符,字符只可能是 00 或者 11 ,字符之间没有空格。

接下来 mm 行,每行 22 个用空格分隔的正整数 i,ji, j ,对应了迷宫中第 ii 行第 jj 列的一个格子,询问从这一格开始能移动到多少格。

输出格式#

mm 行,对于每个询问输出相应答案。

输入输出样例#

输入 #1#
2 2
01
10
1 1
2 2
输出 #1#
4
4

说明/提示#

所有格子互相可达。

对于 20%20\% 的数据, n10n≤10

对于 40%40\% 的数据, n50n≤50

对于 50%50\% 的数据, m5m≤5

对于 60%60\% 的数据, n100,m100n≤100,m≤100

对于 100%100\% 的数据, n1000,m100000n≤1000,m≤100000

解决方案#

#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;
const int maxn = 1050;
class Tuple	//坐标类
{
public:
    int _x_, _y_;
    Tuple()
    {
        _x_ = _y_ = 0;
    }
    void val(int x_, int y_)
    {
        _x_ = x_;
        _y_ = y_;
    }
    Tuple operator+(const Tuple &b_)
    {
        Tuple c_;
        c_._x_ = this->_x_ + b_._x_;
        c_._y_ = this->_y_ + b_._y_;
        return c_;
    }
};
int n, m;
int mp[maxn][maxn], ans[maxn][maxn];
struct Node	//节点
{
    Tuple c;
    int d;
};
bool check(Tuple p, Tuple q)	//检查节点是否合法
{
    int x = p._x_, y = p._y_;
    int a = q._x_, b = q._y_;
    if (ans[x][y])
        return false;
    if (x == 0 || y == 0)
        return false;
    if (x == n + 1 || y == n + 1)
        return false;
    if (mp[x][y] ^ mp[a][b])
        return true;
    return false;
}
int bfs(int x, int y)
{
    if (ans[x][y])
        return ans[x][y];

    Tuple mv[4];
    mv[0].val(0, 1);
    mv[1].val(0, -1);
    mv[2].val(1, 0);
    mv[3].val(-1, 0);

    Node tmp;
    tmp.c.val(x, y);
    tmp.d = 1;

    queue<Node> tree;
    tree.push(tmp);

    vector<Tuple> zone;

    int ansn = 0;
    ans[x][y] = 1;

    while (!tree.empty())
    {
        tmp = tree.front();
        tree.pop();
        zone.push_back(tmp.c);
        ansn++;
        for (int i = 0; i < 4; i++)
        {
            Node now;
            now.c = tmp.c + mv[i];
            now.d = tmp.d + 1;
            if (!check(now.c, tmp.c))
                continue;
            tree.push(now);
            ans[now.c._x_][now.c._y_] = ansn;
        }
    }
    for (int i = 0; i < zone.size(); i++)
    {
        int x_ = zone[i]._x_;
        int y_ = zone[i]._y_;
        ans[x_][y_] = ansn;
    }
    return ansn;
}
int main()
{
    scanf("%d %d", &n, &m);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            char l[5];
            scanf("%1s", l);
            mp[i][j] = l[0] - '0';
        }
    }
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        scanf("%d %d", &x, &y);
        printf("%d\n", bfs(x, y));
    }
    return 0;
}

请参阅#

【OI考古】基础算法 | 搜索
https://blog.vonbrank.com/posts/oi-basic-algorithm-search/
作者
Von Brank
发布于
2021-03-20
许可协议
CC BY-NC-SA 4.0