心血来潮把GA_TSP问题用C++封装起来搞了一遍,期间真是收益不小。
主要是用STL中的vector和list,结构体赋值中遇到了一些难点,原谅我自己是一棵白菜。
选择方法:用种群前面最优的20%代替后面的20%进行淘汰(当然这个比例可以自己拟定,修改代码中得pm_即可)。
变异方法:交换一个路径上随机产生的两个城市。
交叉方法:三交换启发交叉(THGA)。
genticTsp.h 代码如下:
1 #ifndef GENTIC_TSP_H_ 2 #define GENTIC_TSP_H_ 3 #include <iostream> 4 #include <vector> 5 #include <string> 6 #define CITIES 99 7 #define UNITS 50 8 #define MAX_GEN 15 9 10 11 struct city{ 12 int id; 13 int x; 14 int y; 15 }; 16 17 struct unit{ 18 double length; 19 std::vector<int> path; 20 bool operator<(const struct unit &other) const 21 { 22 return length < other.length; 23 } 24 }; 25 26 27 class GenticTSP{ 28 public: 29 GenticTSP(); 30 void initMatrix(const std::string &filename);//file to matrix 31 void initGroup();//shuffle a group 32 double lenOfUnit(unit &p);// 33 int searchCity(unit &, int id);//search a city's id for cross 34 void selectGroup(); 35 void crossUnits(unit &p, unit &q, unit &r); 36 void mutateGroup(); 37 void evoluteGroup(); 38 void printBestUnit(); 39 ~GenticTSP(); 40 private: 41 unit bestUnit_; 42 double pm_;// mutate probability 43 double ps_;//save probability 44 45 }; 46 47 #endif /*GENTIC_TSP_H_*/