跳到正文

个人记录

浅谈模拟退火

ScarletBat约 5 分钟
原文
文章信息与版本

文章信息

发布
2023年4月25日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 5 分钟

版本

  1. v1当前

%你退火

模拟退火与爬山法不同之处就是模拟退火有一定概率会接受非最优解从而跳出局部最优解。而爬山法会陷入局部最优解。

模拟退火通过模拟金属降温,找到最优解。

引用这里一张图:

设T为目前温度,now_ans为现在解,ans为目前最优

则模拟退火接受非最优解解的条件为:

f(x)={1e−ΔEtf(x) = \begin{cases} 1 \\ e^{ \dfrac{-ΔE}{t} } \end{cases}

举个栗子:

C++
#include <bits/stdc++.h> // 模拟退火求最大 
using namespace std;
int n , a[100005] , ans;
inline void SA () // 退火
{
	double t = 100005; // 温度通常设为最大值 
	while (t > 0.000001) // 结束条件 
	{
		int now_ans = a[rand () % n + 1];
		if (now_ans < ans) ans = now_ans; // 如果比现在解更优就直接赋值 
		else if (exp ((- now_ans - ans) / t) * RAND_MAX > rand ()) ans = now_ans;
		// 一定概率接受更劣解 
		t *= 0.97; // 缓慢降温 
	}
}
signed main ()
{
	srand (time (0)); // 一个好的随机种子 
	cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	for (int i = 1; i <= n * 5; i++) SA ();
	// 多跑几遍更准却 
	cout << ans; 
	return 0;
}

注意:模拟退火可不是用来求这个的,这只是举个栗子。

接下来看例题:P3878 分金币

一道退火”水紫”,每次有一定几率交换金币,每次的now_ans为两堆金币的差。代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
inline long long read ()
{
	long long s = 0 , f = 1;
	char c = getchar ();
	while (c < '0' || c > '9')
	{
		if (c == '-') f = -1;
		c = getchar ();
	}
	while (c >= '0' && c <= '9')
	{
		s = (s << 1) + (s << 3) + (c ^ 48);
		c = getchar ();
	}
	return s * f;
}
long long n , a[305] , ans = INT_MAX , mid , tmp;
inline long long func ()
{
	long long _1 = 0 , _2 = 0;
	for (register int i = 1; i <= ((n + 1) / 2); ++i) _1 += a[i];
	for (register int i = ((n + 1) / 2 + 1); i <= n; ++i) _2 += a[i];
	return abs (_1 - _2);
} // 求差
inline void M ()
{
	double t = 100000;
	while (t > 1e-5)
	{
		long long aa = rand () % mid + 1 , b = (rand () % (mid + tmp)) + 1 + mid;
		if (aa == b) continue;
		swap (a[aa] , a[b]);
		long long c = func ();
		if (c < ans) ans = c;
		else if (exp (-(ans - c) * 1.0 / t) > rand ()) swap (a[aa] , a[b]);
		t *= 0.97;
	}
}
signed main ()
{
	srand (time (0));
	int t = read ();
	for (register int ii = 1; ii <= t; ++ii)
	{
		n = read ();
		if (n == 1) // 特判,不然会RE
		{
			long long d; cin >> d;
			cout << d << "\n";
			continue;
		}
		mid = n >> 1;
		tmp = n % 2;
		for (register int i = 1; i <= n; ++i) a[i] = read ();
		for (register int i = 1; i <= 667; ++i) M ();
		cout << ans << endl;
		ans = INT_MAX;
	}
	return 0;
}
原文