《遗传算法解决TSP问题(C++)》由会员分享,可在线阅读,更多相关《遗传算法解决TSP问题(C++)(10页珍藏版)》请在人人文库网上搜索。
1、遗传算法解决TSP问题(C+版)遗传算法流程:交叉,编译,计算适应度,保存最优个体。其中交叉过程是选择最优的两个染色体进行交叉操作,本文采用的是轮盘赌算法。#include #include #include using namespace std;#define population 200/种群数量#define pc 0.9/交叉的概率#define pm 0.1/变异的概率#define count 200/迭代的次数#define num 10/城市的数量int* city;/存放每个个体的访问顺序int path1010 = /0, 1, 2, 3, 4, 5, 6, 7, 8, 。
2、9 0, 23, 93, 18, 40, 34, 13, 75, 50, 35 ,/0 23, 0, 75, 4, 72, 74, 36, 57, 36, 22 ,/1 93, 75, 0, 64, 21, 73, 51, 25, 74, 89 ,/2 18, 4, 64, 0, 55, 52, 8, 10, 67, 1 , /3 40, 72, 21, 55, 0, 43, 64, 6, 99, 74 , /4 34, 74, 73, 52, 43, 0, 43, 66, 52, 39 ,/5 13, 36, 51, 8, 64, 43, 0, 16, 57, 94 ,/6 75, 57, 。
3、25, 10, 6, 66, 16, 0, 23, 11 , /7 50, 36, 74, 67, 99, 52, 57, 23, 0, 42 ,/8 35, 22, 89, 1, 74, 39, 94, 11, 42, 0 /9;int* dis;/存放每个个体的访问顺序下的路径长度double* fitness;/存放灭个个体的适应度int min_dis = ;int min_index = -1;int* min_path;/初始化种群void init()int *a = new intnum;for (int i = 0; i= 0; j-)int n = rand() % (j 。
4、+ 1);/产出的数是0-j,保证交换的后面的数不会再被交换swap(aj, an);/保证a里面全是0-(num-1)的数,无重复的数,只是顺序颠倒cityij = aj;deletea;dis = new intpopulation;fitness = new doublepopulation;min_path = new intnum;/计算适应度void compute()/cout disi)result = disi;index = i;return index;int getMaxDis()int result = dis0;int index = 0;for (int i = 。
5、1; ip2)swap(p1, p2);/cout disi)result = disi;index = i;return result;/释放申请的数组的空间void dispose()for (int i = 0; ipopulation; i+)deletecityi;deletecity;deletedis;deletefitness;int main()init();/初始化种群int i = 0;srand(time(0);compute();while (icount)cross();/交叉morphis();/变异compute();/计算适应度save();/保存当前最优的个体/cout count i+ endl;cout getdis() ;/输出结果/cout min_index ;if (+i % 10 = 0)cout endl;compute();cout min distance is: min_dis endl;for (int i = 0; inum; i+)cout min_pathi ;cout endl;dispose();/释放空间return 0。