P10447最短Hamilton距离 (模拟退火)
__RAGNAROK__ · · 题解
思路 :
经典模拟退火,非常简单 %%%
调了
:::
算法思维难度非常低
其中
卡时也是十分重要的!
以下几点:
- 理论上
δ 越大单次正确性越高(有时候又很玄学),反之越小 - 初始温度
T0 一定要足够!!!
#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;
}