我已经为多重旅行推销员问题(mTSP)创建了一个解决方案。我的下一个目标是从现有的解决方案中实现一个2-opt算法。下面是我的代码片段:
for j in range(len(solutions[i].nodes)-3):
for k in range(j+2, len(solutions[i].nodes)-1):
dist_a = graph.edges[solutions[i].nodes[j], solutions[i].nodes[j + 1]]['weight']
dist_b = graph.edges[solutions[i].nodes[k], solutions[i].nodes[k + 1]]['weight']
dist_c = graph.edges[solutions[i].nodes[j], solutions[i].nodes[k]]['weight']
dist_d = graph.edges[solutions[i].nodes[j + 1], solutions[i].nodes[k + 1]]['weight']
if dist_a + dist_b > dist_c + dist_d:
solutions[i].nodes[j + 1: k + 1] = reversed(solutions[i].nodes[j + 1: k + 1])
solutions[i].cost += (dist_c + dist_d - dist_a - dist_b)
solutions[i].path = []
for l in range(x):
solutions[i].path.append((solutions[i].nodes[l], solutions[i].nodes[(l + 1) % len(solutions[i].nodes)]))
这很有效。但是,如果我将代码稍微更改为更高的整数减法,例如for j in range(len(solutions[i].nodes)-4)
,有时它将生成比for j in range(len(solutions[i].nodes)-3
低成本的解决方案。这怎么会发生?有人能解释一下吗?提前谢谢
目前没有回答
相关问题 更多 >
编程相关推荐