发布时间 : 星期五 文章蚁群算法C++实现,解决TSP问题更新完毕开始阅读beb2f3e9482fb4daa48d4bb7
1 C++基本蚁群算法代码 #include
int AllowedCity[iCityCount]; public:
void addcity(int city); int tabu[iCityCount]; void Clear();
void UpdateResult(); double m_dLength; double m_dShortest; void move(); ant();
void move2last(); };
void ant::move2last() { int i;
for(i=0;i addcity(i); break; } } void ant::Clear() { m_dLength=0; int i; for(i=0;i prob[i]=0; AllowedCity[i]=1; } i=tabu[iCityCount-1]; m_iCityCount=0; addcity(i); } ant::ant() { m_dLength=m_dShortest=0; m_iCityCount=0; int i; for(i=0;i AllowedCity[i]=1; prob[i]=0; } } void ant::addcity(int city) { //add city to tabu; tabu[m_iCityCount]=city; m_iCityCount++; AllowedCity[city]=0; } int ant::ChooseNextCity() { //Update the probability of path selection //select a path from tabu[m_iCityCount-1] to next int i; int j=10000; double temp=0; int curCity=tabu[m_iCityCount-1]; for (i=0;i if((AllowedCity[i]==1)) { temp+=pow((1.0/Map.distance[curCity][i]),beta)*pow((Map.m_dTrial[curCity][i]),alpha); } } double sel=0; for (i=0;i if((AllowedCity[i]==1)) { prob[i]=pow((1.0/Map.distance[curCity][i]),beta)*pow((Map.m_dTrial[curCity][i]),alpha)/temp; sel+=prob[i]; } else prob[i]=0; } double mRate=rnd(0,sel); double mSelect=0; for ( i=0;i if((AllowedCity[i]==1)) mSelect+=prob[i] ; if (mSelect>=mRate) {j=i;break;} } if (j==10000) { temp=-1; for (i=0;i if((AllowedCity[i]==1)) if (temp temp=pow((1.0/Map.distance[curCity][i]),beta)*pow((Map.m_dTrial[curCity][i]),alpha); j=i; } } } return j; } void ant::UpdateResult() { // Update the length of tour int i; for(i=0;i m_dLength+=Map.distance[tabu[i]][tabu[i+1]]; m_dLength+=Map.distance[tabu[iCityCount-1]][tabu[0]]; } void ant::move() { //the ant move to next town and add town ID to tabu. int j; j=ChooseNextCity(); addcity(j); } class project { public: