蚁群算法 C语言程序(已运行)

合集下载

蚁群算法源代码1

蚁群算法源代码1

1.#include<iostream>2.#include<math.h>3.#include<time.h>ing namespace std;5.6.//该程序是以蚁群系统为模型写的蚁群算法程序(强调:非蚂蚁周模型),以三个著名的TSP问题为测试对象7.//通过微调参数,都可以获得较好的解8.9./*10.//----------(1)问题一:Oliver 30 城市 TSP 问题 best_length = 423.7406; ------------------------11.//该程序最好的结果是423.741,可运行多次获得12.//城市节点数目13.#define N 3014.//城市坐标15.double C[N][2]={16. {2,99},{4,50},{7,64},{13,40},{18,54},{18,40},{22,60},{24,42},{25,62},{25,38},17. {37,84},{41,94},{41,26},{44,35},{45,21},{54,67},{54,62},{58,35},{58,69},{62,32},18. {64,60},{68,58},{71,44},{71,71},{74,78},{82,7},{83,46},{83,69},{87,76},{91,38}19.};20.//----------上面参数是固定的,下面的参数是可变的-----------21.//蚂蚁数量22.#define M 3023.//最大循环次数NcMax24.int NcMax = 500;25.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q026.double alpha = 2, beta = 3, rou = 0.1, alpha1 = 0.1, qzero = 0.01;27.//-----------问题一结束------------------------------------------------------------------------28.*/29.30./*31.//----------(2)问题二:Elion50 城市 TSP 问题 best_length = 427.96; ----------------------------32.//该程序最好的结果是428.468,可运行多次获得33.//城市节点数目34.#define N 5035.//城市坐标36.double C[N][2]={37. {5,64}, {5,25}, {5,6}, {7,38}, {8,52}, {10,17},38. {12,42}, {13,13}, {16,57}, {17,33}, {17,63},39. {20,26}, {21,47}, {21,10}, {25,32}, {25,55},40. {27,68}, {27,23}, {30,48}, {30,15}, {31,62},41. {31,32}, {32,22}, {32,39}, {36,16}, {37,69},42. {37,52}, {38,46}, {39,10}, {40,30}, {42,57},43. {42,41}, {43,67}, {45,35}, {46,10}, {48,28},44. {49,49}, {51,21}, {52,33}, {52,41}, {52,64},45. {56,37}, {57,58}, {58,27}, {58,48}, {59,15},46. {61,33}, {62,42}, {62,63}, {63,69}47.};48.//----------上面参数是固定的,下面的参数是可变的-----------49.//蚂蚁数量50.#define M 5051.//最大循环次数NcMax52.int NcMax = 1000;53.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q054.double alpha = 2, beta = 4, rou = 0.1, alpha1 = 0.1, qzero = 0.01;55.//-----------问题二结束------------------------------------------------------------------------56.*/57.58.//----------(3)问题三:Elion75 城市 TSP 问题 best_length = 542.31;59.//该程序最好的结果是542.309,可运行多次获得60.//城市节点数目61.#define N 7562.//城市坐标63.double C[N][2]={64.{6,25}, {7,43}, {9,56}, {10,70}, {11,28},65.{12,17}, {12,38}, {15,5}, {15,14}, {15,56},66.{16,19}, {17,64}, {20,30}, {21,48}, {21,45},67.{21,36}, {22,53}, {22,22}, {26,29}, {26,13},68.{26,59}, {27,24}, {29,39}, {30,50}, {30,20},69.{30,60}, {31,76}, {33,34}, {33,44}, {35,51},70.{35,16}, {35,60}, {36,6}, {36,26}, {38,33},71.{40,37}, {40,66}, {40,60}, {40,20}, {41,46},72.{43,26}, {44,13}, {45,42}, {45,35}, {47,66},73.{48,21}, {50,30}, {50,40}, {50,50}, {50,70},74.{50,4}, {50,15}, {51,42}, {52,26}, {54,38},75.{54,10}, {55,34}, {55,45}, {55,50}, {55,65},76.{55,57}, {55,20}, {57,72}, {59,5}, {60,15},77.{62,57}, {62,48}, {62,35}, {62,24}, {64,4},78.{65,27}, {66,14}, {66,8}, {67,41}, {70,64}80.//----------上面参数是固定的,下面的参数是可变的-----------81.//蚂蚁数量82.#define M 7583.//最大循环次数NcMax84.int NcMax =1000;85.//信息启发因子,期望启发式因子,全局信息素挥发参数,局部信息素挥发参数, 状态转移公式中的q086.double alpha = 2, beta = 5, rou = 0.1, alpha1 = 0.1, qzero = 0.1;87.//-----------问题三结束------------------------------------------------------------------------88.89.90.//===========================================================================================================91.//局部更新时候使用的的常量,它是由最近邻方法得到的一个长度92.//什么是最近邻方法?:)就是从源节点出发,每次选择一个距离最短的点来遍历所有的节点得到的路径93.//每个节点都可能作为源节点来遍历94.double Lnn;95.//矩阵表示两两城市之间的距离96.double allDistance[N][N];97.98.//计算两个城市之间的距离99.double calculateDistance(int i, int j)100.{101.return sqrt(pow((C[i][0]-C[j][0]),2.0) + pow((C[i][1]-C[j][1]),2.0)); 102.}103.104.//由矩阵表示两两城市之间的距离105.void calculateAllDistance()106.{107.for(int i = 0; i < N; i++)108. {109.for(int j = 0; j < N; j++)110. {111.if (i != j)112. {113. allDistance[i][j] = calculateDistance(i, j);114. allDistance[j][i] = allDistance[i][j];115. }116. }117. }118.}120.//获得经过n个城市的路径长度121.double calculateSumOfDistance(int* tour)122.{123.double sum = 0;124.for(int i = 0; i< N ;i++)125. {126.int row = *(tour + 2 * i);127.int col = *(tour + 2* i + 1);128. sum += allDistance[row][col];129. }130.return sum;131.}132.133.class ACSAnt;134.135.class AntColonySystem136.{137.private:138.double info[N][N], visible[N][N];//节点之间的信息素强度,节点之间的能见度139.public:140. AntColonySystem()141. {142. }143.//计算当前节点到下一节点转移的概率144.double Transition(int i, int j);145.//局部更新规则146.void UpdateLocalPathRule(int i, int j);147.//初始化148.void InitParameter(double value);149.//全局信息素更新150.void UpdateGlobalPathRule(int* bestTour, int globalBestLength); 151.};152.153.//计算当前节点到下一节点转移的概率154.double AntColonySystem::Transition(int i, int j)155.{156.if (i != j)157. {158.return (pow(info[i][j],alpha) * pow(visible[i][j], beta)); 159. }160.else161. {162.return 0.0;163. }164.}165.//局部更新规则166.void AntColonySystem::UpdateLocalPathRule(int i, int j)167.{168. info[i][j] = (1.0 - alpha1) * info[i][j] + alpha1 * (1.0 / (N * Lnn));169. info[j][i] = info[i][j];170.}171.//初始化172.void AntColonySystem::InitParameter(double value)173.{174.//初始化路径上的信息素强度tao0175.for(int i = 0; i < N; i++)176. {177.for(int j = 0; j < N; j++)178. {179. info[i][j] = value;180. info[j][i] = value;181.if (i != j)182. {183. visible[i][j] = 1.0 / allDistance[i][j];184. visible[j][i] = visible[i][j];185. }186. }187. }188.}189.190.//全局信息素更新191.void AntColonySystem::UpdateGlobalPathRule(int* bestTour, int globalBestLen gth)192.{193.for(int i = 0; i < N; i++)194. {195.int row = *(bestTour + 2 * i);196.int col = *(bestTour + 2* i + 1);197. info[row][col] = (1.0 - rou) * info[row][col] + rou * (1.0 / global BestLength);198. info[col][row] =info[row][col];199. }200.}201.202.class ACSAnt203.{204.private:205. AntColonySystem* antColony;206.protected:207.int startCity, cururentCity;//初始城市编号,当前城市编号208.int allowed[N];//禁忌表209.int Tour[N][2];//当前路径210.int currentTourIndex;//当前路径索引,从0开始,存储蚂蚁经过城市的编号211.public:212. ACSAnt(AntColonySystem* acs, int start)213. {214. antColony = acs;215. startCity = start;216. }217.//开始搜索218.int* Search();219.//选择下一节点220.int Choose();221.//移动到下一节点222.void MoveToNextCity(int nextCity);223.224.};225.226.//开始搜索227.int* ACSAnt::Search()228.{229. cururentCity = startCity;230.int toCity;231. currentTourIndex = 0;232.for(int i = 0; i < N; i++)233. {234. allowed[i] = 1;235. }236. allowed[cururentCity] = 0;237.int endCity;238.int count = 0;239.do240. {241. count++;242. endCity = cururentCity;243. toCity = Choose();244.if (toCity >= 0)245. {246. MoveToNextCity(toCity);247. antColony->UpdateLocalPathRule(endCity, toCity);248. cururentCity = toCity;249. }250. }while(toCity >= 0);251. MoveToNextCity(startCity);252. antColony->UpdateLocalPathRule(endCity, startCity);253.254.return *Tour;255.}256.257.//选择下一节点258.int ACSAnt::Choose()259.{260.int nextCity = -1;261.double q = rand()/(double)RAND_MAX;262.//如果 q <= q0,按先验知识,否则则按概率转移,263.if (q <= qzero)264. {265.double probability = -1.0;//转移到下一节点的概率266.for(int i = 0; i < N; i++)267. {268.//去掉禁忌表中已走过的节点,从剩下节点中选择最大概率的可行节点269.if (1 == allowed[i])270. {271.double prob = antColony->Transition(cururentCity, i); 272.if (prob > probability)273. {274. nextCity = i;275. probability = prob;276. }277. }278. }279. }280.else281. {282.//按概率转移283.double p = rand()/(double)RAND_MAX;//生成一个随机数,用来判断落在哪个区间段284.double sum = 0.0;285.double probability = 0.0;//概率的区间点,p 落在哪个区间段,则该点是转移的方向286.//计算概率公式的分母的值287.for(int i = 0; i < N; i++)288. {289.if (1 == allowed[i])291. sum += antColony->Transition(cururentCity, i);292. }293. }294.for(int j = 0; j < N; j++)295. {296.if (1 == allowed[j] && sum > 0)297. {298. probability += antColony->Transition(cururentCity, j)/sum;299.if (probability >= p || (p > 0.9999 && probability > 0.9999 ))300. {301. nextCity = j;302.break;303. }304. }305. }306. }307.return nextCity;308.}309.310.//移动到下一节点311.void ACSAnt::MoveToNextCity(int nextCity)312.{313. allowed[nextCity]=0;314. Tour[currentTourIndex][0] = cururentCity;315. Tour[currentTourIndex][1] = nextCity;316. currentTourIndex++;317. cururentCity = nextCity;318.}319.320.//------------------------------------------321.//选择下一个节点,配合下面的函数来计算的长度322.int ChooseNextNode(int currentNode, int visitedNode[])323.{324.int nextNode = -1;325.double shortDistance = 0.0;326.for(int i = 0; i < N; i++)327. {328.//去掉已走过的节点,从剩下节点中选择距离最近的节点329.if (1 == visitedNode[i])330. {331.if (shortDistance == 0.0)333. shortDistance = allDistance[currentNode][i]; 334. nextNode = i;335. }336.if(shortDistance < allDistance[currentNode][i]) 337. {338. nextNode = i;339. }340. }341. }342.return nextNode;343.}344.345.//给一个节点由最近邻距离方法计算长度346.double CalAdjacentDistance(int node)347.{348.double sum = 0.0;349.int visitedNode[N];350.for(int j = 0; j < N; j++)351. {352. visitedNode[j] = 1;353. }354. visitedNode[node] = 0;355.int currentNode = node;356.int nextNode;357.do358. {359. nextNode = ChooseNextNode(currentNode, visitedNode); 360.if (nextNode >= 0)361. {362. sum += allDistance[currentNode][nextNode]; 363. currentNode= nextNode;364. visitedNode[currentNode] = 0;365. }366. }while(nextNode >= 0);367. sum += allDistance[currentNode][node];368.return sum;369.}370.371.//---------------------------------结束---------------------------------------------372.373.//--------------------------主函数--------------------------------------------------374.int main()375.{376.time_t timer,timerl;377.378. time(&timer);379. unsigned long seed = timer;380. seed %= 56000;381. srand((unsigned int)seed);382.383.//由矩阵表示两两城市之间的距离384. calculateAllDistance();385.//蚁群系统对象386. AntColonySystem* acs = new AntColonySystem();387. ACSAnt* ants[M];388.//蚂蚁均匀分布在城市上389.for(int k = 0; k < M; k++)390. {391. ants[k] = new ACSAnt(acs, (int)(k%N));392. }393. calculateAllDistance();394.//随机选择一个节点计算由最近邻方法得到的一个长度395.int node = rand() % N;396. Lnn = CalAdjacentDistance(node);397.398.//各条路径上初始化的信息素强度399.double initInfo = 1 / (N * Lnn);400. acs->InitParameter(initInfo);401.402.//全局最优路径403.int globalTour[N][2];404.//全局最优长度405.double globalBestLength = 0.0;406.for(int i = 0; i < NcMax; i++)407. {408.//局部最优路径409.int localTour[N][2];410.//局部最优长度411.double localBestLength = 0.0;412.//当前路径长度413.double tourLength;414.for(int j = 0; j < M; j++)415. {416.int* tourPath = ants[j]->Search();417. tourLength = calculateSumOfDistance(tourPath);418.//局部比较,并记录路径和长度419.if(tourLength < localBestLength || abs(localBestLength - 0.0) <0.000001)420. {421.for(int m = 0; m< N; m++)422. {423.int row = *(tourPath + 2 * m);424.int col = *(tourPath + 2* m + 1);425. localTour[m][0] = row;426. localTour[m][1] = col;427. }428. localBestLength = tourLength;429. }430. }431.//全局比较,并记录路径和长度432.if(localBestLength < globalBestLength || abs(globalBestLength - 0.0 ) < 0.000001)433. {434.for(int m = 0; m< N; m++)435. {436. globalTour[m][0] = localTour[m][0];437. globalTour[m][1] = localTour[m][1];438. }439. globalBestLength = localBestLength;440. }441. acs->UpdateGlobalPathRule(*globalTour, globalBestLength);442.//输出所有蚂蚁循环一次后的迭代最优路径443. cout<<"第 "<<i + 1<<" 迭代最优路径:"<<localBestLength<<"."<<endl; 444.for(int m = 0; m< N; m++)445. {446. cout<<localTour[m][0]<<".";447. }448. cout<<endl;449. }450.//输出全局最优路径451. cout<<"全局最优路径长度:"<<globalBestLength<<endl;452. cout<<"全局最优路径:";453.for(int m = 0; m< N; m++)454. {455. cout<<globalTour[m][0]<<".";456. }457. cout<<endl;458. time(&timerl);459.int t = timerl - timer;460.return 0;461.}462.//--------------------------主函数结束--------------------------------------------------。

蚁群算法代码

蚁群算法代码

//Basic Ant Colony Algorithm for TSP#include <iostream.h>#include <fstream.h>#include <math.h>#include <time.h>#include <conio.h>#include <stdlib.h>#include <iomanip.h>#define N 31 //city size#define M 31 //ant numberdouble inittao=1;double tao[N][N];double detatao[N][N];double distance[N][N];double yita[N][N];int tabu[M][N];int route[M][N];double solution[M];int BestRoute[N];double BestSolution=10000000000;double alfa,beta,rou,Q;int NcMax;void initparameter(void); // initialize the parameters of basic ACAdouble EvalueSolution(int *a); // evaluate the solution of TSP, and calculate the length of path void InCityXY( double x[], double y[], char *infile ); // input the nodes' coordinates of TSPvoid initparameter(void){alfa=1; beta=5; rou=0.9; Q=100;NcMax=200;}void main(void){int NC=0;initparameter();double x[N];double y[N];InCityXY( x, y, "city31.tsp" );for(int i=0;i<N;i++)for(int j=i+1;j<N;j++){distance[j][i]=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j])); distance[i][j]=distance[j][i];}// calculate the heuristic parametersfor(i=0;i<N;i++)for(int j=0;j<N;j++){tao[i][j]=inittao;if(j!=i)yita[i][j]=100/distance[i][j];}for(int k=0;k<M;k++)for(i=0;i<N;i++)route[k][i]=-1;srand(time(NULL));for(k=0;k<M;k++){route[k][0]=k%N;tabu[k][route[k][0]]=1;}//each ant try to find the optiamal pathdo {int s=1;double partsum;double pper;double drand;//ant choose one whole pathwhile(s<N){for(k=0;k<M;k++){int jrand=rand()%3000;drand=jrand/3001.;partsum=0;pper=0;for(int j=0;j<N;j++){if(tabu[k][j]==0)partsum+=pow(tao[route[k][s-1]][j],alfa)*pow(yita[route[k][s-1]][j],beta); }for(j=0;j<N;j++){if(tabu[k][j]==0)pper+=pow(tao[route[k][s-1]][j],alfa)*pow(yita[route[k][s-1]][j],beta)/partsum; if(pper>drand)break;}tabu[k][j]=1;route[k][s]=j;}s++;}// the pheromone is updatedfor(i=0;i<N;i++)for(int j=0;j<N;j++)detatao[i][j]=0;for(k=0;k<M;k++){solution[k]=EvalueSolution(route[k]);if(solution[k]<BestSolution){BestSolution=solution[k];for(s=0;s<N;s++)BestRoute[s]=route[k][s];}}for(k=0;k<M;k++){for(s=0;s<N-1;s++)detatao[route[k][s]][route[k][s+1]]+=Q/solution[k];detatao[route[k][N-1]][route[k][0]]+=Q/solution[k];}for(i=0;i<N;i++)for(int j=0;j<N;j++){tao[i][j]=rou*tao[i][j]+detatao[i][j];if(tao[i][j]<0.00001)tao[i][j]=0.00001;if(tao[i][j]>20)tao[i][j]=20;}for(k=0;k<M;k++)for(int j=1;j<N;j++){tabu[k][route[k][j]]=0;route[k][j]=-1;}NC++;} while(NC<NcMax);//output the calculating resultsfstream result;result.open("optimal_results.log", ios::app);if(!result){cout<<"can't open the <optimal_results.log> file!\n";exit(0);}result<<"*-------------------------------------------------------------------------*"<<endl; result<<"the initialized parameters of ACA are as follows:"<<endl;result<<"alfa="<<alfa<<", beta="<<beta<<", rou="<<rou<<", Q="<<Q<<endl;result<<"the maximum iteration number of ACA is:"<<NcMax<<endl;result<<"the shortest length of the path is:"<<BestSolution<<endl;result<<"the best route is:"<<endl;for(i=0;i<N;i++)result<<BestRoute[i]<<" ";result<<endl;result<<"*-------------------------------------------------------------------------*"<<endl<<endl; result.close();cout<<"the shortest length of the path is:"<<BestSolution<<endl;}double EvalueSolution(int *a){double dist=0;for(int i=0;i<N-1;i++)dist+=distance[a[i]][a[i+1]];dist+=distance[a[i]][a[0]];return dist;}void InCityXY( double x[], double y[], char *infile ){fstream inxyfile( infile, ios::in | ios::nocreate );if( !inxyfile ){cout<<"can't open the <"<<infile<<"> file!\n";exit(0);}int i=0;while( !inxyfile.eof() ){inxyfile>>x[i]>>y[i];if( ++i >= N ) break;}}31个城市坐标:1304 23123639 13154177 22443712 13993488 15353326 15563238 12294196 10044312 7904386 5703007 19702562 17562788 14912381 16761332 6953715 16783918 21794061 23703780 22123676 25784029 28384263 29313429 19083507 23673394 26433439 32012935 32403140 35502545 23572778 28262370 2975运行后可得到15602的巡游路径改正了n个错误。

蚁群算法附带数据结果

蚁群算法附带数据结果

[代码说明]蚁群算法解决VRP问题[算法说明]首先实现一个ant蚂蚁类,用此蚂蚁类实现搜索。

算法按照tsp问题去解决,但是在最后计算路径的时候有区别。

比如有10个城市,城市1是配送站,蚂蚁搜索的得到的路径是1,3,5,9,4,10,2,6,8,7。

计算路径的时候把城市依次放入派送线路中,每放入一个城市前,检查该城市放入后是否会超过车辆最大载重如果没有超过就放入如果超过,就重新开始一条派送路线……直到最后一个城市放完就会得到多条派送路线这样处理比较简单可以把vrp问题转为tsp问题求解但是实际效果还需要验证。

[作者]Wugsh@2011.12.16wuguangsheng@guangsheng.wu@%}%清除所有变量和类的定义clear;clear classes;%蚁群算法参数(全局变量)global ALPHA; %启发因子global BETA; %期望因子global ANT_COUNT; %蚂蚁数量global CITY_COUNT; %城市数量global RHO; %信息素残留系数!!!global IT_COUNT; %迭代次数global DAry; %两两城市间距离global TAry; %两两城市间信息素global CITYW Ary; %城市货物需求量global VW; %车辆最大载重%===================================================================%设置参数变量值ALPHA=1.0;BETA=2.0;RHO=0.95;IT_COUNT=200;VW=100;%=================================================================== %读取数据并根据读取的数据设置其他参数load data.txt; %从文本文件加载数据city_xy_ary=data(:,2:3); %得到城市的坐标数据CITYW Ary=data(:,4); %得到每个城市的货物需求量CITY_COUNT=length(CITYW Ary); %得到城市数量(包括配送站在内)ANT_COUNT=round(CITY_COUNT*2/3)+1; %根据城市数量设置蚂蚁数量,一般设置为城市数量的2/3%MMAS信息素参数%计算最大信息素和最小信息素之间的比值PBest=0.05; %蚂蚁一次搜索找到最优解的概率temp=PBest^(1/CITY_COUNT);TRate=(1-temp)/((CITY_COUNT/2-1)*temp); %最大信息素和最小信息素之间的比值%信息素的最大最小值开始的时候设置成多大无所谓%第一次搜索完成会生成一个最优解,然后用这个解会重新产生最大最小值Tmax=1; %信息素最大值Tmin=Tmax*TRate; %信息素最小值% 计算两两城市间距离DAry=zeros(CITY_COUNT);for i=1:CITY_COUNTfor j=1:CITY_COUNTDAry(i,j)=sqrt((city_xy_ary(i,1)-city_xy_ary(j,1))^2+(city_xy_ary(i,2)-city_xy_ary(j,2))^2);endend% 初始化城市间信息素TAry=zeros(CITY_COUNT);TAry=TAry+Tmax;%===================================================================%初始化随机种子rand('state', sum(100*clock));%另一种方法%rand('twister',sum(100*clock))%定义蚂蚁mayi=ant();Best_Path_Length=10e9; %最佳路径长度,先设置成一个很大的值tm1=datenum(clock); %记录算法开始执行时的时间FoundBetter=0; %一次搜索是否有更优解产生%开始搜索for i=1:IT_COUNTfprintf('开始第%d次搜索, 剩余%d次',i,IT_COUNT-i);FoundBetter=0; %搜索前先置为没有更优解产生for j=1:ANT_COUNT%蚂蚁搜索一次mayi=Search(mayi);%得到蚂蚁搜索路径长度Length_Ary(j)=get(mayi,'path_length');%得到蚂蚁搜索的路径Path_Ary{j}=get(mayi,'path');%保存最优解if (Length_Ary(j) < Best_Path_Length);Best_Path_Length=Length_Ary(j);Best_Path=Path_Ary{j};%有更优解产生,设置标志FoundBetter=1;endend%有更好解产生,进行2-OPT优化if (FoundBetter == 1)fprintf(' , 本次搜索找到更好解!');Best_Path=opt2(Best_Path);Best_Path_Length=PathLength(Best_Path);end%-------------------------------------------------------------%全部蚂蚁搜索完一次,更新环境信息素TAry=TAry*RHO;%只有全局最优蚂蚁释放信息素dbQ=1/Best_Path_Length;for k=2:CITY_COUNTm=Best_Path(k-1); %上一个城市编号n=Best_Path(k); %下一个城市编号%更新路径上的信息素TAry(m,n)=TAry(m,n)+dbQ;TAry(n,m)=TAry(m,n);end%更新最后城市返回出发城市路径上的信息素TAry(n,1)=TAry(n,1)+dbQ;TAry(1,n)=TAry(n,1);%-------------------------------------------------------------%更新完信息素,进行边界检查Tmax=1/((1-RHO)*Best_Path_Length); %信息素最大值Tmin=Tmax*TRate; %信息素最小值for m=1:CITY_COUNTfor n=1:CITY_COUNTif (TAry(m,n)>Tmax)TAry(m,n)=Tmax;endif (TAry(m,n)<Tmin)TAry(m,n)=Tmin;endendend%-------------------------------------------------------------%换行fprintf('\n');endtm2=datenum(clock); %记录算法结束执行时的时间fprintf('\n搜索完成, 用时%.3f秒, 最佳路径长为%.3f , 派送方案如下::\n\n[1]',(tm2-tm1)*86400,Best_Path_Length);%=================================================================== %输出结果dbW=0;for i=2:CITY_COUNTm=Best_Path(i-1); %上一个城市n=Best_Path(i); %当前城市if (dbW+CITYW Ary(n)>VW) %运送的货物超过限制fprintf(' (满载率: %.1f%%)\n[1]-%d',dbW*100/VW,n);dbW=CITYW Ary(n); %运输的重量等于该城市的需求量else %没有超过限制fprintf('-%d',n);dbW=dbW+CITYWAry(n); %运输的重量加上该城市的需求量endendfprintf(' (满载率: %.1f%%)',dbW*100/VW);fprintf('\n\n');%====== [程序结束]===================================================== %对结果进行2-OPT优化function f=opt2(Line)%数组长度size=length(Line);NewLine=Line; % 返回结果先设置成原来路径Flag=1;while (Flag == 1)Flag=0;for i=1:size-2a=Line(1,1:i); %路径前段b=fliplr(Line(1,i+1:size)); %路径后段倒置c=cat(2,a,b); %新路径%新路径更好就替换if (PathLength(c)<PathLength(NewLine))NewLine=c;Flag=1;fprintf('\n======================= 2-OPT 优化成功! ===');endendend%返回结果f=NewLine;end1 14.5 13.0 0.02 12.8 8.5 0.13 18.4 3.4 0.44 15.4 16.6 1.25 18.9 15.2 1.56 15.5 11.6 0.87 3.9 10.6 1.38 10.6 7.6 1.79 8.6 8.4 0.610 12.5 2.1 1.211 13.8 5.2 0.412 6.7 16.9 0.913 14.8 2.6 1.314 1.8 8.7 1.315 17.1 11.0 1.916 7.4 1.0 1.717 0.2 2.8 1.118 11.9 19.8 1.519 13.2 15.1 1.620 6.4 5.6 1.721 9.6 14.8 1.51 0 0 02 3639 1315 123 4177 2244 134 3712 1399 145 3488 1535 536 3326 1556 457 3238 1229 228 4196 1004 119 4312 790 1110 4386 570 5611 3007 1970 4312 2562 1756 2413 2788 1491 6514 2381 1676 3215 1332 695 5616 3715 1678 6717 3918 2179 6718 4061 2370 2219 3780 2212 3420 3676 2578 5621 4029 2838 2422 4263 2931 2523 3429 1908 2624 3507 2367 4625 3394 2643 8726 3439 3201 3327 2935 3240 2228 3140 3550 2429 2545 2357 5630 2778 2826 2431 2370 2975 4332 1304 2312 12。

C#实现蚁群算法

C#实现蚁群算法

/sun_raining61/blog/item/449da9240b1e71024d088d5d.html/cmtid/1056b bed39d4d24779f05502using System;using System.Collections.Generic;using System.Text;namespace AntSystem{public class AA{/**//// <summary>/// 对信息量的重视程度/// </summary>private int alpha;/**//// <summary>/// 启发式信息的受重视程度/// </summary>private int beta;/**//// <summary>/// 信息素的挥发速度/// </summary>private double lo;/**//// <summary>/// 城市距离矩阵/// </summary>private double[,] City;/**//// <summary>/// 信息素矩阵/// </summary>private double[,] Message;/**//// <summary>/// opneList用于存放下一步可行城市/// </summary>private Queue<int> openList=new Queue<int> ();/**//// <summary>/// closedList用于存放已经访问过的城市/// </summary>private Queue<int> closedList=new Queue<int> ();/**//// <summary>/// 储存较好的路径/// </summary>private Queue <int> BestList=new Queue<int> ();private int Pro_time = 0;/**///////////////////////////////////////////////////////////// <summary>/// 构造函数:形成城市距离和信息素矩阵/// </summary>/// <param name="city">城市距离矩阵</param>/// <param name="Lo"> 信息素的挥发速度</param> public AA(double[,] city,double Lo,int Alpha,int Beta) {alpha = Alpha;beta = Beta;lo=Lo;int temp = Convert.ToInt32( Math.Sqrt(city.Length)); City=new double [temp,temp];Message=new double [temp,temp];for (int i = 0; i < temp; i++){for (int j = 0; j < temp; j++){City[i, j] = city[i, j];}}//初始化信息素矩阵for (int i = 0; i < temp; i++){for (int j = 0; j < temp; j++){if (i != j){Message[i, j] = (double)1 / (temp * temp - temp);}}}}/**//////////////////////////////////////////////////////////////// <summary>/// 改变信息素矩阵,closed_list为较好的路径/// </summary>/// <param name="closed_list"></param>private void Change_Message(Queue<int> closed_list) {lock (this){int[] temp_Array = new int[closed_list.Count];temp_Array = closed_list.ToArray();for (int i = 0; i < closed_list.Count - 1; i++){Message[temp_Array[i], temp_Array[i + 1]] = Message[temp_Array[i], temp_Array[i + 1]] + lo / ((1 - lo) *Convert.ToInt32(Get_Weight(closed_list)+1));}Message[temp_Array[temp_Array.Length - 1], temp_Array[0]] = Message[temp_Array[temp_Array.Length - 1], temp_Array[0]] + lo / ((1 - lo) *Convert.ToInt32(Get_Weight(closed_list)));for (int i = 0; i < closed_list.Count; i++){for (int j = 0; j < closed_list.Count; j++){Message[i, j] = (1 - lo) * Message[i, j];}}}}/**/////////////////////////////////////////////////////////////////// <summary>/// 输入一个链表,计算出其对应的总路径/// </summary>/// <param name="closed_list"></param>/// <returns></returns>public double Get_Weight(Queue <int> closed_list){lock (this){double sum = 0;int[] temp_Array = new int[closed_list.Count];temp_Array = closed_list.ToArray();for (int i = 0; i < Convert.ToInt32(temp_Array.Length) - 1; i++){sum = sum + City[temp_Array[i], temp_Array[i + 1]];}sum = sum + City[temp_Array[temp_Array.Length - 1], temp_Array[0]];return sum;}}/**////////////////////////////////////////////////////////////////// <summary>/// 产生到i城市后,下一个可走城市的集合。

蚁群算法——精选推荐

蚁群算法——精选推荐

蚁群算法⼀、蚁群算法简介 蚁群算法(AG)是⼀种模拟蚂蚁觅⾷⾏为的模拟优化算法,它是由意⼤利学者Dorigo M等⼈于1991年⾸先提出,并⾸先使⽤在解决TSP(旅⾏商问题)上。

之后,⼜系统研究了蚁群算法的基本原理和数学模型.⼆、蚁群算法原理1、蚂蚁在路径上释放信息素。

2、碰到还没⾛过的路⼝,就随机挑选⼀条路⾛。

同时,释放与路径长度有关的信息素。

3、信息素浓度与路径长度成反⽐。

后来的蚂蚁再次碰到该路⼝时,就选择信息素浓度较⾼路径。

4、最优路径上的信息素浓度越来越⼤。

5、最终蚁群找到最优寻⾷路径。

三、蚁群算法流程图四、实例应⽤基于TSP问题的基本蚁群算法原理讲解参考⽼师上课讲解的PPT不做过多粘贴1.源代码:%% 旅⾏商问题(TSP)优化%% 清空环境变量clear allclc%% 导⼊数据citys = ceil(rand(50,2)*50000)%load newcitys.mat%% 计算城市间相互距离fprintf('Computing Distance Matrix... \n');n = size(citys,1);D = zeros(n,n);for i = 1:nfor j = 1:nif i ~= jD(i,j) = sqrt(sum((citys(i,:) - citys(j,:)).^2));elseD(i,j) = 1e-4;endendend%% 初始化参数fprintf('Initializing Parameters... \n');m = 50; % 蚂蚁数量alpha = 1; % 信息素重要程度因⼦beta = 5; % 启发函数重要程度因⼦rho = 0.05; % 信息素挥发因⼦Q = 1; % 常系数Eta = 1./D; % 启发函数Tau = ones(n,n); % 信息素矩阵Table = zeros(m,n); % 路径记录表iter = 1; % 迭代次数初值iter_max = 150; % 最⼤迭代次数Route_best = zeros(iter_max,n); % 各代最佳路径Length_best = zeros(iter_max,1); % 各代最佳路径的长度Length_ave = zeros(iter_max,1); % 各代路径的平均长度%% 迭代寻找最佳路径figure;while iter <= iter_maxfprintf('迭代第%d次\n',iter);% 随机产⽣各个蚂蚁的起点城市start = zeros(m,1);for i = 1:mtemp = randperm(n);start(i) = temp(1);endTable(:,1) = start;% 构建解空间citys_index = 1:n;% 逐个蚂蚁路径选择for i = 1:m% 逐个城市路径选择for j = 2:ntabu = Table(i,1:(j - 1)); % 已访问的城市集合(禁忌表)allow_index = ~ismember(citys_index,tabu);allow = citys_index(allow_index); % 待访问的城市集合P = allow;% 计算城市间转移概率for k = 1:length(allow)P(k) = Tau(tabu(end),allow(k))^alpha * Eta(tabu(end),allow(k))^beta; endP = P/sum(P);% 轮盘赌法选择下⼀个访问城市Pc = cumsum(P);target_index = find(Pc >= rand);target = allow(target_index(1));Table(i,j) = target;endend% 计算各个蚂蚁的路径距离Length = zeros(m,1);for i = 1:mRoute = Table(i,:);for j = 1:(n - 1)Length(i) = Length(i) + D(Route(j),Route(j + 1));endLength(i) = Length(i) + D(Route(n),Route(1));end% 计算最短路径距离及平均距离if iter == 1[min_Length,min_index] = min(Length);Length_best(iter) = min_Length;Length_ave(iter) = mean(Length);Route_best(iter,:) = Table(min_index,:);else[min_Length,min_index] = min(Length);Length_best(iter) = min(Length_best(iter - 1),min_Length);Length_ave(iter) = mean(Length);if Length_best(iter) == min_LengthRoute_best(iter,:) = Table(min_index,:);elseRoute_best(iter,:) = Route_best((iter-1),:);endend% 更新信息素Delta_Tau = zeros(n,n);% 逐个蚂蚁计算for i = 1:m% 逐个城市计算for j = 1:(n - 1)Delta_Tau(Table(i,j),Table(i,j+1)) = Delta_Tau(Table(i,j),Table(i,j+1)) + Q/Length(i); endDelta_Tau(Table(i,n),Table(i,1)) = Delta_Tau(Table(i,n),Table(i,1)) + Q/Length(i); endTau = (1-rho) * Tau + Delta_Tau;% 迭代次数加1,清空路径记录表% figure;%最佳路径的迭代变化过程[Shortest_Length,index] = min(Length_best(1:iter));Shortest_Route = Route_best(index,:);plot([citys(Shortest_Route,1);citys(Shortest_Route(1),1)],...[citys(Shortest_Route,2);citys(Shortest_Route(1),2)],'o-');pause(0.3);iter = iter + 1;Table = zeros(m,n);% endend%% 结果显⽰[Shortest_Length,index] = min(Length_best);Shortest_Route = Route_best(index,:);disp(['最短距离:' num2str(Shortest_Length)]);disp(['最短路径:' num2str([Shortest_Route Shortest_Route(1)])]);%% 绘图figure(1)plot([citys(Shortest_Route,1);citys(Shortest_Route(1),1)],...[citys(Shortest_Route,2);citys(Shortest_Route(1),2)],'o-');grid onfor i = 1:size(citys,1)text(citys(i,1),citys(i,2),[' ' num2str(i)]);endtext(citys(Shortest_Route(1),1),citys(Shortest_Route(1),2),' 起点');text(citys(Shortest_Route(end),1),citys(Shortest_Route(end),2),' 终点');xlabel('城市位置横坐标')ylabel('城市位置纵坐标')title(['蚁群算法优化路径(最短距离:' num2str(Shortest_Length) ')'])figure(2)plot(1:iter_max,Length_best,'b',1:iter_max,Length_ave,'r:')legend('最短距离','平均距离')xlabel('迭代次数')ylabel('距离')title('各代最短距离与平均距离对⽐')运⾏结果:利⽤函数citys = ceil(rand(50,2)*50000) 随机产⽣五⼗个城市坐标2.研究信息素重要程度因⼦alpha, 启发函数重要程度因⼦beta,信息素挥发因⼦rho对结果的影响为了保证变量唯⼀我重新设置五⼗个城市信息进⾏实验在原来设值运⾏结果:实验结果可知当迭代到120次趋于稳定2.1 alpha值对实验结果影响(1)当alpha=4时运⾏结果实验结果可知当迭代到48次左右趋于稳定(2)当alpha=8时运⾏结果:有图可知迭代40次左右趋于稳定,搜索性较⼩(3)当alpha= 0.5运⾏结果:有图可知迭代到140次左右趋于稳定(4)当alpha=0.2时运⾏结果:结果趋于110次左右稳定所以如果信息素因⼦值设置过⼤,则容易使随机搜索性减弱;其值过⼩容易过早陷⼊局部最优2.2 beta值对实验影响(1)当 beta=8时运⾏结果结果迭代75次左右趋于稳定(2)当 beta=1时运⾏结果:结果迭代130次左右趋于稳定所以beta如果值设置过⼤,虽然收敛速度加快,但是易陷⼊局部最优;其值过⼩,蚁群易陷⼊纯粹的随机搜索,很难找到最优解2.3 rho值对实验结果影响(1)当rho=3时运⾏结果:结果迭代75次左右趋于稳定(2)当rho=0.05运⾏结果:结果迭代125次左右趋于稳定所以如果rho取值过⼤时,容易影响随机性和全局最优性;反之,收敛速度降低总结:蚁群算法对于参数的敏感程度较⾼,参数设置的好,算法的结果也就好,参数设置的不好则运⾏结果也就不好,所以通常得到的只是局部最优解。

蚁群算法原理及在TSP中的应用(附程序)

蚁群算法原理及在TSP中的应用(附程序)

蚁群算法原理及在TSP 中的应用1 蚁群算法(ACA )原理1.1 基本蚁群算法的数学模型以求解平面上一个n 阶旅行商问题(Traveling Salesman Problem ,TSP)为例来说明蚁群算法ACA (Ant Colony Algorithm )的基本原理。

对于其他问题,可以对此模型稍作修改便可应用。

TSP 问题就是给定一组城市,求一条遍历所有城市的最短回路问题。

设()i b t 表示t 时刻位于元素i 的蚂蚁数目,()ij t τ为t 时刻路径(,)i j 上的信息量,n 表示TSP 规模,m 为蚁群的总数目,则1()ni i m b t ==∑;{(),}ij i i t c c C τΓ=⊂是t 时刻集合C 中元素(城市)两两连接ij t 上残留信息量的集合。

在初始时刻各条路径上信息量相等,并设 (0)ij const τ=,基本蚁群算法的寻优是通过有向图(,,)g C L =Γ实现的。

蚂蚁(1,2,...,)k k m =在运动过程中,根据各条路径上的信息量决定其转移方向。

这里用禁忌表(1,2,...,)k tabu k m =来记录蚂蚁k 当前所走过的城市,集合随着k tabu 进化过程作动态调整。

在搜索过程中,蚂蚁根据各条路径上的信息量及路径的启发信息来计算状态转移概率。

()kij p t 表示在t 时刻蚂蚁k 由元素(城市)i 转移到元素(城市)j 的状态转移概率。

()*()()*()()0k ij ij k kij ij ij s allowed t t j allowed t t p t αβαβτητη⊂⎧⎡⎤⎡⎤⎣⎦⎣⎦⎪∈⎪⎡⎤⎡⎤=⎨⎣⎦⎣⎦⎪⎪⎩∑若否则(1)式中,{}k k allowed C tabuk =-表示蚂蚁k 下一步允许选择的城市;α为信息启发式因子,表示轨迹的相对重要性,反映了蚂蚁在运动过程中所积累的信息在蚂蚁运动时所起作用,其值越大,则该蚂蚁越倾向于选择其他蚂蚁经过的路径,蚂蚁之间协作性越强;β为期望启发式因子,表示能见度的相对重要性,反映了蚂蚁在运动过程中启发信息在蚂蚁选择路径中的重视程度,其值越大,则该状态转移概率越接近于贪心规则;()ij t η为启发函数,其表达式如下:1()ij ijt d η=(2)式中,ij d 表示相邻两个城市之间的距离。

蚁群算法求函数最大值的程序

蚁群算法求函数最大值的程序

蚁群算法求函数最大值的程序蚁群算法是一种模拟蚂蚁觅食行为的启发式算法,常用于求解函数最大值问题。

本文将详细介绍蚁群算法的原理和实现步骤,以及一个示例程序。

1.蚁群算法原理蚁群算法基于蚁群觅食行为中的信息素交流和随机跳跃,通过多个智能体(模拟蚂蚁)在解空间中的和信息传递,逐步寻找到函数的最大值。

具体而言,蚁群算法包含以下关键要素:-蚂蚁:代表着算法解空间的个体,通过在解空间中的移动来探索新的解。

-信息素:用于模拟蚂蚁之间的信息传递和集体合作,蚂蚁在移动过程中会根据信息素浓度进行选择。

-目标函数:蚁群算法通过目标函数来评估到的解的优劣,从而引导蚂蚁进行。

-路径选择规则:蚂蚁在移动过程中根据一定的规则选择下一步的移动路径。

信息素浓度、目标函数值等因素都可以作为路径选择规则的参考。

-信息素更新规则:当蚂蚁选择了条路径后,会根据该路径的质量(目标函数值等)来更新路径上的信息素浓度。

2.蚁群算法步骤蚁群算法的一般步骤如下:1.初始化蚂蚁群和信息素矩阵。

2.对每只蚂蚁,计算其适应度并选择下一步的移动方向。

3.更新每只蚂蚁的位置,并根据移动结果更新信息素矩阵。

4.检查是否满足停止条件,如果满足则输出最优解,否则返回步骤23.蚁群算法示例程序下面是一个求解函数f(x)=x^2在[-10,10]范围内的最大值的蚁群算法示例程序。

```pythonimport randomimport math#目标函数def target_function(x):return x ** 2#初始化蚂蚁群ant_count = 100ants = [random.uniform(-10, 10) for _ in range(ant_count)] #初始化信息素矩阵pheromones = [1 for _ in range(ant_count)]#蚁群算法参数max_iter = 100 # 最大迭代次数alpha = 1 # 信息素重要程度因子beta = 1 # 启发因子rho = 0.1 # 信息素挥发因子Q=1#信息素强度best_solution = None#迭代优化过程for iter in range(max_iter):#计算每只蚂蚁的适应度并选择下一步移动方向for i in range(ant_count):ant = ants[i]fitness = target_function(ant)#选择下一步移动方向if random.random( < pheromones[i]:ant += random.uniform(-1, 1) # 信息素浓度高的蚂蚁随机选择一个方向else:ant += random.uniform(-0.1, 0.1) # 信息素浓度低的蚂蚁随机选择一个方向ants[i] = ant#更新最优解if best_solution is None or target_function(ant) >target_function(best_solution):best_solution = ant#更新信息素矩阵for i in range(ant_count):#蚂蚁越接近最优解,释放的信息素越多pheromones[i] = (1 - rho) * pheromones[i] + Q *(target_function(ants[i]) / target_function(best_solution)) #输出最优解print("最大值点坐标为:", best_solution)print("最大值为:", target_function(best_solution))```4.程序解释该示例程序使用Python编写,实现了蚁群算法来求解函数f(x)=x^2在[-10, 10]范围内的最大值。

蚁群算法

蚁群算法

蚁群算法解决TSP问题题目:基于蚁群算法的TSP问题的分析与实现学号: 2220150496姓名:陈帅一、预备知识1、TSP问题旅行商问题,简称TSP,即给定n个城市和两两城市之间的距离,要求确定一条经过各城市当且仅当一次的最短路线。

其图论描述为:给定图G=(V,A),其中V为顶点集,A为各顶点相互连接组成的边集,设D=(dij)是由顶点i和顶点j之间的距离所组成的距离矩阵,要求确定一条长度最短的Hamilton回路,即遍历所有顶点当且仅当一次的最短距离。

旅行商问题可分为如下两类:(1)对称旅行商问题(d ij=d ji,Πi,j=1,2,3,⋯,n);(2)非对称旅行商问题(d ij≠d ji,ϖi,j=1,2,3,⋯,n)。

非对称旅行商问题较难求解,我们一般是探讨对称旅行商问题的求解。

若对于城市V={v1,v2,v3,⋯,v n}的一个访问顺序为T={t1,t2,t3,⋯,t i,⋯,t n},其中t i∈V(i=1,2,3,⋯,n),且记t n+1=t1,则旅行商问题的数学模型为:minL=。

TSP是一个典型的组合优化问题,并且是一个NP完全难题,是诸多领域内出现的多种复杂问题的集中概括和简化形式,并且已成为各种启发式的搜索、优化算法的间接比较标准。

因此,快速、有效地解决TSP有着重要的理论价值和极高的实际应用价值。

2、蚁群算法蚁群算法是一种基于种群的启发式仿生进化系统。

该算法通过模拟自然界的蚂蚁觅食过程对目标进行搜索,而在搜索过程中人工蚂蚁会在其经过的路径上释放信息素,蚁群依赖于同类散发在周围环境中的特殊物质—信息素的轨迹来决定自己的去向。

当某些路径上走过的蚂蚁越来越多时,留下的信息素也会越来越多,以致后蚂蚁选择该路径的概率也越来越高,从而更增加了该路径的吸引强度,逐渐形成了一条它们自己事先并未意识到的最短路线。

蚁群算法实现TSP 过程为:将 m 只蚂蚁放入到 n 个随机选择的城市中,那么每个蚂蚁每步的行动是:根据一定的依据选择下一个它还没有访问的城市;同时在完成一步(从一个城市到达另一个城市)或者一个循环(完成对所有 n 个城市的访问)后,更新所有路径上的信息素浓度。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
double EvalueSolution(int *a); // evaluate the solution of TSP, and calculate the length of path
void InCityXY( double x[], double y[], char *infile ); // input the nodes' coordinates of TSP
if(tao[i][j]>20)
tao[i][j]=20;
}
for(k=0;k<M;k++)
for(int j=1;j<N;j++)
{
tabu[k][route[k][j]]=0;
route[k][j]=-1;
}
NC++;
} while(NC<NcMax);
//output the calculating results
result<<"the shortest length of the path is:"<<BestSolution<<endl;
result<<"the best route is:"<<endl;
for(i=0;i<N;i++)
result<<BestRoute[i]<<" ";
result<<endl;
for(i=0;i<N;i++)
for(int j=0;j<N;j++)
{
tao[i][j]=inittao;
if(j!=i)
yita[i][j]=100/distance[i][j];
}
for(int k=0;k<M;k++)
for(i=0;i<N;i++)
route[k][i]=-1;
srand(time(NULL));
int route[M][N];
double solution[M];
int BestRoute[N];
double BestSolution=10000000000;
double alfa,beta,rou,Q;
int NcMax;
void initparameter(void); // initialize the parameters of basic ACA
result<<"the initialized parameters of ACA are as follows:"<<endl;
result<<"alfa="<<alfa<<", beta="<<beta<<", rou="<<rou<<", Q="<<Q<<endl;
result<<"the maximum iteration number of ACA is:"<<NcMax<<endl;
detatao[route[k][N-1]][route[k][0]]+=Q/solution[k];
}
for(i=0;i<N;i++)
for(int j=0;j<N;j++)
{
tao[i][j]=rou*tao[i][j]+detatao[i][j];
if(tao[i][j]<0.00001)
tao[i][j]=0.00001;
void initparameter(void)
{
alfa=1; beta=5; rou=0.9; Q=100;
NcMax=200;
}
void main(void)
{
int NC=0;
initparameter();
double x[N];
double y[N];
InCityXY( x, y, "city31.tsp" );
}
s++;
}
// the pheromone is updated
for(i=0;i<N;i++)
for(int j=0;j<N;j++)
detatao[i][j]=0;
for(k=0;k<M;k++)
{
solution[k]=EvalueSolution(route[k]);
if(solution[k]<BestSolution)
#define N 31 //city size
#define M 31 //ant number
double inittao=1;
double tao[N][N];
double detatao[N][N];
double distance[N][N];
double yita[N][N];
int tabu[M][N];
while(s<N)
{
for(k=0;k<M;k++)
{
int jrand=rand()%3000;
drand=jrand/3001.;
partsum=0;
pper=0;
for(int j=0;j<N;j++)
{
if(tabu[k][j]==0)
partsum+=pow(tao[route[k][s-1]][j],alfa)*pow(yita[route[k][s-1]][j],beta);
}
double EvalueSolution(int *a)
{
double dist=0;
for(int i=0;i<N-1;i++)
dist+=distance[a[i]][a[i+1]];
dist+=distance[a[i]][a[0]];
return dist;
}
void InCityXY( double x[], double y[], char *infile )
{
BestSolution=solution[k];
for(s=0;s<N;s++)
BestRoute[s]=route[k][s];
}
}
for(k=0;k<M;k++)
{
for(s=0;s<N-1;s++)
detatao[route[k][s]][route[k][s+1]]+=Q/solution[k];
}
for(j=0;j<N;j++)
{
if(tabu[k][j]==0)
pper+=pow(tao[route[k][s-1]][j],alfa)*pow(yita[route[k][s-1]][j],beta)/partsum;
if(pper>drand)
break;
}
tabu[k][j]=1;
route[k][s]=j;
{
fstream inxyfile( infile, ios::in | ios::nocreate );
if( !inxyfile )
{
cout<<"can't open the <"<<infile<<"> file!\n";
exit(0);
}
int i=0;
while( !inxyfile.eof() )
for(int i=0;i<N;i++)
for(int j=i+1;j<N;j++)
{
distance[j][i]=sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
distance[i][j]=distance[j][i];
}
// calculate the heuristic parameters
result<<"*-------------------------------------------------------------------------*"<<endl<<endl;
result.close();
cout<<"the shortest length of the path is:"<<BestSolution<<endl;
fstream result;
result.open("optimal_results.log", ios::app);
if(!result)
{
cout<<"can't open the <optimal_results.log> file!\n";
exit(0);
}
result<<"*-------------------------------------------------------------------------*"<<endl;
相关文档
最新文档