以下是遺傳演算法(ga)解決旅行商問題(tsp)原始碼:
#include
#include
#include
#include
#include
using
namespace
std;
#define inf 1000
typedef
struct individual;
bool compare(individual a, individual b)
class sga
~sga();
void initial(int** a);
void select(int** a);
void variation();
void mutation();
void evolution(int** a);
void print();
void updatedata(int** a);
private:
vector
matingpool;
int popsize;//種群大小
int genlen;//基因長度,也即城市個數
int maxgener;//迭代代數
double pc;
double pm;
bool isnotexit(individual vc, int start, int end, int value);
vector
buildrandomsequence(int len);
};sga::sga()
bool sga::isnotexit(individual vc, int start, int len, int value)
//隨機產生序列,也即隨機產生個體
vector
sga::buildrandomsequence(int length)
return vc;
}//更新每個個體的fitness
void sga::updatedata(int** a)
for (size_t tt = 0; tt < matingpool.size(); tt++)
}//初始化種群
void sga::initial(int** a)
updatedata(a);
}void sga::select(int** a)
matingpool.clear();
double rate;
double ff = 0.0;
srand((unsigned)time(null));
while (1)
ff += vcida[i].percentage;
}ff = 0.0;
if (matingpool.size() == popsize) break;
}updatedata(a);
}void sga::variation()
int i,j;
srand((unsigned)time(null));
int start = rand() % (genlen - 3);
int length = rand() % (genlen - start);
individual a, b,o1,o2;
vector
ttp;
for (i = 0; i != 2 * pcd; i+=2)
for (j = 0; j < start; j++)
for (j = start+length; j < genlen; j++)
ttp.clear();
for (j = 0; j != genlen; j++)
for (j = 0; j < start; j++)
for (j = start + length ; j < genlen; j++)
matingpool.push_back(o1);
matingpool.push_back(o2);
}crw.clear();
ttp.clear();
}//突變操作
void sga::mutation()
}//進化操作
void sga::evolution(int** a)
}void sga::print()
}cout
<< "最短距離: "
<< matingpool[k].pathl << endl;
cout
<< "最短路徑: " ;
for (i = 0; i < genlen; i++) cout
<< matingpool[k].chrom[i] << " ";
cout
<< matingpool[k].chrom[0];
cout
<< endl;
}sga::~sga()
TSP 旅行商問題 遺傳演算法
問題描述 對於n組城市座標,尋找最短路徑使其經過所有城市並回到起點。問題資料集 tsp.eil51問題1 37 52 2 49 49 3 52 64 4 20 26 5 40 30 6 21 47 7 17 63 8 31 62 9 52 33 10 51 21 11 42 41 12 31 32 ...
遺傳演算法解決旅行商問題 TSP (實驗課)
在旅行商問題中,給定一組城市及每座城市與其他城市之間的旅行成本,目標是找出一條經過所有城市的路徑,要求該路徑只經過每座城市一次並且旅行總成本最低。從任意一座城市出發,經過每一座城市之後,再回到出發城市結束旅行。課上給的距離矩陣,可能是疏忽9到3和3到9的距離不一致,但這不妨礙程式設計 include...
C語言編寫遺傳演算法解決TSP旅行商問題
最近在上計算智慧型的課,老師剛剛教了遺傳演算法,布置了用遺傳演算法解決tsp的問題的作業,於是經過幾小時的奮戰,終於編寫完成。首先先對tsp問題進行分析。tsp問題,也就是旅行商問題,題目的大題內容是 一位旅行商,要遍遊n座城市 城市數量記為num city 已知每兩座城市之間的位置,要求每座城市必...