bfs

11  •  1个月前


#include <iostream>
#include <queue>
#include <vector>
using namespace std;

// 定义状态结构体
struct State {
    int index; // 当前处理的苹果索引
    int count; // 已经摘取的苹果数
};

int bfs(const vector<int>& appleHeights, int maxReachWithStool) {
    queue<State> q;  // 创建队列
    q.push({0, 0});  // 初始状态:从第0个苹果开始,摘取数量为0
    int maxApples = 0;

    while (!q.empty()) {
        State current = q.front();  // 取出队首元素
        q.pop();

        // 如果已经处理完所有苹果,更新最大摘取数量
        if (current.index == 10) {
            if (current.count > maxApples) {
                maxApples = current.count;
            }
            continue;
        }

        // 不摘取当前苹果,扩展下一个状态
        q.push({current.index + 1, current.count});

        // 如果可以摘取当前苹果,扩展下一个状态
        if (appleHeights[current.index] <= maxReachWithStool) {
            q.push({current.index + 1, current.count + 1});
        }
    }

    return maxApples;  // 返回能够摘到的最大苹果数
}

int main() {
    vector<int> appleHeights(10);
    int maxReachHeight;

    // 读取10个苹果的高度
    for (int i = 0; i < 10; i++) {
        cin >> appleHeights[i];
    }

    // 读取陶陶的伸手高度
    cin >> maxReachHeight;

    // 计算能够达到的最大高度
    int maxReachWithStool = maxReachHeight + 30;

    // 执行BFS搜索
    int result = bfs(appleHeights, maxReachWithStool);

    // 输出最终结果
    cout << result << endl;

    return 0;
}


评论:

大佬方法太好了,看一遍就懂了


lzhh_lzhh26  •  1个月前

大佬风范,一遍就懂


天生我材必有难,千金散尽还债来  •  1个月前

大佬的方法太简单了,一学就会


6  •  1个月前

请先登录,才能进行评论