I am trying optimize a recursion problem using map to deal with the runtime errors. However, using memoization method and implementing a map still cannot solve the problem completely. By using the naive way of recursion, the segmentation fault error will not show up until the totalNum = 36. After optimization, the segmentation fault error will still show up when the totalNum getting really large, like 99999. Is there any way to solve this runtime problem even when the totalNum gets bigger than 99999? The following is my code for the header file:
using namespace std;
static map<pair<int, int>, double> map;
double val(int r, int b){
if (0 == r)
return ((double) b);
if (0 == b)
return (0);
if (map.find(make_pair(r, b)) != map.end()){
return (double)map[make_pair(r, b)];
} else{
double num1 = ((double) r/(r+b)) * value(r-1, b);
double num2 = ((double) b/(r+b)) * value(r, b-1);
double value = max((num1 + num2), (double) (b - r));
map[make_pair(r, b)] = value;
return value;
}
}
#endif
It is used in the main() to print out a message: cout << "Value = " << val(totalNum/2,totalNum/2) << endl;