The outputs:
Inputs
5 // the number of elements in array
2 0 1 1 1 // the values in array
outputs:
4 // that means we need at least 4 steps to cross river
The codes:
# include <iostream>
# include <iomanip>
# include <climits>
using namespace std;
void create_array(int* &a, int n);
int cross_river(int a[], int n);
int main ()
{
int n; // the length of the array or the interval length of river
cin >> n;
int* a;
create_array (a, n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
cout << cross_river(a, n);
return 0;
}
void create_array (int* &a, int n)
{
a = new int[n];
for(int i = 0; i < n; i ++){
*(a + i) = INT_MAX;
}
}
int cross_river(int a[], int n)
{
int* dp;
create_array (dp, n+1); // create the dynamic programming array
dp[0] = 0; // that means from bank to bank no needs step
for (int i = 1; i <= n; i ++){
for (int j = 0; j < i; ++j){
if (a[j] + j >= i){
dp[i] = min (dp[j]+1, dp[i]);
}
}
}
return dp[n] < INT_MAX ? dp[n] : -1; // it is obvious that dp[n] store the least steps from bank to the other.
}