思路
橙题中一道很考验调试的题 ,居然没人贪心。大意就是已知一个数组 , 表示在第 个木桩上最多可以向前走 个木桩。考虑使用搜索:如果是暴搜的话,时间复杂度是 的,肯定超时;考虑贪心,使用优先队列优化和标记优化,走得远的先遍历,做过了就标记,这样就得到了 90 分的代码。
#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 代码啦~
#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;
}完结撒花~(理论上是卡不掉的,因为标记,所以都是取最小步数向下拓展,所以只会比 慢一点)