【发布时间】:2015-04-12 05:24:12
【问题描述】:
给你一个长度为“n”的木头。日志上有“m”标记。必须在每个标记处切割原木。切割成本等于被切割原木的长度。给定这样的原木,确定切割成本最低。
我的部分解决方案是使用递归: 当我按顺序进入标记阵列时,即从第 0 次切割到阵列切割结束时,我能够获得成本。然而,当我们不按顺序切割时,我被困在如何为序列编写代码,即在随机序列中,例如代码可以解释切割不按顺序的情况,并为所有这些情况取最大值。
一种解决方案是对标记数组进行所有排列。为所有排列调用木刻函数并取最大值,但这似乎是幼稚的方法。
有什么建议吗?
标记 = [2, 4](切割点)
int woodcut(length, cut_point, index){
if (cut_point > length)
return INFINITY
first_half = cut_point;
second_half = length - cut_point
if (markings[index++] == exist) {
if (next_cut_point > first)
cost = length + woodcut(second_half, next_cut_point-first)
else
cost = length + woodcut(first_half, next_cut_point)
} else if (index >= sizeof(markings))
return cost;
}
http://www.careercup.com/question?id=5188262471663616
在查找答案并在一些慷慨的人的帮助下,我能够编写以下解决方案:
#include <stdio.h>
int min(int a, int b)
{
return a>b?b:a;
}
int min_cut(int first, int last, int size, int *cuts)
{
int i;
unsigned int min_cost = 1U<<30;
/* there are no cuts */
if (size == 2)
return 0;
/* there is only one cut between the end points */
if (size == 3)
return last - first;
/* cut at all the positions and take minimum of all */
for (i=1;i<size;i++) {
if (cuts[i] > first && cuts[i] < last) {
int cost = last-first + min_cut(first, cuts[i], i+1, cuts) +
min_cut(cuts[i], last, size - i, cuts);
min_cost = min(cost, min_cost);
}
}
return min_cost;
}
int main()
{
int cuts[] = {0, 2, 4, 7, 10};
int size = sizeof(cuts)/sizeof(cuts[0]);
printf("%d", min_cut(cuts[0], cuts[size-1], size, cuts));
return 0;
}
【问题讨论】:
-
您的问题可以使用格式。 stackoverflow.com/editing-help
-
您应该说明问题的根源,并在可能的情况下提供链接。
-
@DouglasZare:没有来源。我是从参加谷歌面试的人问到的职业杯网站上得到的。
-
这是一个来源。您应该在问题陈述中包含这一点,并链接到讨论该问题的职业杯网站。
-
再次,您可以编辑问题以包含该问题。这至少有两个好处。首先,它可以让有兴趣的人看到其他人在该线程上提出的解决方案,以避免重复工作。其次,适当的归因意味着您不会试图声称发明问题的功劳。
标签: algorithm recursion dynamic-programming