Description
给定 个函数形如 和 。求 阶排列 ,最大化 。
。
Solution
已经轻松最优解。
我们充分发扬人类智慧,参考经典模拟退火解决 TSP(最短哈密顿回路问题),设当前的排列为 ,每次向邻域尝试“走一步”。根据 TSP 的经验,定义邻域结构如下:
- 随机 ,交换 。
- 随机 ,翻转 。
- 随机 ,将 插入至位置 。
void step() {
int op = rand(1, 3);
if (op == 1) {
int i = rand(1, n), j = rand(1, n);
swap(p[i], p[j]);
}
else if (op == 2) {
int l = rand(1, n), r = rand(1, n);
if (l > r) swap(l, r);
reverse(p.begin() + l, p.begin() + r + 1);
}
else {
int i = rand(1, n), j = rand(1, n);
int x = p[i];
p.erase(p.begin() + i);
p.insert(p.begin() + j, x);
}
}模拟退火时,每次尝试走一步至 ,令 ,当前温度为 ,则接受新解的概率为:
注意 的符号, 的指数上一定是个负数,不然就会跟我一样永远接受最劣解导致赛时过不去以为假了。
由于 非常小,温度和降温系数都可以极限一点,我这里取初始温度 ,终止温度 ,降温系数 。为了得到更优质的解在每次退火完随机取邻域内 个点取最大值,最后再卡一下时多跑几次就能直接过了。(事实上不需要这么极限的参数,只是由于我赛时写假了以为过不了,参数调小一点随便最优解)
模拟退火核心代码(注意要开 __int128):
using i128 = __int128;
mt19937 mt{random_device{}()};
vector<int> p, q;
i128 calc() {
i128 x = s;
for (int i = 1; i <= n; i++) {
x = a[p[i]] * (x < 0 ? -x : x) + b[p[i]] * x + c[p[i]];
}
return x;
}
i128 ans = -INF, E;
while ((double)clock() / CLOCKS_PER_SEC < 0.95) {
shuffle(p.begin() + 1, p.end(), mt);
E = calc();
double T = T0;
while (T > Tk) {
q = p;
step();
i128 dE = calc() - E;
if (dE < 0 && rand(1, 10000) / 10000.0 > pow(2.718, dE / T)) p = q;
else E += dE;
ans = max(ans, E);
T *= d;
}
for (int i = 1; i <= 1000; i++) {
q = p;
step();
ans = max(ans, calc());
p = q;
}
}