随机算法——蒙特卡洛算法——TSP问题

1 简单介绍

在这里插入图片描述

2 随机算法 在这里插入图片描述

3 算法 描述

在这里插入图片描述

5 代码

  • 本代码默认城市数为5
  • 为了城市数作为下表,默认边边距离从1开始
  • 可以从城市数自定义、边与边距离自定义、记录多条最优路径等改进代码
  • 随机生成路径的方式还有很多,可以改进。
也许你会想怎么处理的两点无边的情况:
  1. so easy,只需要将两点无边的情况,让他有一个超级大的边,这样看似右边,实则无边。
  2. 因为要计算的是路径最小化,这么大的边即使被计算过,一定会被pass。
#include <iostream>
#include<algorithm> 
using namespace std;
int city[5] = {1, 2, 3, 4, 5};
int cityNum = 5;
int path[5]={1, 2, 3, 4, 5}; //路径	
int edge[6][6] = 
	{-1,-1,-1,-1,-1,-1,
	 -1, 0, 1, 3, 4, 5,
	 -1, 1, 0, 1, 2, 3,
	 -1, 3, 1, 0, 1, 2,
	 -1, 4, 2, 1, 0, 1,
	 -1, 5, 3, 2, 1, 0};
 int edge1[6][6] = 
	{-1,-1,-1,-1,-1,-1,
	 -1, 0, 1,10,10, 5,
	 -1, 1, 0, 2, 1, 1,
	 -1,10, 2, 0, 3,10,
	 -1,10, 1, 3, 0, 4,
	 -1, 5, 1,10, 4, 0};

//计算随机路径的距离 
int distance(){
	int sumdist = 0;
	for(int i=0;i<cityNum-1;i++){
		sumdist+= edge[path[i]][path[i+1]];	
	}
	//加上从末点到始点的距离
	sumdist+= edge[path[cityNum-1]][path[0]];
	return sumdist;
}

//生成随机路径path 
void randomPath(){ 
	for(int i = 0; i < cityNum; i++){
 		int j = rand()%cityNum;
   		swap(path[i],path[j]);
 	}
}

//copy path to bestpath
void copy(int bestpath[]){
	for(int i=0;i<cityNum;i++){
		bestpath[i]=path[i];
	}
} 

//打印随机路径 
void display(){
	cout<<"the random path is:";
	for(int i=0;i<cityNum;i++)
		cout<<path[i]<<" ";
	cout<<endl;
} 

int main(int argc, char *argv[]){
 	cout<<"原始边矩阵:"<<endl; 
	for(int i=0;i<5;i++){
		printf("%d %d %d %d %d\n",edge[i][0],edge[i][1],edge[i][2],edge[i][3],edge[i][4]);
	}
	
	int iteration = 1000;
	
	int bestPath[cityNum];
	int minDist=1000;   //初始1000代表无穷大 
	for(int i=0;i<iteration;i++){
		randomPath();//获取随机路径
		display(); 
		int curDist=distance(); 
		cout<<"该随机路径的长度: "<<curDist<<endl; 
		if(curDist<minDist){
			minDist=curDist;
			copy(bestPath);
		}
	}
	
	cout<<"the minDist is "<<minDist<<" the best path is:";
	for(int i=0;i<cityNum;i++)
		cout<<bestPath[i]<<" ";
	cout<<endl;
	
	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值