如comments 中所述,您可以为此使用图形搜索算法,例如Dijkstra's algorithm。也可以使用A*,但为了这样做,您需要一个好的启发式函数。使用最低价格可能会奏效,但现在,让我们坚持使用 Dijkstra 的。
图中的一个节点表示为(cost, num, counts) 的元组,其中cost 显然是成本,num 是购买的物品总数,counts 是每个物品数量的细分卖方。 cost 是元组中的第一个元素,成本最低的项目将始终位于 heap 的前面。如果卖家的当前计数低于最小值,我们可以通过添加费用来处理“额外费用”,并在达到最小值后再次减去。
这是一个简单的 Python 实现。
import heapq
def find_best(goal, num_cheap, pay_extra, price, items):
# state is tuple (cost, num, state)
heap = [(0, 0, tuple((seller, 0) for seller in price))]
visited = set()
while heap:
cost, num, counts = heapq.heappop(heap)
if (cost, num, counts) in visited:
continue # already seen this combination
visited.add((cost, num, counts))
if num == goal: # found one!
yield (cost, num, counts)
for seller, count in counts:
if count < items[seller]:
new_cost = cost + price[seller] # increase cost
if count + 1 < num_cheap: new_cost += pay_extra # pay extra :(
if count + 1 == num_cheap: new_cost -= (num_cheap - 1) * pay_extra # discount! :)
new_counts = tuple((s, c + 1 if s == seller else c) for s, c in counts)
heapq.heappush(heap, (new_cost, num+1, new_counts)) # push to heap
以上是一个生成器函数,即您可以使用next(find_best(...)) 找到最佳组合,或者遍历所有组合:
price = {1: 17, 2: 18, 3: 23}
items = {1: 1, 2: 3, 3: 5}
for best in find_best(5, 4, 5, price, items):
print(best)
正如我们所见,购买五件商品还有一个更便宜的解决方案:
(114, 5, ((1, 1), (2, 0), (3, 4)))
(115, 5, ((1, 0), (2, 0), (3, 5)))
(115, 5, ((1, 0), (2, 1), (3, 4)))
(119, 5, ((1, 1), (2, 3), (3, 1)))
(124, 5, ((1, 1), (2, 2), (3, 2)))
(125, 5, ((1, 0), (2, 3), (3, 2)))
(129, 5, ((1, 1), (2, 1), (3, 3)))
(130, 5, ((1, 0), (2, 2), (3, 3)))
更新 1:虽然上述示例适用于上述示例,但 可能 在某些情况下它会失败,因为一旦达到最小数量就减去额外成本意味着我们可以拥有 边负成本,这在 Dijkstra 中可能是个问题。或者,我们可以在一个“动作”中一次添加所有四个元素。为此,将算法的内部部分替换为:
if count < items[seller]:
def buy(n, extra): # inner function to avoid code duplication
new_cost = cost + (price[seller] + extra) * n
new_counts = tuple((s, c + n if s == seller else c) for s, c in counts)
heapq.heappush(heap, (new_cost, num + n, new_counts))
if count == 0 and items[seller] >= num_cheap:
buy(num_cheap, 0) # buy num_cheap in bulk
if count < num_cheap - 1: # do not buy single item \
buy(1, pay_extra) # when just 1 lower than num_cheap!
if count >= num_cheap:
buy(1, 0) # buy with no extra cost
更新 2:此外,由于将商品添加到“路径”的顺序无关紧要,我们可以将卖家限制为不在当前卖家之前的卖家。我们可以将for seller, count in counts: 循环添加到他的:
used_sellers = [i for i, (_, c) in enumerate(counts) if c > 0]
min_sellers = used_sellers[0] if used_sellers else 0
for i in range(min_sellers, len(counts)):
seller, count = counts[i]
通过这两项改进,探索图中的状态会像这样查找next(find_best(5, 4, 5, price, items))(点击放大):
请注意,有许多“低于”目标状态的状态,成本要高得多。这是因为这些都是已添加到队列中的状态,并且对于这些状态中的每一个,前驱状态仍然优于最佳状态,因此它们被扩展并添加到队列中,但从未真正从队列中弹出。其中许多可能可以通过使用带有启发式函数(如items_left * min_price)的 A* 来消除。