Розбір
Let the array contain the cutting points: . Add the start and end points: and .
Let the function return the minimal cost of cutting a stick from to considering the necessary cutting points within the segment. There are no cutting points within the segment , so . The solution to the problem will be the value of . Store the computed values of in the cells of the array .
Let the segment of the stick be cut into several pieces. If the first cut is made at point , the cost of the cut itself will be . Then, the remaining pieces need to be cut at the costs and , respectively. Choose to minimize the total cost:
Example
Consider the second test case. Here is one possible way to cut a stick of length with a cost of :
Now, consider the optimal way to cut the stick, which has a cost of :
Algorithm implementation
Declare constants and arrays.
#define MAX 55 #define INF 0x3F3F3F3F int dp[MAX][MAX]; int m[MAX];
The function returns the minimum cost of cutting a piece of stick on the segment at the cutting points located inside the segment.
int f(int a, int b) {
If , then there are no cutting points within the segment . Return .
if (b - a == 1) return 0;
If the value of is already computed, return it.
if (dp[a][b] != INF) return dp[a][b];
Make a cut at the point . Compute the cost as follows:
for (int i = a + 1; i < b; i++) dp[a][b] = min(dp[a][b], m[b] - m[a] + f(a, i) + f(i, b));
Return the result .
return dp[a][b]; }
The main part of the program. Read the input data for each test case.
while(scanf("%d",&l),l) { scanf("%d",&n);
Add the start and end cutting points: .
m[0] = 0; m[n+1] = l; for(i = 1; i <= n; i++) scanf("%d",&m[i]);
Initialize the array.
memset(dp,0x3F,sizeof(dp));
Find and print the answer.
printf("The minimum cutting is %d.\n",f(0,n+1)); }