广告牌收益(回溯法)

题目:
在[0,M]处放置广告牌,位置收益自拟,两块广告牌之间距离要大于5,求最大收益

val = [3,5,6,5,1,10]
dist = [2,6,7,12,14,20]
bv = 0
pv = 0
pd = -1000
x = [0] * len(val)

def Backtrack(i,pv,bv,pd):
    global path
    if i == len(val):
        if pv > bv:
            bv = pv
            path = [x[i] for i in range(len(x))]
    else:
        if dist[i] - pd > 5:
            for j in range(2):
                x[i] = j
                pv += j * val[i]
                pd = pd * (1 - j) + dist[i] * j
                bv = Backtrack(i+1,pv,bv,pd)
                pv -= j * val[i]
        else:
            x[i] = 0
            bv = Backtrack(i+1,pv,bv,pd)
    return bv

bv = Backtrack(0,pv,bv,pd)
path = [dist[i] for i in range(len(path)) if path[i] == 1]

print("收益:\t"+'\t'.join([str(_) for _ in val]))
print("位置:\t"+'\t'.join([str(_) for _ in dist]))
print('最大收益是:%d' % bv)
print("位置分别为:"+'->'.join([str(_) for _ in path]))
    原文作者:回溯法
    原文地址: https://blog.csdn.net/chenxihou1/article/details/53697787
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞