【发布时间】:2018-08-28 19:20:22
【问题描述】:
我正在学习 CLRS 书中的杆切割算法。
我相信我理解其中的逻辑,并且我的以下解决方案已在 thisOJ 上被接受。
#include <climits>
#include <iostream>
using namespace std;
int prices[101];
int result[101];
int function(int length)
{
if (length == 0)
return 0;
if (result[length] != INT_MIN)
{
return result[length];
}
//calculate result for length
//if cutting the rod is more profitable, this variable will get overwritten in the loop below
int current_max = prices[length];
for (int cut_size = 1; cut_size < length; cut_size++)
{
int a;
int b;
a = function(cut_size); //this question is about this step
b = function(length - cut_size);
if (a + b > current_max)
current_max = a + b;
}
result[length] = current_max;
return current_max;
}
int main() {
int number_of_test_cases;
int length_of_rod;
cin>>number_of_test_cases;
while (number_of_test_cases--)
{
cin>>length_of_rod;
for (int i = 1; i <= length_of_rod; i++)
{
cin>>prices[i];
result[i] = INT_MIN;
}
//profit of cutting rod to size 1
result[1] = prices[1];
cout<<function(length_of_rod)<<endl;
}
return 0;
}
上面,我已经实现了书中解释的逻辑,除了稍作修改,这就是这篇文章的内容。
从书中,
1: let r[0..n] be a new array
2: r[0] = 0
3: for j = 1 to n
4: q = -1
5: for i = 1 to j
6: q = max(q, p[i] + r[j-i])
7: r[j] = q
8: return r[n]
p 是输入数组,其中包含杆长度从 1 到 n 的利润,r 用于存储结果。
为什么在第 6 行没有使用 r[i] 而不是 p[i],而 r[i] 已经包含长度为 i 的杆可以出售的最佳价格? r[i] 可能包含比 p[i] 更高的值,这意味着长度为 i 的杆在被切割后可以获得更高的价格,而不是单独出售。当然,对于循环的最后一次运行,当 i = j 并且长度为 j 的杆没有被切割时,它必须是 p[i],因为 r[j] 是正在计算的值,它没有'还不存在。但是当杆被切割时,我对循环的其他运行感到困惑。
我的解决方案通过这些语句使用逻辑 q = max(q, r[i] + r[j-i]) -
a = function(cut_size);
b = function(length - cut_size);
if (a + b > current_max)
current_max = a + b;
如果我根据书用a = prices[cut_size]修改它,它仍然在OJ上成功。
我在这里缺少什么?
【问题讨论】:
标签: algorithm dynamic-programming clrs