First, the discussion
1. Algorithm source
The basic principle of ant colony algorithm originates from the principle of the shortest path of ants foraging in nature, according to the observation of the insect, it is found that the ant of nature is not developed visually, but it can find the shortest path from food source to nest without any hint, and can change the environment (if there are obstacles on the original path). Adaptively search for the new best path.
2, a single ant to find the path
Positive feedback:
In order to avoid getting lost, a single ant, when crawling, also releases a special secretion, pheromone (pheromone), and it can perceive the pheromone secreted by other ants within a certain range and thus affect its own behavior. As the pheromone of a route becomes more and more (and, of course, gradually diminishes over time), the probability of the subsequent ants choosing the path becomes larger, further increasing the pheromone concentration of the pathway, which is called the self-catalysis of the ant process.
Diversity:
At the same time in order to ensure that ants in the foraging time not into a dead end and infinite circulation, ants in the process of searching for a path, the need for a certain randomness, although in the process of foraging will be based on the concentration of pheromone to forage, but sometimes there are no judgments, environmental impact and other many other situations, And finally, the point is that the current pheromone concentration of the path is not necessarily the shortest path, need to constantly revise, diversity to ensure the system's innovative ability.
It is this two-point careful combination that makes ant colony intelligent behavior emerge.
3, the specific implementation needs to solve the two first issues
(1) How to realize the process of single ant seeking Road
(2) How to achieve the update of pheromone concentration
Second, the concrete realization
The code looks like this:
#include <iostream> #include <algorithm> #include <cstring> #include <windows.h> #include < stdio.h> #include <stdlib.h> #include <math.h> #include <time.h>using namespace Std;/*int citypos[ 10][2]= {{87,7},{91,38},{83,46},{71,44},{64,60},{68,58},{83,69}, {87,76},{74,78},{71,71}}; Coordinates of 10 cities */unsigned seed= (unsigned) time (0);//prototype: void Srand (unsigned seed);//30 City coordinates int citypos[30][2]={{87,7},{ 91,38},{83,46},{71,44},{64,60},{68,58},{83,69},{87,76},{74,78},{71,71},{58,69},{54,62},{51,67},{37,84},{41,94} , {2,99},{7,64},{22,60},{25,62},{18,54},{4,50},{13,40},{18,40},{24,42},{25,38},{41,26},{45,21},{44,35},{58,35}, {62,32}}; #define CITY_NUM 30//City Number # # Ant_num 30//Ant colony number # # TMAC 1000//Iteration Max # # ROU 0.5//Error size # define ALPHA 1//Pheromone Critical degree parameter # # BETA 4//heuristic factor importance parameter # # Q 100//pheromone residue parameter const int MAXN = 100;double DIS[MAXN][MAXN]; Distance double INFO[MAXN][MAXN]; Pheromone matrix double e[city_num][city_num]; Heuristic factor matrix inT Vis[city_num][city_num];d ouble bestlength;double ans[city_num];const Double Mmax = 10e9;//returns the random integer in the specified range int rnd (int Nlow,int nupper) {return nlow+ (Nupper-nlow) *rand ()/(rand_max+1);} Returns a random floating-point number within the specified range double rnd (double dblow,double dbupper) {double Dbtemp=rand ()/((double) rand_max+1.0); Return dblow+dbtemp* (Dbupper-dblow);} Returns the floating-point number of a floating-point number rounding rounding, double ROUND (double DbA) {return (double) ((int) (dba+0.5));} struct ant{int path[city_num]; The ant walks the path double length; Path total length int vis[city_num]; Walk through the city mark int cur_cityno; Current city int moved_cnt; Number of walks//Initialize void Init () {memset (Vis, 0, sizeof (VIS)); length = 0; Cur_cityno = Rnd (0, City_num);//Randomly Select a departure city path[0] = Cur_cityno; Vis[cur_cityno] = 1; moved_cnt = 1; printf ("Init%d \ n", Cur_cityno); }//Select Next city//return value for City number int choosenextcity () {int nselectedcity=-1;//return result, set it to 1//To calculate the current city and The pheromone sum of the cities that have not been visited double dbtotal=0.0; DoUble Prob[city_num]; Save each city the probability of being selected for (int i = 0; i < City_num; i++) {if (!vis[i]) {PR Ob[i]=pow (Info[cur_cityno][i],alpha) *pow (1.0/dis[cur_cityno][i], BETA); Dbtotal + = Prob[i]; } else {Prob[i] = 0; }}//Make roulette select double dbtemp=0.0; if (Dbtotal > 0.0)//The total pheromone value is greater than 0 {dbtemp = rnd (0.0, dbtotal); for (int i = 0; i < City_num; i++) {if (!vis[i]) {dbtemp -= Prob[i]; if (Dbtemp < 0.0) {nselectedcity = i; Break }}}}//If the inter-city pheromone is very small (smaller than the smallest number the double can represent)//the first city that has not been visited is returned as a Fruit if (nselectedcity = =-1) {for (int i=0; i<city_num; i+ +) {if (!vis[i])//city has not been to {nselectedcity=i; Break }}} return nselectedcity; }//ants move between cities void Move () {int ncityno = choosenextcity ();//select Next City path[moved_cnt] = ncityno;//Save Ma Ant walk path Vis[ncityno] = 1;//The city is set to have been to Cur_cityno = Ncityno; Update path Length (+ + dis[path[moved_cnt-1]][path[moved_cnt]); moved_cnt++; }//Ant search once void search () {Init (); If the number of cities the ant has visited is smaller than the number of cities, continue to move while (Moved_cnt < City_num) {move (); } length + = dis[path[city_num-1]][path[0]]; }};struct tsp{Ant Ants[ant_num]; Define a swarm of ant ant Ant_best; Save the best results of the Ant void Init () {//Initialize to maximum value ant_best.length = Mmax; Puts ("Cal Dis"); Calculates the distance between 22 cities for (int i = 0; i < City_num; i++) {for (int j = 0; J < City_num; J + +) {double temp1=citypos[j][0]-citypos[i][0]; Double temp2=citypos[j][1]-citypos[i][1]; DIS[I][J] = sqrt (TEMP1*TEMP1+TEMP2*TEMP2); }}//Initialize the Environment pheromone puts ("init info"); for (int i=0, i<city_num; i++) {for (int j=0; j<city_num; J + +) {Info[i ][j]=1.0; }}}//update pheromone, the current pheromone on each route is equal to the pheromone of the past reservation//Plus each ant walks past the remainder of the pheromone void Updateinfo () {//puts ("Update inf O "); Double Tmpinfo[city_num][city_num]; memset (tmpinfo, 0, sizeof (tmpinfo)); int m = 0; int n = 0; Traverse each ant for (int i = 0; i < Ant_num; i++) {//puts ("* * * *");//for (int j = 0; J < CIT Y_num; J + +) {//printf ("%d", ants[i]. PATH[J]);//}//puts (""); for (int j = 1; j < City_num; J + +) {m = ants[i]. PATH[J]; n = ants[i]. PATH[J-1]; printf ("%d%d\n", M, N); TMPINFO[N][M] = tmpinfo[n][m]+q/ants[i].length; Tmpinfo[m][n] = tmpinfo[n][m]; }//The last city and the beginning of the city between the pheromone n = ants[i]. PATH[0]; TMPINFO[N][M] = tmpinfo[n][m]+q/ants[i].length; Tmpinfo[m][n] = tmpinfo[n][m]; }//Update environment pheromone for (int i = 0; i < City_num; i++) {for (int j = 0; J < City_num; j + +) {//Latest environmental pheromone = retained pheromone + newly-left pheromone info[i][j] = Info[i][j]*rou + tmpinfo[i][j]; }}}//Find the path, iterate TMAC times void Search () {for (int i = 0; i < TMAC; i++) {printf ("C Urrent Iteration Times%d\n ", I); for (int j = 0; J < Ant_num; J + +) {Ants[j]. Search (); }//Save best results for (int j = 0; J < Ant_num; J + +) {if (Ant_best.length > Ants[j].le Ngth) {ANt_best = Ants[j]; }}//Update environmental pheromone Updateinfo (); printf ("Current minimum length%lf\n", ant_best.length); }}};int Main () {//freopen ("Output.txt", "w", stdout); Srand (seed); TSP tsp; Initializes the ant colony of the TSP. Init (); Start looking for the TSP. Search (); Puts ("The Minimum length route is: \ n"); for (int i = 0; i < City_num; i++) {if (I! = 0 && i = = 0) {puts (""); } printf ("%d", tsp.ant_best. Path[i]); } return 0;}
Result of Operation
(1) Select the data that the teacher gave to 10 cities, the results are as follows, after 50 iterations can get the best solution, and the algorithm is quite stable, many attempts are 50 times to get the best solution, compared to the genetic algorithm 500 iterations in time has a great improvement.
(2) Select the 30 cities the teacher gives data, after 1000 iterations can get a very good solution, the results are stable at about 425, and the optimal solution 424.869292 is very close, and occasionally get the optimal solution, compared to the genetic algorithm iteration 10,000 times results in about 700, the best results have a great leap.
Summarize:
(1) Ant colony algorithm compared to the genetic algorithm to solve the TSP problem has a great improvement, I think very big reason is the ant colony in the search path process of the positive feedback adjustment, is based on the pheromone concentration adjustment, so that the path length is easy to converge. At the same time, due to the use of roulette algorithm, there is guaranteed to exist a certain diversity, affected by the initial value is not small.
(2) Ant colony algorithm also has certain limitations, although compared with the genetic algorithm has a great improvement, but sometimes still can not find the optimal solution, only to find the suboptimal solution. The subsequent to the specific optimization, it is necessary to adjust the relevant parameters to continue to improve.
Solving tsp problem with ant colony algorithm