动态规划-钢筋切割问题
#include <iostream>
#include <stdint.h>
#include <stdlib.h>
using namespace std;
#define FREE_SPACE(ptr) { \
if (NULL != ptr) { \
free(ptr); \
ptr = NULL; \
} \
}
uint32_t priceTable[] = {
0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30};
uint32_t rebarCurring(uint32_t *p, uint32_t *s, uint32_t n) {
p[0] = 0, s[0] = 0;
for (uint32_t i = 1; i <= n; ++i) {
uint32_t subMaxPrice = 0;
for (uint32_t j = 1; j <= i; ++j) {
if (subMaxPrice < priceTable[j] + p[i - j]) {
subMaxPrice = priceTable[j] + p[i - j];
s[i] = j;
}
}
p[i] = subMaxPrice;
}
return p[n];
}
int main(int argc, const char *argv[]) {
uint32_t len = atoi(argv[1]);
uint32_t *maxPrices = (uint32_t *)malloc((len + 1) * sizeof(uint32_t));
uint32_t *spilteLens = (uint32_t *)malloc((len + 1) * sizeof(uint32_t));
uint32_t maxPrice = rebarCurring(maxPrices, spilteLens, len);
cout << "maxPrice: " << maxPrice << endl;
cout << "Spilte len: ";
uint32_t remainLen = len;
while (remainLen > 0) {
cout << spilteLens[remainLen] << " ";
remainLen -= spilteLens[remainLen];
}
FREE_SPACE(maxPrices);
FREE_SPACE(spilteLens);
return 0;
}