跳到正文

题解

P10447最短Hamilton距离 (模拟退火)

__RAGNAROK__约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年2月3日
收录
2026年5月3日
更新
2026年11月17日
篇幅
约 4 分钟
题目
P10447

版本

  1. v2当前
  2. v1

思路 :

经典模拟退火,非常简单 %%%

调了 NN 次 δδ 的痛,无人诉说

T0T0均摊乱搞可知大概在1e41e4 ~ 1e51e5之间

DeltaδDeltaδ(退火系数) 没依据 0.99 0.9990.99 ~ 0.999 差不多就行了

LL 是一个小技巧据说可以减小误差

nwansnwans 次局部解 −>-> ansans局部解 −>-> flansflans全局解

通过交换坐标来生成解集

计算方式:

对一个解集PP:

Ans(P)=∑i=2nG[pi−1][pi]Ans(P) = \sum_{i = 2}^{n} G[p_{i-1}][p_{i}]

算法思维难度非常低

MetropolisMetropolis准则为核心的决策函数是该算法最神秘以及重要的地方,有:

{β>0α∞>exp(βT)\begin{cases} β > 0 \\ \frac{α}{∞} > exp(\frac{β}{T}) \end{cases}

其中α∞\frac{α}{∞}是随机的,ββ是新解的贡献,exp(βT)exp(\frac{β}{T})是一个概率,TT为当前温度

卡时也是十分重要的!卡时也是十分重要的!

以下几点:

  1. 理论上 δδ 越大单次正确性越高(有时候又很玄学),反之越小
  2. 初始温度 T0T0 一定要足够 !!!!!!
C++
#include <bits/stdc++.h>

#define int long long

using namespace std;

const int N = 21, L = 49;
const double delta = 0.993/*退火系数*/, T0 = 5000, MIN = 1e-3;
int p[N];
int n, g[N][N];
int flans = 1e18;

inline int getans () {
	int rs = 0;
	for (int i = 2; i <= n; i++) rs += g[p[i - 1]][p[i]];
	return rs;
}
inline double rrand () { return double (rand()) / double (RAND_MAX);}
inline bool YorN (double dt, double Tp) { return (dt > 0 || rrand() < exp(dt / Tp)); }
inline void Solve () {
	for (int i = 1; i <= n; i++) p[i] = i;
	int ans = getans();
	double T = T0;
	while (T > MIN) {
		for (int i = 1; i <= L; i++) {
			int u = rand() % n + 1, v = rand() % n + 1;
			while (u == 1 || v == 1 || u == n || v == n) u = rand() % n + 1, v = rand() % n + 1;
		    swap (p[u], p[v]);
            int nwans = getans();
		    if (YorN (ans - nwans, T)) ans = nwans, flans = min (flans, ans);
		    else swap (p[u], p[v]);
		}
		T *= delta;
	}
}
signed main () {

	ios :: sync_with_stdio (false), cin.tie (NULL);
    srand (time(0)), srand (rand());
	cin >> n;
	for (int i = 1; i <= n; i++)
	  for (int j = 1; j <= n; j++)
	      cin >> g[i][j];
	int st = clock();
	while (clock() - st < 0.925 * CLOCKS_PER_SEC) Solve ();
	cout << flans;
	return 0;
}
原文