《(完整版)遗传算法(C++版).doc》由会员分享,可在线阅读,更多相关《(完整版)遗传算法(C++版).doc(8页珍藏版)》请在金锄头文库上搜索。
1、#include #include #include #include #include using namespace std;const int city_num = 10;/城市数量const int unit_num = 100;/群体规模int ps = 10;/变异概率const int genmax = 500;/最大迭代数/城市间距离映射 最优解权值=10int length_table1010 = 0,1,1272,2567,1653,2097,1425,1177,3947,1, 1,0,1,2511,1633,2077,1369,1157,3961,1518, 1272,1
2、,0,1,380,1490,821,856,3660,385, 2567,2511,1,0,1,2335,1562,2165,3995,933, 1653,1633,380,1,0,1,1041,1135,3870,456, 2097,2077,1490,2335,1,0,1,920,2170,1920, 1425,1369,821,1562,1041,1,0,1,4290,626, 1177,1157,856,2165,1135,920,1,0,1,1290, 3947,3961,3660,3995,3870,2170,4290,1,0,1, 1,1518,385,993,456,1920,
3、626,1290,1,0;class Unitpublic: int pathcity_num;/个体的路径信息 int length;/个体价值;class Grouppublic: Unit groupunit_num; Unit best; int best_gen; Group() best.length = 0x3f3f3f3f; best_gen = 0; for(int i = 0; i unit_num; i+) bool flagcity_num = ; for(int j = 0; j city_num; j+) int t_city = rand()%city_num;
4、while(flagt_city) t_city = rand()%city_num; flagt_city = true; groupi.pathj = t_city; /对每个个体进行评估 void assess() for(int k = 0; k unit_num; k+) int rel = 0; for(int i = 1; i city_num; i+) rel += length_tablegroupk.pathi-1groupk.pathi; rel += length_tablegroupk.pathcity_num-1groupk.path0; groupk.length
5、 = rel; /根据评估结果对个体进行排序 void unit_sort() for(int i = 0; i unit_num; i+) for(int j = i+1; j groupj.length) Unit temp; memcpy(&temp, &groupi, sizeof(Unit); memcpy(&groupi, &groupj, sizeof(Unit); memcpy(&groupj, &temp, sizeof(Unit); /交叉 Unit cross(Unit &father, Unit &mother) int l = rand()%city_num; int
6、 r = rand()%city_num; if(l r) swap(l, r); bool flagcity_num = ; for(int i = l; i = r; i+) flagfather.pathi = true; Unit son; int pos = 0; for(int i = 0; i l; i+) while(flagmother.pathpos) pos+; son.pathi = mother.pathpos+; for(int i = l; i = r; i+) son.pathi = father.pathi; for(int i = r+1; i ps) re
7、turn; int one = rand()%city_num; int two = rand()%city_num; while(two != one) two = rand()%city_num; swap(t.pathone, t.pathtwo); /输出信息 void print() for(int i = 0; i unit_num; i+) printf(第%d个个体,路径信息:, i); for(int j = 0; j city_num; j+) printf(%d , groupi.pathj); printf(;总权值:%d;n, groupi.length); prin
8、tf(最优个体,路径信息:); for(int j = 0; j city_num; j+) printf(%d , group0.pathj); printf(;总权值:%d;n, group0.length); /种群进化 void work() for(int i = 0; i 20) ps *= 3; assess();/评估 unit_sort();/根据评估结果排序 if(best.length group0.length) memcpy(&best, &group0, sizeof(group0); best_gen = i; for(int j = 0; j+2 unit_nu
9、m; j+=3) groupj+2 = cross(groupj, groupj+1); for(int j = 0; j city_num; j+)/变异(从1开始,保留最优) mutation(groupj); ;Unit groupunit_num;/种群变量Unit bestone;/记录最短路径int generation_num;/记录当前达到了第几代int main() srand(int)time(0); for(int i = 0; i 20; i+) Group g; g.work(); printf(第%d次求解。路径:, i+1); for(int j = 0; j city_num; j+) printf(%d , g.best.pathj); printf(;总权值:%d; 第%d代;n, g.best.length, g.best_gen); ret