The first dynamic programming problem of algorithm introduction--Steel bar cutting
We know the lengths and prices of steel rods are:
Length I |
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
Price PI |
1 |
5 |
8 |
9 |
10 |
17 |
17 |
20 |
24 |
30 |
The two methods of the book are already very clear, here is mainly said after class after the practice of 15-3 steel strip cost plus cutting costs, that is, to cut the least number of times. 15-4 return to the cutting scheme
#include <fstream> #include <iostream>using namespace Std;int main () {int const N = 11;int P[n] = {0,1,5,8,8,10, 17,17,20,24,30}; Steel bar length corresponds to the price int const length = 7; Length of steel bar to be cut int r[length+1] = {0},num[length+1] = {0};//array R records the maximum price of each steel bar from bottom up, array num record number of cuts int s[length + 1] = {0};//record first paragraph Optimal cutting length for steel bars for (int j = 1; J <= Length; j + +) {int q = -1,index=0;for (int i = 1; I <= J; i++) {if (Q < p[i] + r[j-i ]) {q = p[i] + r[j-i];index = j-i;s[j] = i;} if (q = = P[i] + r[j-i]) {if (Num[j-i] > Num[index]) {index = j-i;s[j] = i;}}} if (index = = 0) Num[j] = = 0;else Num[j] = Num[index] + 1;r[j] = q;} for (int i = 1; I <= length; i++)//{//cout << num[i] << endl;//}int n = length;while (n > 0) {cout < < S[n] << ""; n = n-s[n];} System ("pause"); return 0;}
An introduction to the algorithm dynamic programming 15.1-3 steel bar cutting problem