额,大二暑假写的模拟退火,翻出来存起来以后备用。
我记得当时是用来跑数学建模的NP问题的,别人都用MATLAB,我用的是Codeblocks。。。
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <algorithm>
#include <stdio.h>
#include <time.h>
#include <math.h>
#define N 30 //城市数量
#define T 3000 //初始温度
#define EPS 1e-8 //终止温度
#define DELTA 0.98 //温度衰减率
#define LIMIT 10000 //概率选择上限
#define OLOOP 1000 //外循环次数
#define ILOOP 15000 //内循环次数
using namespace std;
//定义路线结构体
struct Path
{
int citys[N];
double sum;
};
//定义城市点坐标
struct Node
{
double x, y;
};
Path path; //记录最优路径
Node p[N]; //每个城市的坐标
double w[N][N]; //两两城市之间路径长度
int nTest; //测试次数
double Oushi(Node A, Node B)
{
return sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y));
}
void GetDist(Node p[], int n)
{
for(int i = 0; i < n; i++)
for(int j = i + 1; j < n; j++)
w[i][j] = w[j][i] = Oushi(p[i], p[j]);
}
void Input(Node p[], int &n) //输入各城市的坐标 下标0始
{
scanf("%d", &n);
for(int i = 0; i < n; i++)
scanf("%lf %lf", &p[i].x, &p[i].y);
}
void Init(int n) //初始化路径以及测试次数
{
nTest = 1; //nTest表示测试次数
path.sum = 0; //sum表示路径总权值
for(int i = 0; i < n; i++) //默认路径为0到n-1
{
path.citys[i] = i;
if(i != n - 1)
{
printf("%d--->", i);
path.sum += w[i][i + 1];
}
else
printf("%d\n", i);
}
printf("\nInit path length is : %.3lf\n", path.sum);
}
void Print(Path t, int n) //输出路径以及总权值
{
printf("Path is : ");
for(int i = 0; i < n; i++)
{
if(i != n - 1)
printf("%d-->", t.citys[i]);
else
printf("%d\n", t.citys[i]);
}
printf("\nThe path length is : %.3lf\n", t.sum);
}
Path GetNext(Path p, int n) //通过调用随机函数,随机变化两个城市位置
{
int x =0,y =0; //随便取1,下循环会随机的
while(x == y)
{
x = (int)(n * (rand() / (RAND_MAX + 1.0)));
y = (int)(n * (rand() / (RAND_MAX + 1.0)));
}
swap(p.citys[x], p.citys[y]);
p.sum = 0;
for(int i = 0; i < n - 1; i++)
p.sum += w[p.citys[i]][p.citys[i + 1]];
//cout << "nTest = " << nTest++ << endl; 尼玛,加输出,时间巨大
//Print(p, n);
return p;
}
void SA(int n) //模拟退火开始
{
double t = T; //t表示温度
srand(time(NULL));
Path curPath = path;
Path newPath = path;
int P_L = 0; //垃圾解连跳次数
int P_F = 0;
while(1) //外循环,主要更新参数t,模拟退火过程
{
for(int i = 0; i < ILOOP; i++) //内循环,寻找在一定温度下的最优值
{
newPath = GetNext(curPath, n);
double dE = newPath.sum - curPath.sum;
if(dE < 0) //如果找到更优值,直接更新
{
curPath = newPath;
P_L = 0;
P_F = 0;
}
else
{
double rd = rand() / (RAND_MAX + 1.0);
if(exp(-dE / t) > rd && exp(-dE / t) < 1) //如果找到比当前更差的解,以一定概率接受该解,并且这个概率会越来越小
curPath = newPath;
P_L++;
}
if(P_L > LIMIT)
{
P_F++;
break;
}
}
if(curPath.sum < newPath.sum)
path = curPath;
if(P_F > OLOOP || t < EPS)
break;
t *= DELTA;
}
}
int main()
{
freopen("input.data", "r", stdin);
int n;
Input(p, n); //输入城市坐标
GetDist(p, n); //计算城市距离
Init(n);
SA(n);
Print(path, n);
printf("Total test times is : %d\n", nTest);
return 0;
}