浙江工商大学23机试(小兔子跳格子)

题解:

方法思路:

  1. 贪心策略:每次在当前位置的可跳跃范围内,选择能跳得最远的位置作为下一跳的目标。

  2. 贪心遍历:

    1. 更新当前能到达的最远位置farthest

    2. 当遍历到当前跳跃位置最远位置cutrrent_end时,必须进行一次跳跃,并更新current_end为新的最远位置

    3. 若此时current_end已经超过最后一个格子,标记为可到达并终止循环

    4. 若此时继续前进(farthest未更新),终止循环           

  3. 终止条件:当current_end超过或等于最后一个位置时,表示已到达终点。

#include<bits/stdc++.h>
using namespace std;
int main(){
	int n;
	cin>>n;
	vector<int> a(n);
	for (int i = 0; i < n; i++){
		cin>>a[i];
	}
	
 	int jumps = 0;
    int current_end = 0;  //记录当前跳跃能到达的最远位置 
    int farthest = 0;    
    bool can_reach = false;
	for (int i = 0; i < n; ++i) {
        farthest = max(farthest, i + a[i]);
        if (i == current_end) {
            jumps++;
            current_end = farthest;
            if (current_end >= n - 1) {
                can_reach = true;
                break;
            }
            if (farthest <= i) {
                // 无法继续前进
                break;
            }
        }
    }

    if (can_reach) {
        cout << jumps << endl;
    } else {
        cout << -1 << endl;
    }

    return 0;
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值