旅行商问题(TSP)的启发式求解算法

2024-05-16 07:48

本文主要是介绍旅行商问题(TSP)的启发式求解算法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、TSP问题

TSP问题(Travelling Salesman Problem)即旅行商问题,又译为旅行推销员问题、货郎担问题,是数学领域中著名问题之一。假设有一个旅行商人要拜访n个城市,他必须选择所要走的路径,路径的限制是每个城市只能拜访一次,而且最后要回到原来出发的城市。路径的选择目标是要求得的路径路程为所有路径之中的最小值。

二、求解算法

从图论的角度来看,TSP问题实质是在一个带权完全无向图中,找一个权值最小的Hamilton回路。由于该问题的可行解是所有顶点的全排列,随着顶点数的增加,会产生组合爆炸,它是一个NP完全问题。
早期的研究者使用精确算法求解该问题,常用的方法包括:分枝定界法、线性规划法、动态规划法等。但是,随着问题规模的增大,精确算法将变得无能为力,因此,在后来的研究中,国内外学者重点使用近似算法或启发式算法,主要有遗传算法、模拟退火法、蚁群算法、禁忌搜索算法、贪婪算法和神经网络等。
下面使用遗传算法模拟退火法蚁群算法禁忌搜索算法贪婪算法 对TSP问题求近似解。
我们使用的TSP问题来自于TSPLIB上的att48,这是一个对称TSP问题,城市规模为48,其最优值为10628.其距离计算方法下所示:
这里写图片描述

首先定义几个通用类,类City表示城市,类CityManager表示旅行商需要拜访的所有城市,类Tour表示旅行商的行走路线。

public class City {int x;    //城市坐标xint y;    //城市坐标ypublic City(int x, int y){this.x = x;this.y = y;}public int getX(){return this.x;}public int getY(){return this.y;}/*** 计算两个城市之间的距离,距离计算方法由上图提供* @param city* @return*/public int distanceTo(City city){int xd = Math.abs(getX() - city.getX());int yd = Math.abs(getY() - city.getY());double rij = Math.sqrt( ( xd*xd + yd*yd ) / 10.0 );int tij = (int)Math.round(rij);if (tij < rij)return tij + 1;elsereturn tij;}@Overridepublic String toString(){return "(" + getX()+ "," + getY() + ")";}
}
import java.util.ArrayList;public class CityManager {//保存所有的目的城市private static ArrayList destinationCities = new ArrayList<City>();public static void addCity(City city) {destinationCities.add(city);}public static City getCity(int index){return (City)destinationCities.get(index);}// 获得城市的数量public static int numberOfCities(){return destinationCities.size();}}
import java.util.ArrayList;
import java.util.Collections;public class Tour{// 访问路线,保存需要访问的城市private ArrayList tour = new ArrayList<City>();// 构建一个空的路线public Tour(){for (int i = 0; i < CityManager.numberOfCities(); i++) {tour.add(null);}}// 用路线tour构建当前路线public Tour(ArrayList tour){this.tour = (ArrayList) tour.clone();}// 返回当前路线信息public ArrayList getTour(){return tour;}// 创建一个城市路线public void generateIndividual() {// 将目的城市一个个添加到当前路线中for (int cityIndex = 0; cityIndex < CityManager.numberOfCities(); cityIndex++) {setCity(cityIndex, CityManager.getCity(cityIndex));}// 把路线上城市的顺序打乱Collections.shuffle(tour);}// 从当前路线中获取指定位置的城市public City getCity(int tourPosition) {return (City)tour.get(tourPosition);}// 将一个目的城市放置到当前路线的指定位置public void setCity(int tourPosition, City city) {tour.set(tourPosition, city);}// 获得当前路线上所有城市距离的总和public int getDistance(){int tourDistance = 0;for (int cityIndex=0; cityIndex < tourSize(); cityIndex++) {City fromCity = getCity(cityIndex);City destinationCity;if(cityIndex+1 < tourSize()){destinationCity = getCity(cityIndex+1);}else{destinationCity = getCity(0);}tourDistance += fromCity.distanceTo(destinationCity);}return tourDistance;}// 获得路线上城市的数量public int tourSize() {return tour.size();}@Overridepublic String toString() {String geneString = "|";for (int i = 0; i < tourSize(); i++) {geneString += getCity(i)+"|";}return geneString;}
}

1. 模拟退火算法

模拟退火算法其实也是一种贪心算法,但是它的搜索过程引入了随机因素。模拟退火算法以一定的概率来接受一个比当前解要差的解,因此有可能会跳出这个局部的最优解,达到全局的最优解。以图1为例,模拟退火算法在搜索到局部最优解A后,会以一定的概率接受到E的移动。也许经过几次这样的不是局部最优的移动后会到达D点,于是就跳出了局部最大值A。模拟退火算法是一种随机算法,并不一定能找到全局的最优解,但可以比较快的找到问题的近似最优解。

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;public class SimulatedAnnealing {// Calculate the acceptance probabilitypublic static double acceptanceProbability(int energy, int newEnergy, double temperature) {// If the new solution is better, accept itif (newEnergy < energy) {return 1.0;}// If the new solution is worse, calculate an acceptance probabilityreturn Math.exp((energy - newEnergy) / temperature);}public static void initCities() throws IOException {BufferedReader br = new BufferedReader(new FileReader("att48.tsp"));String line = null;while ( (line = br.readLine()) != null ) {String[] token = line.split(" ");City city = new City(Integer.parseInt(token[1]), Integer.parseInt(token[2]));CityManager.addCity(city);}}public static void main(String[] args) {try {initCities();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return;}// Set initial tempdouble temp = 1000;// Cooling ratedouble coolingRate = 0.002;// Initialize intial solutionTour currentSolution = new Tour();currentSolution.generateIndividual();System.out.println("Initial solution distance: " + currentSolution.getDistance());// Set as current bestTour best = new Tour(currentSolution.getTour());// Loop until system has cooledwhile (temp > 1) {// Create new neighbour tourTour newSolution = new Tour(currentSolution.getTour());// Get a random positions in the tourint tourPos1 = (int) (newSolution.tourSize() * Math.random());int tourPos2 = (int) (newSolution.tourSize() * Math.random());while (tourPos1 == tourPos2 ) {tourPos2 = (int) (newSolution.tourSize() * Math.random());}// Get the cities at selected positions in the tourCity citySwap1 = newSolution.getCity(tourPos1);City citySwap2 = newSolution.getCity(tourPos2);// Swap themnewSolution.setCity(tourPos2, citySwap1);newSolution.setCity(tourPos1, citySwap2);// Get energy of solutionsint currentEnergy = currentSolution.getDistance();int neighbourEnergy = newSolution.getDistance();// Decide if we should accept the neighbourif (acceptanceProbability(currentEnergy, neighbourEnergy, temp) > Math.random()) {currentSolution = new Tour(newSolution.getTour());}// Keep track of the best solution foundif (currentSolution.getDistance() < best.getDistance()) {best = new Tour(currentSolution.getTour());}// Cool systemtemp *= 1-coolingRate;}System.out.println("Final solution distance: " + best.getDistance());System.out.println("Tour: " + best);}
}

这篇关于旅行商问题(TSP)的启发式求解算法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/994303

相关文章

解决pandas无法读取csv文件数据的问题

《解决pandas无法读取csv文件数据的问题》本文讲述作者用Pandas读取CSV文件时因参数设置不当导致数据错位,通过调整delimiter和on_bad_lines参数最终解决问题,并强调正确参... 目录一、前言二、问题复现1. 问题2. 通过 on_bad_lines=‘warn’ 跳过异常数据3

解决RocketMQ的幂等性问题

《解决RocketMQ的幂等性问题》重复消费因调用链路长、消息发送超时或消费者故障导致,通过生产者消息查询、Redis缓存及消费者唯一主键可以确保幂等性,避免重复处理,本文主要介绍了解决RocketM... 目录造成重复消费的原因解决方法生产者端消费者端代码实现造成重复消费的原因当系统的调用链路比较长的时

深度解析Nginx日志分析与499状态码问题解决

《深度解析Nginx日志分析与499状态码问题解决》在Web服务器运维和性能优化过程中,Nginx日志是排查问题的重要依据,本文将围绕Nginx日志分析、499状态码的成因、排查方法及解决方案展开讨论... 目录前言1. Nginx日志基础1.1 Nginx日志存放位置1.2 Nginx日志格式2. 499

kkFileView启动报错:报错2003端口占用的问题及解决

《kkFileView启动报错:报错2003端口占用的问题及解决》kkFileView启动报错因office组件2003端口未关闭,解决:查杀占用端口的进程,终止Java进程,使用shutdown.s... 目录原因解决总结kkFileViewjavascript启动报错启动office组件失败,请检查of

SpringBoot 异常处理/自定义格式校验的问题实例详解

《SpringBoot异常处理/自定义格式校验的问题实例详解》文章探讨SpringBoot中自定义注解校验问题,区分参数级与类级约束触发的异常类型,建议通过@RestControllerAdvice... 目录1. 问题简要描述2. 异常触发1) 参数级别约束2) 类级别约束3. 异常处理1) 字段级别约束

Python错误AttributeError: 'NoneType' object has no attribute问题的彻底解决方法

《Python错误AttributeError:NoneTypeobjecthasnoattribute问题的彻底解决方法》在Python项目开发和调试过程中,经常会碰到这样一个异常信息... 目录问题背景与概述错误解读:AttributeError: 'NoneType' object has no at

Spring的RedisTemplate的json反序列泛型丢失问题解决

《Spring的RedisTemplate的json反序列泛型丢失问题解决》本文主要介绍了SpringRedisTemplate中使用JSON序列化时泛型信息丢失的问题及其提出三种解决方案,可以根据性... 目录背景解决方案方案一方案二方案三总结背景在使用RedisTemplate操作redis时我们针对

Kotlin Map映射转换问题小结

《KotlinMap映射转换问题小结》文章介绍了Kotlin集合转换的多种方法,包括map(一对一转换)、mapIndexed(带索引)、mapNotNull(过滤null)、mapKeys/map... 目录Kotlin 集合转换:map、mapIndexed、mapNotNull、mapKeys、map

nginx中端口无权限的问题解决

《nginx中端口无权限的问题解决》当Nginx日志报错bind()to80failed(13:Permissiondenied)时,这通常是由于权限不足导致Nginx无法绑定到80端口,下面就来... 目录一、问题原因分析二、解决方案1. 以 root 权限运行 Nginx(不推荐)2. 为 Nginx

解决1093 - You can‘t specify target table报错问题及原因分析

《解决1093-Youcan‘tspecifytargettable报错问题及原因分析》MySQL1093错误因UPDATE/DELETE语句的FROM子句直接引用目标表或嵌套子查询导致,... 目录报js错原因分析具体原因解决办法方法一:使用临时表方法二:使用JOIN方法三:使用EXISTS示例总结报错原