⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 main.cpp

📁 经典的用遗传算法解决TSP问题
💻 CPP
字号:
/*
用遗传算法(GA)解决TSP(旅行商)问题
完成时间:2005.8.2
编译环境:VC7.1 (用VC6的话需要修改几处,要把hash_map改为map)

作者:西南科技大学   唐坤(sf.tk)
QQ: 226152161
Blog: blog.gameres.com/show.asp?BlogID=1450&column=0
E-mail: starsftk@yahoo.com.cn

ps:初学遗传算法,很多都不懂,程序还有很多不足,若你改进了别忘了告诉我
*/

#include "GA.h"
#include "o_time.h"
#include <iostream>
const int lchrom = 20;
float pcross = 0.65;     //交叉率
float pmutation = 0.2;  //变异率
int popsize = 300;      //种群大小	
int maxgen = 300;    //最大世代数	

int main()
{
	cout<<"*************用遗传算法解决TSP(旅行商)问题******************"<<endl;
	//用矩阵保存各城市间的路程开销
	/*float dist[lchrom][lchrom] = {{0,8,5,4,1,2,3,1,5,6},{8,0,4,6,7,1,6,5,4,1},{5,4,0,3,1,2,9,8,1,5},{4,6,3,0,2,1,8,1,9,6},{1,7,1,2,0,5,6,1,3,4},
	{2,1,2,1,5,0,7,3,2,8},{3,6,9,8,6,7,0,1,3,1},{1,5,8,1,1,3,1,0,9,2},{5,4,1,9,3,2,3,9,0,8},{6,1,5,6,4,8,1,2,8,0}};*/
	float dist[lchrom][lchrom] ={{0, 1, 4, 6, 8, 1, 3, 7, 2, 9, 7, 3, 4, 5, 8, 9, 2, 8, 2, 8},{1, 0, 7, 5, 3, 8, 3, 4, 2, 4, 4, 6, 2, 8, 2, 9, 4, 5, 2, 1},{4, 7, 0, 3, 8, 3, 7, 9, 1, 2, 5, 8, 1, 8, 9, 4, 7, 4, 8, 4},{6, 5, 3, 0, 3, 1, 5, 2, 9, 1, 3, 5, 7, 3, 4, 7, 3, 4, 5, 2},
	{8, 3, 8, 3, 0, 2, 3, 1, 4, 6, 3, 8, 4, 5, 2, 8, 1, 7, 4, 7},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信息
	cout<<"\n染色体长度:"<<lchrom<<"\n种群大小:"<<popsize<<"\n交叉率:"<<pcross<<"\n变异率:"<<pmutation;
	cout<<"\n最大世代数:"<<maxgen<<endl;

	//输出路径信息
	cout<<endl<<"  ";
	for(int i=0;i<lchrom;i++)
		cout<<i<<" ";
	cout<<endl;		
	for(int i=0;i<lchrom;i++)
	{
		cout<<i<<":";
		for(int j=0;j<lchrom;j++)
		{
			cout<<map[i][j]<<" ";
		}
		cout<<endl;
	}
	cout<<endl;	

	our::Time time; //测时对象
	//关键部分
	CGA ga;
	time.start();
	result = ga.start(map,pcross,pmutation,popsize,maxgen);
	//
	time.end();
	cout<<"耗时:"<<time.time_milli()<<" s"<<endl<<"最优路径:";
	copy(result.first.begin(), result.first.end(), ostream_iterator<int>(cout,"->"));
	cout<<endl<<"开销:"<<result.second<<endl;

	system("pause");
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -