模拟退火/爬山算法模板题
为什么它可以使用爬山算法?
不难看出,这道题的目标函数是单峰函数,即每一个答案与准确答案之差形成单峰函数,遂,我们可以使用爬山算法解决此题,当然,也可以使用模拟退火。
如何实现
由于爬山算法过于简单,所以这里只给出模拟退火思路及代码,定义f为准确答案,cnt为退火过程中最大变化量,初始设为1。在模拟降温时每次将临时答案加减1到cnt的随机数,对比与当前最优解同时减f的绝对值,更改新解或概率接受结果
代码
#include<bits/stdc++.h>
#define cen cout << endl;
#define c1 cout << 1 << " ";
#define cs cout << " ";
using namespace std;
double Rand1(double a,double b){static mt19937 t(random_device{}());uniform_real_distibution<double> f(a,b);return f(t);}
int aa;
int bb;
int Rand2(){static mt19937 t(random_device{}());uniform_int_distribution<int> f(aa,bb);return f(t);}
bool use(int &a,int &b,double &t){return (1.0*exp(a-b))/t<(Rand1(0.0,1.0));}
long long times=2025*114514;
const double time_second=0.7;
const double temp_end=1e-2;
const double temp_begin=1e10;
const double temp=0.99999;
int a,b;
char c;
int f(){
return ((c=='+'?a+b:0)+(c=='-'?a-b:0)+(c=='*'?a*b:0)+(c=='/'?a/b:0)+(c=='%'?a%b:0));
}
int main(){
cin >> a >> c >> b;
int ans=0;
int x,tempp;
double i;
int tans;
int cnt;
while((clock()/(1.0*CLOCKS_PER_SEC))<time_second&×--){
tans=ans;
cnt=1;
for(i=temp_begin;i>=temp_end;i*=temp){
aa=1;
bb=cnt;
++cnt;
x=Rand2();
tempp=tans;
if(tans>ans){
tans-=x;
}
else{
tans+=x;
}
if(abs(tans-f())<=abs(ans-f())){
ans=tans;
}
else{
if(!use(tans,ans,i)){
tans=tempp;
}
}
}
}
cout << ans;
return 0;
}
/*
*/代码已做防盗
因为是随机,所以不能避免错误,欢迎hack
正解
本题正解其实为二分,但仍不失为一道模拟退火好题