?? main.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},{1, 8, 3, 1, 2, 0, 3, 3, 9, 5, 4, 5, 2, 7, 3, 6, 2, 3, 7, 1},{3, 3, 7, 5, 3, 3, 0, 7, 5, 9, 3, 4, 5, 9, 3, 7, 3, 2, 8, 1},{7, 4, 9, 2, 1, 3, 7, 0, 1, 3, 4, 5, 2, 7, 6, 3, 3, 8, 3, 5},
{2, 2, 1, 9, 4, 9, 5, 1, 0, 1, 3, 4, 7, 3, 7, 5, 9, 2, 1, 7},{9, 4, 2, 1, 6, 5, 9, 3, 1, 0, 3, 7, 3, 7, 4, 9, 3, 5, 2, 5},{7, 4, 5, 3, 3, 4, 3, 4, 3, 3, 0, 5, 7, 8, 4, 3, 1, 5, 9, 3},{3, 6, 8, 5, 8, 5, 4, 5, 4, 7, 5, 0, 8, 3, 1, 5, 8, 5, 8, 3},
{4, 2, 1, 7, 4, 2, 5, 2, 7, 3, 7, 8, 0, 5, 7, 4, 8, 3, 5, 3},{5, 8, 8, 3, 5, 7, 9, 7, 3, 7, 8, 3, 5, 0, 8, 3, 1, 8, 4, 5},{8, 2, 9, 4, 2, 3, 3, 6, 7, 4, 4, 1, 7, 8, 0, 4, 2, 1, 8, 4},{9, 9, 4, 7, 8, 6, 7, 3, 5, 9, 3, 5, 4, 3, 4, 0, 4, 1, 8, 4},
{2, 4, 7, 3, 1, 2, 3, 3, 9, 3, 1, 8, 8, 1, 2, 4, 0, 4, 3, 7},{8, 5, 4, 4, 7, 3, 2, 8, 2, 5, 5, 5, 3, 8, 1, 1, 4, 0, 2, 6},{2, 2, 8, 5, 4, 7, 8, 3, 1, 2, 9, 8, 5, 4, 8, 8, 3, 2, 0, 4},{8, 1, 4, 2, 7, 1, 1, 5, 7, 5, 3, 3, 3, 5, 4, 4, 7, 6, 4, 0}};
vector<vector<float> > map(lchrom);
vector<float> tmp(lchrom);
for(int i=0;i<lchrom;++i)
{
tmp.assign(dist[i],dist[i]+lchrom);
map[i] = tmp;
}
pair<vector<int>,float> result;
//輸出配置信息
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 + -