c++ - Dynamic Programming : Timus Online Judge 1119 Metro -


i trying problem http://acm.timus.ru/problem.aspx?space=1&num=1119 on timus online judge. however, strange reason recursive function doesn't work. if print final value returned prints : "-nan". when print its's rounded form prints garbage value.

#include <iostream> #include <cstring> #include <cmath> #define min(x,y) ((x<y) ? (x) : (y)) using namespace std; int x,y; float dp[1001][1001];    //for memoization bool d[1001][1001];      // storing whether diagonal movement possible or not float solve(int x,int y) {     if (dp[x][y]!= -1.0)         return dp[x][y];     if (x == 0 && y == 0)         return (dp[x][y] = 0.0);     if (x == 0 )         return (dp[x][y] = y*100);     if (y == 0)         return (dp[x][y] = x*100);     float ret;     float r1,r2,r3;     r1 = 100.0 + solve(x-1,y);     r2 = 100.0 + solve(x,y-1);     ret = min(r1,r2);     if (d[x][y]) {         r3 = solve(x-1,y-1);         r3 = r3 + 141.42;         ret = min(ret,r3);     }     dp[x][y] = ret;     return ret; } int main() {     cin >> x >> y;     int k;     int d1,d2;     cin >> k;     memset(dp,-1.0,sizeof dp);     memset(d,false,sizeof d);     (int i=0;i<k;i++) {         cin >> d1 >> d2;         d[d1][d2]=true;     }     float dist = solve(x,y);     int ans = dist;     if (dist - ans > 0.5) {         ans++;     }     cout << ans << endl;    // prints garbage value }                           // cout << dist << endl prints "-nan" 

here's ideone link : http://ideone.com/6c2wjr

memset(dp,-1.0,sizeof dp); doesn't think, use std::fill or std::fill_n instead.

or std::vector:

std::vector<std::vector<float>> dp(1001, std::vector<float>(1001, -1.f)); 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -