【模拟退火】【爬山算法】模板

本文探讨了退火算法与爬山法在解决优化问题中的区别及应用。通过调整参数delta,作者成功优化了一个特定问题,展示了退火算法在面对局部最优解时的概率接受机制如何帮助跳出局部最小值,而爬山法则会在遇到第一个更优解时停止。文章深入分析了这两种算法在实际问题求解中的表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习博客
题目链接
玄学算法。。。一开始不知道调参wa到怀疑人生
后来尝试改一下delta竟然过了。。。退火和爬山的区别其实就是当没有更优解的时候退火会以一个概率来接收,爬山就不接受。所以把else if(exp((res-temp)/t)*RAND_MAX > rand())注释掉就是爬山了。。

#pragma GCC optimize(2)
#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
#define ft first
#define sd second
#define all(c) ((c).begin()), ((c).end())
#define mp(a, b) make_pair(a, b)
#define pb(x) push_back(x)
const int maxn = 1e5+5;
typedef long long ll;
const ll mod = 1e9+7;
int Case = 1;
int n, m;
struct node{
    double x, y, z;
}cc[maxn];
double res, t;
const double delta = 0.993;
double resx, resy;
double cal(double X, double Y) {
    double rt = 0;
    for(int i = 1; i <= n; i++) {
        double deltax = X-cc[i].x, deltay = Y-cc[i].y;
        rt  += sqrt(deltax*deltax+deltay*deltay)*cc[i].z;
    }
    return rt;
}
void simulate_anneal() {
    t = 2000;
    double x = resx, y = resy;
    while(t > 1e-14) {
        double X = x + ((rand()<<1)-RAND_MAX)*t;
        double Y = y + ((rand()<<1)-RAND_MAX)*t;
        double temp = cal(X, Y);
        if(temp < res) {
            res = temp;
            resx = X;resy = Y;
            x = X;y = Y;
        }
        //else if(exp((res-temp)/t)*RAND_MAX > rand())x = X, y = Y;
        t *= delta;
    }
}
void solve() {
    cin>>n;res = 1e18;
    resx = 0, resy = 0;
    for(int i = 1; i <= n; i++)
        {cin>>cc[i].x>>cc[i].y>>cc[i].z; resx += cc[i].x; resy += cc[i].y;}
    resx /= n;resy /= n;
    simulate_anneal();
    simulate_anneal();
    simulate_anneal();
    printf("%.3f %.3f\n", resx, resy);
    return;
}
int main() {
    srand(19260817);
    ios::sync_with_stdio(false);cin.tie(0);std::cout.tie(0);
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    //freopen("out.txt","w",stdout);
#endif
    //scanf("%d", &Case);
    while(Case--){
        solve();
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值