How to print the optimal path from beginning in dynamic programming technique
Below is the code for standard maxsum of an array containing +ve and -ve numbers. I think, the below programs works correct. Bot how do I print the optimal path? By keeping a pointer to optimal parent, I can print the path in backwards direction easily, but how to print it in forward direction, preferably without keeping too much extra bookkeeping.
#include <stdio.h>
main()
{
int array[]={5,-5,3,4,-2};
int n=5;
int i;
int maxsumendingat[n];
int parent[n];
int maxsum=-9999; // better way to code?
int optimallastindex;
maxsumendingat[0]=array[0];
for(i=1;i<n;i++)
{
if(maxsumendingat[i-1] <= 0)
{
maxsumendingat[i]=array[i];
parent[i]=i;
}
else
{
maxsumendingat[i]=array[i]+maxsumendingat[i-1]; // also keep backtra开发者_高级运维cking info
parent[i]=i-1;
}
}
// now print results
for(i=0;i<n;i++)
{
if(maxsum < maxsumendingat[i])
{
maxsum=maxsumendingat[i];
optimallastindex=i;
}
}
// now print path. how to print it in fwd direction?
i=optimallastindex;
printf("%d ",array[i]);
while(parent[i]!= i)
{
printf("%d ",array[parent[i]]);
i=parent[i];
}
}
Just store the reversed path in a temporary array and then iterate that array backwards.
Simply you can copy parents in new array (or stack) then iterate array in backward order, or instead of using parent use next and in your else
statement do next[i-1] = i
.
精彩评论