[Algorithm design-Dynamic Planning] steel strip cutting problem, plan Steel Strip
Problem: given a piece of steel strip with a length of n inches and a price list pi (I =,..., n), find the cutting steel strip solution, which maximizes the sales revenue of rn. If the price of a steel strip with a length of n inches is pn large enough, the optimal solution may be that no cutting is required at all.
Method 1: Recursion
Search all from top to bottom
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 2: Save the recursive complexity of the computed sub-problems from top to bottom o (n ^ 2)
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 3: Dynamic Planning
Dynamic Planning is a bottom-up method. It is implemented through the for loop. When a problem is solved, all its subproblems have been obtained. This part of the introduction to algorithms on the p209 page is very exciting.
In addition, the reconstruction solution is used for 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 ("the length of section % d is % d", I, mycut-> s [n]);
I ++;
N = n-mycut-> s [n];
}
}
Int main (void)
{
Cut * mycut = (cut *) malloc (sizeof (cut ));
Printf ("length n :");
Int n;
Scanf ("% d", & n );
Initialize (mycut, n );
Int * p = (int *) malloc (sizeof (int ));
Int I = 1;
Printf ("Enter the price corresponding to different lengths, end with # \ 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;
}
Result:
Length I 1 2 3 4 5 6 7 8 9 10
Price pi 1 5 8 9 10 17 20 24 30