Niuke.com Sohu 2017 Autumn Recruitment R&D Engineer Written Test Paper (2) - Kangaroo Crossing the River

Link: https://www.nowcoder.com/questionTerminal/74acf832651e45bd9e059c59bc6e1cbf?toCommentId=1118302
Source: Niuke.com

  • Space limit: 32768K
A kangaroo wants to jump from one side of the river to the other side of the river. The river is very wide, but there are many stakes in the middle of the river, one every one meter, and there is a spring on each stake, and the kangaroo can jump by jumping on the spring. farther. The strength of each spring is different, and a number represents its strength. If the spring strength is 5, it means that the kangaroo can jump up to 5 meters in the next jump. If it is 0, it will get stuck and cannot continue to jump. The river is N meters wide. The initial position of the kangaroo is on the first spring. After jumping to the last spring, the river is crossed. Given the force of each spring, find out how many jumps the kangaroo needs at least to reach the opposite bank. If the output cannot be reached -1

Enter description:
The input is divided into two lines, the first line is the array length N (1 ≤ N ≤ 10000), and the second line is the value of each item, separated by spaces.


Output description:
Output the minimum number of hops, unable to reach output -1

Example 1

enter

5
2 0 1 1 1

output

4


analyze:

There was this question in the school competition. At that time, I saw that it was a dp question. I felt that it was private, but I couldn't submit it. Then I came down and saw other people's ideas. I understand. So detailed.

In this question, the use of a function is deepened again. The memset and memset functions initialize the memory block by bytes, so it cannot be used to initialize the int array to other values ​​than 0 and -1. It is always less than The correct answer, and then changed it here.


#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;

const int N=10005;
#define INF 99999999
int dp[N],s[N];

intmain()
{
    int n;
    for(int i=0;i<N;i++)///Initialize the dp array
        dp[i]=INF;
    dp[0]=0;///Remember that the one here is set to 0
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&s[i]);
    for(int i=1;i<=n;i++)///Then update the value of the big dp[i]
    {
        for(int j=0;j<i;j++)
        {
            if(j+s[j]>=i)///If you can reach the i position from the j position, see if you can update the array of dp[i]
                dp[i]=min(dp[i],dp[j]+1);
        }
    }
    printf("%d\n",dp[n]==INF?-1:dp[n]);
    return 0;
}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324939457&siteId=291194637
Recommended