1847: Game

 Wx最近在玩一个跳格子的游戏,游戏的规则如下:给出n个格子,每个格子有一个数字x,

代表在该位置可以向右跳0-x步,现在Wx需要算出最少的跳跃次数,从最左边的格子跳到

最右边的格子,输出跳跃的次数,若跳不到最右边的格子,则输出-1.

Input

输入一个t,表示有t组测试数据(1<=t<=10)

对于每组测试数据读入一个n表示格子的个数(2<=n<=20),下面一行n个数,表示每个格子上的数字是多少

Output

对于每组测试数据,输出一个数字,表示跳到最右边格子的最小跳跃次数,若跳不到,则输出-1.

Sample Input

4
5
1 2 3 4 5
5
4 3 2 1 0
6
1 1 1 1 1 1
7
4 1 1 1 0 2 4

Sample Output

3
1
5
-1
 
一开始是用队列宽搜,自己觉得逻辑没问题,但老是错误。
从起点开始,每次下一步都找那步能走最远的那个数
 
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<queue>

using namespace std;

int main()
{
    int T;
    cin>>T;

    while(T--)
    {
        int n;
        int flag=1;
        cin>>n;
        int a[100]={0};
        int dp[100]={0};
        int b[100]={0};
        for(int i=1;i<=n;i++)
             cin>>a[i];
        int t1=1;//当前位置
        int s=0;//步数
        while(flag)
        {
            if(t1+a[t1]<n)
            {
                int ma=0;
                int e;
                for(int i=1;i<=a[t1];i++)
                {
                    if(i+a[i+t1]>ma)
                    {
                        ma=i+a[i+t1];
                        e=i+t1;
                    }
                }
                if(ma==0)
                    break;
                else
                {
                   t1=e;
                   s++;
                }
            }
            else
            {
                cout<<s+1<<endl;
                flag=0;
            }
        }
        if(flag)
           cout<<"-1"<<endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/xzxj/p/6744314.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值