c++ - How to avoid SEGMENTATION ERROR for the code below? -
i'm getting segmentation error code below. solution the spoj problem "coins".
i went through how avoid sigsegv? , made sure not use uninitialized pointers, not access out of memory etc (given n ≤ 109).
i know array a[1000000000]
lead stack overflow, used std::map
. std::map
ever lead stack overflow? wrong code?
#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> #include <cmath> #include <map> using namespace std; map<unsigned long long int, unsigned long long int> a; unsigned long long int dp(unsigned long long int n) { if (a.find(n) == a.end()) a[n] = dp(n/2) + dp(n/3) + dp(n/4); return a[n]; } int main() { (unsigned long long int = 1; <= 24; i++) { a[i] = i; if (i == 12 || == 24) a[i] = + 1; } unsigned long long int n = 0; cin >> n; while (!feof(stdin)) { printf("%llu\n", dp(n)); cin >> n; } }
you sigsegv on dp(0)
call. causes infinite recursion.
by way, solution wrong, example answer 24 not 25. try avoid magic constants, enough set a[0] = 0
, make more accurate dp
function:
uint32_t dp(uint32_t n) { if (a.find(n) == a.end()) a[n] = max(n, dp(n / 2) + dp(n / 3) + dp(n / 4)); return a[n]; }
as can seen above, 32-bit type enough store possible answer.
Comments
Post a Comment