# 动态规划：钢条切割问题实现

#include <iostream>
#include <stdio.h>
#include <memory.h>
#define N 100
int prices[N];              //长度为n的钢条的价格
int r[N];                   //长度为n时的最大收益
int cut_rod(int n);         //求最大收益

int main()
{
int n;
while(1 == scanf("%d", &n))
{
memset(r, -1, sizeof(r));
for(int i = 1; i <= n; ++i)
scanf("%d", &prices[i]);

printf("%d\n", cut_rod(n));
}
return 0;
}

/* 自顶向下的递归求解算法 */
int cut_rod(int n)
{
if(r[n] > 0)    //如果已经算过，直接返回
return r[n];
int temp = -1;
if(0 == n)      //长度为0的钢条价格为0
temp = 0;
//下面的循环递归求解长度为n的钢条的最大收益
for(int i = 1; i <= n; ++i)
{
int x = prices[i] + cut_rod(n - i);
if(x > temp)
temp = x;
}
r[n] = temp;
return temp;
}


#include <iostream>
#include <stdio.h>
#include <memory.h>
#define N 100
int prices[N];                          //长度为n的钢条的价格
int r[N];                               //长度为n时的最大收益
int cut_rod_bottom_up(int n);           //求最大收益

int main()
{
int n;
while(1 == scanf("%d", &n))
{
memset(r, -1, sizeof(r));
for(int i = 1; i <= n; ++i)
scanf("%d", &prices[i]);

printf("%d\nBest Cut:", cut_rod_bottom_up(n));
int x = 0;
//输出最优方案的切割位置
while(n > 0)
{
printf("%d ", x);
}
printf("\n");
}
return 0;
}
/* 自底向上的非递归求解算法 */
int cut_rod_bottom_up(int n)
{
r[0] = 0;
for(int i = 1; i <= n; ++i)
{
int x = 0;
//下面的循环，求解长度为i的钢条的最大收益
for(int j = 1; j <= i; ++j)
{
if(prices[j] + r[i-j] > x)
{
x = prices[j] + r[i-j];
}
}
r[i] = x;   //储存长度为i的钢条的最佳收益
}
return r[n];
}


11-25 1404

07-17 757

07-31 1175

11-01 1074

11-14 1356

03-08 972

04-10 1323

08-05 607

05-26 699

12-31 77