【发布时间】:2014-11-13 07:05:59
【问题描述】:
所以我一直在研究这个问题,它与选择具有给定约束的最大子数组有关。问题如下:
Yuckdonalds 正在考虑在 Quaint Valley Highway 沿线开设一系列餐厅 (QVH)。可能的位置在一条直线上,并且这些位置的距离 从 QVH 开始的位置,以英里为单位,按升序排列, 米1;平方米; : : : ; mn
约束如下: 在每个地点,Yuckdonalds 最多可开设一家餐厅。预期的 在当地开餐厅获利 i 是 pi,其中 pi > 0 且 i = 1;2; : : : ; n
任何两家餐馆都应该至少相距 k 英里,其中 k 是一个正整数。
我已将排序后的数组 M 视为二进制堆,我的算法包括遍历二进制堆的每个索引(在数组 M 中)并选择其左/右子节点的最大值,只要它满足距离约束 k。然后用索引的左右孩子递归调用函数。
似乎我正在选择一些最佳指标,因为这是输出所暗示的,但我遗漏了一些东西,但我无法弄清楚是什么。 PS。这不是给学校的,那是一个多月前的事了,我现在正在编码它是为了好玩,我知道我的 tempProfit 变量现在没用了
def binHandle(parent, M, P, tmp, lc):
lastchosen = lc
i = parent
left = 2*i
right = 2*i + 1
if left > len(M):
return
parent = M[parent]
if right <= len(M) and left < len(M):
childRestL = M[left]
childRestR = M[right]
#choose best child
if distance(lastchosen, childRestL) >= k:
if P[right] > P[left]:
outcome = P[right]
lastchosen = M[right]
tmp += outcome
print outcome
binHandle(right , M, P, tmp, lastchosen)
else:
outcome = P[left]
lastchosen = M[left]
tmp += outcome
print outcome
binHandle(left , M, P, tmp, lastchosen)
def maxprofits(M, P, k):
maxProf = 0
global tempProfit
tempProfit = 0
n = 1
#test each index in array
for n in range(1, len(M)):
binHandle(n, M, P, tempProfit, 0)
if tempProfit > maxProf:
maxProf = tempProfit
tempProfit = 0
return maxProf
编辑:弄明白了
【问题讨论】:
-
为什么要投反对票,这个问题写得很好,而且很努力?! ...
标签: python arrays algorithm dynamic-programming