跳格子【DP】

>Description
他们来到了一片空地,画了N个连续的方格,每个方格上随机填上了一个数字,大家从第一个格子开始,每次可以向后跳不超过当前格子上的数的步数,大家开始就此比赛,看谁跳到最后一个格子的步数最少。


>Input
输入第一行包含一个整数N,表示画的格子的个数。
第二行包含N整数,表示每个格子上的数ai。

>Output
输出一行,表示跳的最少步数


>Sample Input
5
2 3 1 1 1

>Sample Output
2

对于40%的数据满足N<=10,ai<=10。
对于100%的数据满足N<=5000,ai<=1000。


解题思路
直接DP:f[i]=到第i格的最少步数


>代码

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,a,f[5005];
int main()
{
	memset(f,0x7f,sizeof(f));
	scanf("%d",&n);
	f[1]=0; //设初值
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&a);
		for(int j=i+1;j<=i+a;j++)
		{
		    if(j>n) break; //如果越界了就退出
			f[j]=min(f[j],f[i]+1); //状态转移方程
			if(j==n) //先到就直接输出
			{
				printf("%d",f[n]);
				return 0;
			}
		}
	}
	printf("%d",f[n]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43010386/article/details/88850107