设为首页 加入收藏

TOP

C++版遗传算法求解TSP(四)
2019-01-06 16:10:09 】 浏览:357
Tags:遗传 算法 求解 TSP
p;       if (randShk < 0.33) {
                tmpS = shk.Swap(Pop[p], randPosition);        //交换操作
            }
            else if (randShk >= 0.67) {
                tmpS = shk.Flip(Pop[p], randPosition);        //翻转操作
            }
            else {
                tmpS = shk.Insert(Pop[p], randPosition);    //插入操作
            }


            HeuristicOperator evl;
            if (evl.eva l(tmpS, GA_DM, n) > evl.eva l(Pop[p], GA_DM, n)) {
                newPop[p] = Pop[p];
            }
            else {
                newPop[p] = tmpS;
            }
        }
        Pop = newPop;


        //选择操作(轮盘赌)
        vector<double> Cusum(POP_SIZE + 1, 0);        //适用于轮盘赌的累加器Cusum(补充了cus[0]=0;
        for (int i = 0; i < POP_SIZE; i++) {
            Cusum[i + 1] = Cusum[i] + popFit[i];
        }


        double Sum = accumulate(popFit.begin(), popFit.end(), 0.0);        //计算各个体被选择的概率(归一化)
        vector<double> cusFit(POP_SIZE + 1);        //放置种群中个个体被选择的概率值
        for (int i = 0; i < POP_SIZE + 1; i++) {
            cusFit[i] = Cusum[i] / Sum;
        }


        for (int p = 0; p < POP_SIZE; p++) {        //轮盘赌产生新种群
            double r = rand() / double(RAND_MAX);
            for (int q = 0; q < POP_SIZE; q++) {
                if (r > cusFit[q] && r <= cusFit[q + 1]) {
                    newPop[p] = Pop[q];
                }
            }
        }
        Pop = newPop;
    }


    //计时结束
    auto end = system_clock::now();
    auto duration = duration_cast<microseconds>(end - start);
    cout << "花费了"
        << double(duration.count()) * microseconds::period::num / microseconds::period::den
        << "秒" << endl;


    //输出结果
    double gs0 = 15377.711;
    cout << "最优解为" << gs[MAX_GEN] << endl;
    double e = (gs[MAX_GEN] - gs0) / gs0;
    cout << "误差为" << e * 100.0 << '%' << endl;
    cout << "最优路径为" << endl;
    for (int i = 0; i < n; i++) {
        cout << bestIndival[i] + 1 << '\t';
    }
   

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C语言歌星大奖赛代码解析 下一篇Linux下使用cmake生成动态链接库..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目