#include<iostream>
#include<cmath>
#include<cstdlib>
#include<vector>
#include<ctime>
#define T_MAX 1e+6
#define T_MIN 50
#define ITER_TIMES 50
#define ALPHA 0.98
using namespace std;
vector<int>Value_Input;
vector<int>Value_Output;
void Input_Data()
{
int x[29] = { 11501760,6301660,402090,7501100,7502030,10302070,1650650,
14901630,7902260,7101310,8400550,11702300,9701340,5100700,
7500900,12801200,2300590,4600860,10400950,5901390,8301770,4900500,
18401240,12601500,12800790,4902130,14601420,12601910,3601980}; //对坐标进行编码,利于计算。
for (unsigned int i = 0; i < 29; i++)
{
Value_Input.push_back(x[i]);
}
}
static float Distance()
{
int x, y; //解码后的x,y
vector<int>x_state; //将解码后的x储存起来
vector<int>y_state; //将解码后的y储存起来
int Distance_Of_All = 0; //总距离
int square_x;
int square_y;
float Distance_Each;
/*将输入解码后得到输出x,y*/
for (size_t i = 0; i < Value_Input.size(); i++)
{
x = Value_Input[i] / 10000;
y = Value_Input[i] - 10000 * x;
x_state.push_back(x);
y_state.push_back(y);
}
/*分别获取x,y方向的总距离*/
for (size_t i = 0; i < x_state.size() - 1; i++)
{
square_x = pow((x_state[i] - x_state[i + 1]), 2);
square_y = pow((x_state[i] - x_state[i + 1]), 2);
Distance_Each = powf((square_x + square_y), 0.5);
Distance_Of_All += Distance_Each;
}
/*计算终点与起点的距离*/
square_x += pow((x_state[0] - x_state[x_state.size() - 1]), 2);
square_y += pow((y_state[0] - y_state[y_state.size() - 1]), 2);
Distance_Each = powf((square_x + square_y), 0.5);
Distance_Of_All += Distance_Each;
return Distance_Of_All;
}
void Simulated_Annealing()
{
int a, b; //生成两个随机数
float p; //随机概率(与Metropolis准则得到的概率比较)
float Metropolis;
float temputure = T_MAX; //当前温度
float E_FIRST, E_SECOND; //E_FIRST为原来的总能量,E_SECOND为变化后的能量
srand(time(NULL));
while (temputure >= T_MIN)
{
for (int i = 0; i < ITER_TIMES; i++)
{
a = rand() % 29; //生成第一个随机数
b = rand() % 29; //生成第二个随机数
while (a!=b)
{
E_FIRST = Distance(); //求解初始距离
swap(Value_Input[a], Value_Input[b]); //交换两个数
E_SECOND = Distance(); //求解第二个距离
/*如果得到更优的解则替换,不是的话进行下一步*/
if (E_FIRST >= E_SECOND)
{
break;
}
/*生成随机概率p与Metropolis值进行比较*/
p = rand() % 2;
Metropolis = exp2f((E_FIRST - E_SECOND) / temputure);
if (p >= Metropolis)
{
Value_Output.push_back(E_SECOND);
break;
}
/*如果不同意的话取消交换*/
swap(Value_Input[a], Value_Input[b]);
}
}
temputure *= ALPHA; //温度迭代(退火)
}
}
void outputVector()
{
int x, y;
float distance;
for (size_t i = 0; i < Value_Input.size(); i++)
{
x = Value_Input[i] / 10000; //解码得到x
y = Value_Input[i] - 10000 * x; //解码得到y
cout << "x = " << x << "y =" << y << endl;
}
distance = Distance(); //输出距离
cout << "距离为" << distance << endl;
}
int main()
{
Input_Data(); //这里可以自己输入TSP坐标
Simulated_Annealing(); //模拟退火算法
outputVector(); //输出最终结果
return 0;
}
我想输入的数据是:
第一组:cities= [0.6606,0.9500;0.9695,0.6740;0.5906,0.5029;0.2124,0.8274;0.0398,0.9697; 0.1367,0.5979;0.9536,0.2184;0.6091,0.7148;0.8767,0.2395;0.8148,0.2867; 0.3876,0.8200;0.7041,0.3296;0.0213,0.1649;0.3429,0.3025;0.7471,0.8192;0.5449,0.9392;0.9464,0.8191;0.1247,0.4351;0.1636,0.8646;0.8668,0.6768];
你把类型换成double 就行了