Problem: Given a length of n-inch steel bars and a price list pi (i=1,2,..., N), the Cut steel bar scheme, the largest sales yield rn. If the price pn is large enough for an n-inch steel bar, the optimal solution may be that it does not need to be cut at all.
Method One: Recursion
Go from top to bottom and search all over again.
int cut_rod (int p[],int N)
{
if (n==0)
return 0;
int q=int_min;
for (int i=1;i<=n;i++)
{
Q=max (Q,p[i]+cut_rod (p,n-i));
printf ("n=%d", n-i);
}
printf ("q=%d", Q);
printf ("\ n");
return q;
}
Method Two: top-down saving recursive complexity O (n^2) for computed sub-problems
int a (int p[],int n,int r[])
{
int q;
if (r[n]>0)
return r[n];
if (n==0)
q=0;
Else
{
Q=int_min;
for (int i=1;i<=n;i++)
Q=max (Q,p[i]+a (p,n-i,r));
}
r[n]=q;
return q;
}
int memoized_cut_rod (int q[],int N)
{
int *r= (int *) malloc (sizeof (int) *n);
for (int i=1;i<=n;i++)
R[i]=int_min;
Return a (Q,N,R);
}
Method Three: Dynamic programming
Dynamic programming is a bottom-up approach that is implemented through a for loop, where all of its sub-problems are found when a problem is asked. The introduction of this part of the algorithm p209 page explanation is very exciting.
And in order to output the scheme, the reconstruction solution is used to output.
The code is as follows
#include <stdio.h>
#include <stdlib.h>
typedef struct CUT
{
int *r;
int *s;
}cut;
void Initialize (Cut *mycut,int N)
{
mycut->r= (int *) malloc (sizeof (int) *n);
mycut->s= (int *) malloc (sizeof (int) *n);
}
cut* T (int p[],int N)
{
Cut *mycut= (Cut *) malloc (sizeof (cut));
Initialize (mycut,n);
mycut->r[0]=0;
for (int j=1;j<=n;j++)
{
int q=int_min;
for (int i=1;i<=j;i++)
{
if (Q<p[i]+mycut->r[j-i])
{
q=p[i]+mycut->r[j-i];
mycut->s[j]=i;
}
}
mycut->r[j]=q;
}
return mycut;
}
void print_cut_rod_solution (int p[],int N)
{
int i=1;
Cut *mycut= (Cut *) malloc (sizeof (cut));
Initialize (mycut,n);
Mycut=t (P,n);
while (n>0)
{
printf ("%d length is%d", i,mycut->s[n]);
i++;
n=n-mycut->s[n];
}
}
int main (void)
{
Cut *mycut= (Cut *) malloc (sizeof (cut));
printf ("Length n is how much:");
int n;
scanf ("%d", &n);
Initialize (mycut,n);
int *p= (int *) malloc (sizeof (int));
int i=1;
printf ("Enter the price corresponding to the different lengths to end \ n");
int key;
while (scanf ("%d", &key) ==1)
{
P[i++]=key;
}
Mycut=t (P,n);
printf ("max=%d", Mycut->r[n]);
Print_cut_rod_solution (P,n);
return 0;
}
Results:
Length I 1 2 3 4 5 6 7 8 9 10
Price PI 1 5 8 9 10 17 17 20 24 30
"Algorithm design-dynamic programming" steel bar cutting problem