I wrote following code for a Dynamic Programming problem but the online judge gives me a 'Time Limit Exceeded' error. I wonder how can I optimize this code more efficiently, especially the part of initializing the DP array to 0.0(I am using memset() right now.) Any pointers to the 'inefficient' lines of the code are welcome.
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<cstring>
using namespace std;
#define max 2000
int main(){
int T;
double **dp = new double*[max];
for(int i=0; i<max; ++i)
dp[i] = new double[max];
cin >> T;
while(T--){
int N;
cin >> N;
int V[N];
for(int i=0; i<N; ++i)
cin >> V[i] ;
for(int i=0; i<N; ++i)
memset(dp[i], 0.0, sizeof(dp[0][0])*N);
for(int i=0; i<N; ++i)
dp[i][i] = V[i];
for(int j=1; j<N; ++j)
for(int i=j-1; i>=0; --i){
dp[j][i] = 0.5 * ( dp[i][i] + dp[j][j] + dp[j-1][i+1] );
if( (i+2)<N )
dp[j][i] += (0.250 * dp[j][i+2]);
if( (j-2)>=0 )
dp[j][i] += (0.250 * dp[j-2][i]);
}
cout << setprecision (5) << dp[N-1][0] << endl;
}
for(int i=0; i<max; ++i)
delete[] dp[i];
delete dp;
return 0;
}
Thanks in advance,
EDIT:
The given problem is as following:
1. There are N values in an array. Two players take turn by turn to play the game.
2. Player1, with 50% probability can pick the left most value or the right most value.
3.If there is only one value left in the array, the player, having no more choice, will just pick up that value.
4. Question is to calculate the expected sum of values that First player can obtain.
Edit 2:
T<=500 and N<=2000
Updated code.
Now using dp array on stack instead of heap(as suggested by dasblinkenlight).
#include<iostream>
#include<iomanip>
#include<cstring>
#define max 2000
int main(){
int T;
std::cin >> T;
while(T--){
int N;
std::cin >> N;
int V[N];
for(int i=0; i<N; ++i)
std::cin >> V[i];
int r = N < 3 ? N : 3;
double dp[r][N];
for(int i=0; i<r; ++i)
dp[i][i] = V[i];
for(int j=1; j<N; ++j)
for(int i=j-1; i>=0; --i){
dp[j%3][i] = 0.5 * ( V[i] + V[j] + dp[(j-1)%3][i+1] );
dp[j%3][i] += (0.250 * dp[(j-2)%3][i]);
if( (i+2)<N )
dp[j%3][i] += (0.250 * dp[j%3][i+2]);
}
std::cout << std::setprecision (5) << dp[(N-1)%3][0] << std::endl;
}
return 0;
}
This still gives me a 'Time Limit Exceeded' error.
I wonder if there is any better approach to solve this problem?