📅  最后修改于: 2023-12-03 15:41:55.065000             🧑  作者: Mango
运输问题是指在将一组物品从供应地运往需求地的物流问题中,寻求一种使得总运费最小的运输方案问题。而运输问题组合2是指采用西北角方法(即从左上角开始,按照往右或往下的方向填表),对于存在供应限制和需求限制的运输问题求解总运费最小的问题。
def northwest_corner_method(costs, supplies, demands):
"""使用西北角法求解运输问题
Args:
costs (list): 代表成本的二维数组
supplies (list): 一维数组,记录每个供应商的供给量
demands (list): 一维数组,记录每个顾客的需求量
Returns:
tuple: (最小总费用, 二维数组)
"""
num_supplies, num_demands = len(supplies), len(demands)
# 初始化结果矩阵和剩余需求和供给矩阵
result = [[0] * num_demands for _ in range(num_supplies)]
remain_supplies, remain_demands = deepcopy(supplies), deepcopy(demands)
# 西北角法
i, j = 0, 0
while i < num_supplies and j < num_demands:
if remain_supplies[i] < remain_demands[j]:
result[i][j] = remain_supplies[i]
remain_demands[j] -= remain_supplies[i]
remain_supplies[i] = 0
i += 1
else:
result[i][j] = remain_demands[j]
remain_supplies[i] -= remain_demands[j]
remain_demands[j] = 0
j += 1
# 计算总费用
total_cost = sum([result[i][j] * costs[i][j] for i in range(num_supplies)
for j in range(num_demands)])
return total_cost, result