深搜广搜例题讲解--蒟蒻成长之路

P2404 自然数的拆分问题 - 洛谷

#include<bits/stdc++.h>
using namespace std;
int n,a[100];

void dfs(int sum, int c, int begin) {
    if (sum == n) {
        for (int i = 1; i <= c-2; i++) {//1~8,打印前面六个
            cout << a[i] << "+";
        }
        cout << a[c-1] << endl;
        return;
    }
    if (sum > n)return;
    for (int i = begin; i < n; i++) {//如果n=4,只能是112,排除121或者211
        a[c] = i;
        dfs(sum + i, c + 1, i);
    }
}
int main() {
    cin >> n;
    dfs(0, 1, 1);
    return 0;
}

P2895 [USACO08FEB] Meteor Shower S - 洛谷

#include <bits/stdc++.h>
using namespace std;
int n, x, y, t;
const int N = 305;
int a[N][N]; // 坐标是否被流星摧毁的时间//如果一直为1就是没有被摧毁
int mark[N][N]; // 标记坐标是否被访问过
int dx[] = { 1, -1, 0, 0 }; // 方向数组
int dy[] = { 0, 0, 1, -1 };
struct pos { // 结构体变量x  y相当于人移动
    int x, y, step;//step相当于时间变量
};
void bfs();

int main() {
    cin >> n;
    memset(a, -1, sizeof(a)); // 初始化 a 数组为 -1,表示未被摧毁
    // 处理流星信息
    while (n--) {
        cin >> x >> y >> t;
        if (a[x][y] == -1 || t < a[x][y]) a[x][y] = t; // 更新撞击点的最早毁灭时间//错在这个开始不会用
        // 更新撞击点周围四个点的最早毁灭时间
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            if (nx >= 0 && ny >= 0 && nx < N && ny < N) {
                if (a[nx][ny] == -1 || t < a[nx][ny])  a[nx][ny] = t;
            }
        }
    }
    bfs(); // 开始 BFS 寻找最短路径
    return 0;
}

void bfs() {
    queue<pos> qu;
    qu.push({ 0, 0, 0 }); // 起点
    mark[0][0] = 1; // 标记起点为已访问
    while (!qu.empty()) {
        pos cur = qu.front();
        qu.pop();
        // 检查当前点是否安全
        if (a[cur.x][cur.y] == -1 || a[cur.x][cur.y] > cur.step) {
            if (a[cur.x][cur.y] == -1) { // 如果该点永远不会被摧毁
                cout << cur.step << endl;
                return;
            }
            // 遍历四个方向
            for (int i = 0; i < 4; i++) {
                int xx = cur.x + dx[i];
                int yy = cur.y + dy[i];
                // 检查边界和访问状态
                if (xx >= 0 && yy >= 0 && xx < N && yy < N && !mark[xx][yy]) {
                    // 检查该点是否安全
                    if (a[xx][yy] == -1 || a[xx][yy] > cur.step + 1) {
                        mark[xx][yy] = 1; // 标记为已访问
                        qu.push({ xx, yy, cur.step + 1 });
                    }
                }
            }
        }
    }
    // 如果没有找到安全地点,输出 -1
    cout << -1 << endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值