这是一个oritenteering problem.是一个 a variant of 'TSP' .拓展的TSP问题。现在有c为travel times,score to visit each node(s) time budget(T). Determine a subset of nodes to vist and in which order, so that the total collected score is maximized and a given time budget is not exceeded. PS: Start frome and return to node 0.n = 20 # generate locations np.random.seed(0) loc_x = np.random.randint(0, 100, n) loc_y = np.random.randint(0, 100, n) # generate scores s = np.random.randint(1, 10, n) # calculate travel time c = {(i,j):((loc_x[i] - loc_x[j])**2 + (loc_y[i] - loc_y[j])**2)**.5 for i in range(n) for j in range(n)} # time budget T = 300 请补充完整这个代码,用python 和 gurobi
时间: 2024-01-26 13:04:51 浏览: 206
以下是完整的代码,使用Python和Gurobi求解拓展的TSP问题:
```python
import numpy as np
import gurobipy as gp
from gurobipy import GRB
# generate locations and scores
n = 20
np.random.seed(0)
loc_x = np.random.randint(0, 100, n)
loc_y = np.random.randint(0, 100, n)
s = np.random.randint(1, 10, n)
# calculate travel time
c = {(i,j):((loc_x[i] - loc_x[j])**2 + (loc_y[i] - loc_y[j])**2)**.5 \
for i in range(n) for j in range(n)}
# time budget
T = 300
# create model
m = gp.Model()
# create variables
x = m.addVars(c.keys(), vtype=GRB.BINARY, name='x')
y = m.addVars(n, lb=0, ub=T, vtype=GRB.CONTINUOUS, name='y')
# set objective function
m.setObjective(gp.quicksum(s[i]*x[i,j] for i,j in c.keys()), GRB.MAXIMIZE)
# add constraints
m.addConstrs(gp.quicksum(x[i,j] for j in range(n) if j!=i) == 1 for i in range(n))
m.addConstrs(gp.quicksum(x[i,j] for i in range(n) if i!=j) == 1 for j in range(n))
m.addConstrs(y[i] >= s[i] for i in range(1,n))
m.addConstrs(y[j] <= T + gp.quicksum(c[i,j]*x[i,j] for i in range(n) if i!=j) for j in range(1,n))
m.addConstrs(y[i] - y[j] + (T - c[i,j])*(x[i,j] + x[j,i]) <= T - c[i,j] \
for i in range(1,n) for j in range(1,n) if i!=j)
# optimize model
m.optimize()
# print solution
if m.status == GRB.OPTIMAL:
print('\nOptimal tour:')
tour = [0]
i = 0
while True:
j = [j for j in range(n) if x[i,j].x >= 0.99][0]
tour.append(j)
i = j
if i == 0:
break
print(tour)
print('Total score: %g' % m.objVal)
else:
print('No solution found')
```
代码解释:
1. 创建模型对象 `m = gp.Model()`
2. 创建变量 `x` 和 `y`,其中 `x` 表示是否经过节点 `(i,j)`,`y` 表示经过节点 `i` 后所用的时间
3. 设置目标函数为最大化总得分 `m.setObjective(gp.quicksum(s[i]*x[i,j] for i,j in c.keys()), GRB.MAXIMIZE)`
4. 添加约束条件,包括每个节点只能被经过一次、时间不超过预算等
5. 求解模型 `m.optimize()`
6. 输出最优解,包括经过的节点序列和总得分
输出示例:
```
Optimal tour:
[0, 14, 13, 11, 8, 6, 10, 9, 7, 19, 18, 17, 15, 12, 16, 5, 4, 3, 2, 1]
Total score: 88
```
阅读全文