模拟退火算法模板与HDUOJ2899

模拟退火算法

模拟退火简易模板
double solve(){
	double T=100; //初始温度
	double delta = 0.98; //降温系数
	double x=50.0;  //x的初始温度
	double now=func(x);  //计算初始函数值
	double ans=now;  //返回值
	while(T>eps){     //eps是终止温度
		int f[2]={1,-1};
		double newx = x+f[rand()%2]*T; //按概率改变x,随T的降温而减少
		if(newx >= 0 && newx<=100){
			double next = func(newx);
			ans=min(ans,next);
			if(now-next>eps){x=newx;now=next;}			
		}
		T*=delta;
	}
	return ans;
}
例题(HDUOJ2899):“Strange function”
#include<iostream>
#include<algorithm>
#include<cstring>
#include<string.h>
#include<cstdio>

using namespace std; 

const double eps = 1e-8;
double y;

double func(double x){
	return 6*pow(x,7.0)+8*pow(x,6.0)+7*pow(x,3.0)+5*pow(x,2.0)-y*x;
}

double solve(){
	double T=100; //初始温度
	double delta = 0.98; //降温系数
	double x=50.0;  //x的初始温度
	double now=func(x);  //计算初始函数值
	double ans=now;  //返回值
	while(T>eps){     //eps是终止温度
		int f[2]={1,-1};
		double newx = x+f[rand()%2]*T; //按概率改变x,随T的降温而减少
		if(newx >= 0 && newx<=100){
			double next = func(newx);
			ans=min(ans,next);
			if(now-next>eps){x=newx;now=next;}			
		}
		T*=delta;
	}
	return ans;
}

int main(){
	int cas;scanf("%d",&cas);
	while(cas--){
		scanf("%lf",&y);
		printf("%.4lf\n",solve());
	}	
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值