跳到正文

题解

题解:B4296 [蓝桥杯青少年组国赛 2022] 最少问题

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

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
题目
B4296

版本

  1. v1当前

思路

橙题中一道很考验调试的题 ,居然没人贪心。大意就是已知一个数组 aa,aia_i 表示在第 ii 个木桩上最多可以向前走 aia_i 个木桩。考虑使用搜索:如果是暴搜的话,时间复杂度是 O(n!)O(n!) 的,肯定超时;考虑贪心,使用优先队列优化和标记优化,走得远的先遍历,做过了就标记,这样就得到了 90 分的代码。

C++
#include <bits/stdc++.h>
#define ll long long
#define U unsigned
using namespace std;
struct node{
    int foot,id;
    bool operator<(const node& a)const{
        return id<a.id;//走得远的在前
    }
}t;//优先队列结构体
bool vis[1005];//标记
int n,a[1005];
int main() {
	cin.tie(0)->sync_with_stdio(0);
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];//输入
    priority_queue<node>Q;
    Q.push({0,1});
    while(Q.size()){
        t=Q.top();
        Q.pop();//弹出对头
        if(t.id==n){
            cout<<t.foot;//输出
            break;
        }
        for(int i=min(a[t.id],n-t.id);i>=1;i--){//最多跳到第n个木桩上
            if(vis[t.id+i])continue;
            Q.push({t.foot+1,t.id+i});
            vis[t.id+i]=1;//标记
        }
    }//广搜
	return 0;
}

这究竟是因为什么呢?我们发现第一次到达时不一定是最优的,考虑就标记换为到达该处的最小步数,小于时应该再次进队。这样就得到了 AC 代码啦~

C++
#include <bits/stdc++.h>
#define ll long long
#define U unsigned
using namespace std;
struct node{
    int foot,id;
    bool operator<(const node& a)const{
        return id<a.id;//走得远的在前
    }
}t;//优先队列结构体
int vis[1005];//标记
int n,a[1005],minn=1e9;
int main() {
	cin.tie(0)->sync_with_stdio(0);
    cin>>n;
    for(int i=1;i<=n;i++)cin>>a[i];//输入
    priority_queue<node>Q;
    memset(vis,0x3f,sizeof vis);//初始化
    Q.push({0,1});
    while(Q.size()){
        t=Q.top();
        Q.pop();//弹出对头
        if(t.id>=n){
            minn=min(minn,t.foot);
            continue;
        }
        for(int i=min(a[t.id],n-t.id);i>=1;i--){
            if(vis[t.id+i]<t.foot+1)continue;//小于,不更新
            Q.push({t.foot+1,t.id+i});
            vis[t.id+i]=t.foot+1;//标记最小步数
        }
    }//广搜
    cout<<minn;//输出最小值
	return 0;
}

完结撒花~(理论上是卡不掉的,因为标记,所以都是取最小步数向下拓展,所以只会比 O(n)O(n) 慢一点)

原文