算法导论动态规划实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int max(int a,int b)
{
return a>b?a:b;
}
int bottomup(int p[],int n)
{
int *r=(int *)malloc((n+1)*sizeof(int));
memset(r,0,n*sizeof(int));
int i=0,j=0;
int q=-999999;
for(j=0;j<n;++j)
{
q=-999999;
for(i=0;i<=j;++i)
q=max(q,p[i]+r[j-i]);
r[j+1]=q;
}
int best=r[n];
free(r);
return best;
}
int main()
{
int p[10]={1,5,8,9,10,17,17,20,24,30};
printf("%d\n",bottomup(p,4));
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int max(int a,int b)
{
if(a==b)
printf("%d\n",a);
return a>b?a:b;
}
int extendbottomup(int p[],int n,int r[],int s[])
{
int q=-999999;
int i=0,j=0;
for(j=0;j<n;++j)
{
q=-999999;
for(i=0;i<=j;++i)
{
if(q<p[i]+r[j-i])
{
q=p[i]+r[j-i];
s[j+1]=i+1;
}
r[j+1]=q;
}
}
return r[n];
}
int main()
{
int n=7;
int p[10]={1,5,8,9,10,17,17,20,24,30};
int r[8]={0};
int s[8]={0};
printf("%d\n",extendbottomup(p,n,r,s));
while(n>0)
{
printf("%d\n",s[n]);
n=n-s[n];
}
return 0;
}