Routes
所有可能的路线,而你只有
cost_to_send
为某些路线定义。
路线
Routes = [(i, j) for i in origin for j in destination if j in cost_to_send[i]]
我能看到的另一个问题是第二组约束:
for i in origin:
prob += lpSum(quantity[i][j] for j in destination) == 1
所有目的地必须只有一个来源,而不是所有来源
必须使用
from pulp import *
import pandas as pd
origin = ["a","b","c","d","e","f","g","h"]
destination = ["1","2","3","4","5","6","7","8","9","10"]
offer = {"a":3,"b":3,"c":3,"d":3,"e":3,"f":4,"g":3,"h":3}
demand = {"1":1,"2":1,"3":1,"4":1,"5":1,"6":1,"7":1,"8":1,"9":1,"10":1}
cost_to_send = {
"a":{"1":1,"2":1,"3":1},
"b":{"2":1,"3":1,"9":1},
"c":{"5":1,"6":1,"7":1},
"d":{"7":1,"9":1,"10":1},
"e":{"3":1,"6":1,"8":1},
"f":{"1":1,"4":1,"7":1,"9":1},
"g":{"4":1,"5":1,"9":1},
"h":{"1":1,"4":1,"8":1}
}
prob = LpProblem("Exercise", LpMinimize)
# Routes = [(i,j) for i in origin for j in destination]
Routes = [(i, j) for i in origin for j in destination if j in cost_to_send[i]]
quantity = LpVariable.dicts("quantity de envio",Routes,0)
prob += lpSum(quantity[(i,j)]*cost_to_send[i][j] for (i,j) in Routes)
for j in destination:
prob += lpSum(quantity[(i,j)] for i in origin if (i,j) in Routes) == demand[j]
#for i in origin:
# prob += lpSum(quantity[i][j] for j in destination) == 1
prob.solve()
print("Status: ", LpStatus[prob.status])
for v in prob.variables():
if v.varValue > 0:
print(v.name, "=", v.varValue)
print("Answer ", value(prob.objective))
Returns:
Status: Optimal
quantity_de_envio_('a',_'1') = 1.0
quantity_de_envio_('a',_'2') = 1.0
quantity_de_envio_('a',_'3') = 1.0
quantity_de_envio_('b',_'9') = 1.0
quantity_de_envio_('c',_'5') = 1.0
quantity_de_envio_('c',_'6') = 1.0
quantity_de_envio_('d',_'10') = 1.0
quantity_de_envio_('f',_'4') = 1.0
quantity_de_envio_('f',_'7') = 1.0
quantity_de_envio_('h',_'8') = 1.0
Answer 10.0
请注意,如果您希望对一个给定的目的地有大于1的请求,但是希望强制目的地只接收来自单个源的输入,那么您需要添加
二元的