利用python基于西北角法求解运输问题基本可行解的代码
时间: 2023-08-11 19:05:51 浏览: 161
以下是一个基于Python实现的西北角法求解运输问题的代码示例:
```python
# 定义运输问题的供应地和需求地
supply = [20, 30, 50] # 供应地的供应量
demand = [40, 20, 40, 10] # 需求地的需求量
# 定义运输问题的单位运输成本
cost = [
[2, 4, 5, 3],
[3, 5, 2, 1],
[6, 4, 2, 5],
]
# 初始化基本可行解
basic_feasible_solution = [[0 for j in range(len(demand))] for i in range(len(supply))]
# 利用西北角法求解基本可行解
i, j = 0, 0
while i < len(supply) and j < len(demand):
if supply[i] < demand[j]:
basic_feasible_solution[i][j] = supply[i]
demand[j] -= supply[i]
i += 1
else:
basic_feasible_solution[i][j] = demand[j]
supply[i] -= demand[j]
j += 1
# 输出基本可行解和总成本
total_cost = 0
for i in range(len(supply)):
for j in range(len(demand)):
if basic_feasible_solution[i][j] > 0:
total_cost += basic_feasible_solution[i][j] * cost[i][j]
print(basic_feasible_solution[i][j], end='\t')
print()
print("Total Cost:", total_cost)
```
该代码首先定义了一个运输问题的供应地、需求地和单位运输成本,然后利用西北角法求解基本可行解,并输出基本可行解和总成本。