Dynamic Programming Using STL Vectors Makes Program Freeze Beyond Certain Values
Following insights from the comments, the problem has been solved.
There were two issues with the initial program:
-
Trying to insert elements beyond the current size of the vector: To fix this issue, use an
if
statement before inserting elements to the vector to ensure that it has the correct capacity.if(memory.capacity()<(n+1)){ memory.resize(n+1); } memory[n]=m;
-
Using items from memory that we did not previously insert: When we are resizing
memory
from the previous point, we are also creating empty values at spots that we did not insert into before. For example,mini(7)
would insert the values ofmini(3)
andmini(7)
intomemory
. The values ofmini(4)
,mini(5)
andmini(6)
would remain0
. Later when we use the function, the values ofmini(4)
,mini(5)
andmini(6)
would be found in the memory to be0
, and be used as such, leading to incorrect answers.
Fixing both errors, the revised function looks like this:
int mini(int n, vector<int> &memory){
if(n<memory.size() && memory[n]!=0){
return memory[n];
}
else{
int m = (n+1)+mini(((n-1)/2), memory)+mini(((n-1)-((n-1)/2)), memory);
if(memory.capacity()<(n+1)){
memory.resize(n+1);
}
memory[n]=m;
return m;
}
}