简体   繁体   English

用GA解决TSP:距离矩阵是否应加快运行时间?

[英]Solving TSP with GA: Should a distance matrix speed up run-time?

I am trying to write a GA in Python to solve TSP. 我正在尝试用Python编写GA来解决TSP。 I would like to speed it up. 我想加快速度。 Because right now, it takes 24 seconds to run 200 generations with a population size of 200 . 因为现在, 人口总数为200的 200个世代需要24秒才能运行。

I am using a map with 29 cities . 我正在使用包含29个城市的地图。 Each city has an id and (x,y) coordinates. 每个城市都有一个ID和(x,y)坐标。

I tried implementing a distance matrix, which calculates all the distances once and stores it in a list. 我尝试实现一个距离矩阵,该矩阵一次计算所有距离并将其存储在列表中。 So instead of calculating the distance using the sqrt() function 1M+ times, it only uses the function 406 times. 因此,它没有使用sqrt()函数计算距离1M +次,而是仅使用函数406次。 Every time a distance between two cities is required, it is just retrieved from the matrix using the id of the two cities as the index. 每次需要两个城市之间的距离时,只需使用两个城市的id作为索引从矩阵中检索距离即可。

But even with this, it takes just as much time. 但是即使这样,它也需要花费很多时间。 I thought sqrt() would be more expensive than just indexing a list. 我认为sqrt()不仅比索引列表还要昂贵。 Is it not? 不是吗 Would a dictionary make it faster? 字典会使它更快吗?

The short answer: 简短的答案:

Yes. 是。 Dictionary would make it faster. 字典可以使其更快。

The long answer: 长答案:

Lets say, you pre-processing and calculates all distances once - Great! 可以说,您预处理并计算一次所有距离-太好了! Now, lets say I want to find the distance between A and B. So, all I have to do now is to find that distance where I put it - it is in the list! 现在,假设我要查找A和B之间的距离。因此,我现在要做的就是找到放置该距离的位置-它在列表中!

What is the time complexity to find something in the list? 在列表中查找内容的时间复杂度是多少? Thats right - O(n) 没错-O(n)

And how may times I'm going to use it? 以及我将如何使用它? My guess according to your question: 1M+ times 根据您的问题我的猜测:超过1M次

Now, that is a huge problem. 现在,这是一个巨大的问题。 I suggest you to use a dictionary so you could search in the pre-calculated distace between any two cities in O(1). 我建议您使用词典,以便搜索O(1)中任何两个城市之间的预先计算的距离。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM