蚁群算法C++实现,解决TSP问题 联系客服

发布时间 : 星期五 文章蚁群算法C++实现,解决TSP问题更新完毕开始阅读beb2f3e9482fb4daa48d4bb7

1 C++基本蚁群算法代码 #include #include #include #include using namespace std; const int iAntCount=34;//ant numbers const int iCityCount=51; const int iItCount=2000; const double Q=100; const double alpha=1; const double beta=5; const double rou=0.5; int besttour[iCityCount]; double rnd(int low,double uper) { double p=(rand()/(double)RAND_MAX)*((uper)-(low))+(low); return (p); }; int rnd(int uper) { return (rand()%uper); }; class GInfo { public: double m_dDeltTrial[iCityCount][iCityCount]; double m_dTrial[iCityCount][iCityCount]; double distance[iCityCount][iCityCount]; }; GInfo Map; class ant { private: int ChooseNextCity(); double prob[iCityCount]; int m_iCityCount;

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: