X
X
xxxx_videos2022-01-29 20:55:26
Algorithms
xxxx_videos, 2022-01-29 20:55:26

How to solve the grasshopper problem using dynamic programming?

According to the condition, there is a certain number of water lilies with a different amount of grass on each. it can be positive or negative. the grasshopper initially stands on the first water lily, and can only jump over one or two water lilies. you need to find the maximum amount of grass that the grasshopper will collect on the way to the last water lily.
the input is given the number n (the number of water lilies), and n different numbers (the amount of grass on the water lilies). withdraw the maximum amount.
On one of the tests, the program gives an incorrect answer. I don’t know what input data there is, so I can’t figure out what’s wrong. help find the error

#include <iostream>
using namespace std;

int max(int one, int two)
{
    if (one > two)
        return one;
    return two;
}

int main()
{

    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);

    int N;
    int a[1000];
    cin >> N;
    for (int i = 0; i < N; i++)
        cin >> a[i];
    a[2] = a[0] + a[2];
    a[3] = a[0] + a[3];
    a[4] = a[2] + a[4];
    for (int i = 5; i < N; i++)
        a[i] += max(a[i - 2], a[i - 3]);
    cout << a[N - 1];
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexandroppolus, 2022-01-29
@Alexandroppolus

Does a grasshopper have to visit the last water lily?
If not (if you can skip it), then end up with cout << max(a[N-2], a[N - 1]);

W
Wataru, 2022-01-29
@wataru

Describe your dynamic programming - the physical meaning of the function and the recurrence relation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question