跳到正文

算法·理论

随机化专题讲解

Python_enjoy约 40 分钟
原文
文章信息与版本

文章信息

发布
2026年3月17日
收录
2026年3月17日
更新
2026年11月20日
篇幅
约 40 分钟

版本

  1. v2当前
  2. v1

这个文章综合了浅谈随机化和再谈随机化,并且进行了一些修改(基本算是重构了)。

若要引用,请注明出处。

在浅谈随机化中,@Redshift_Shine 在评论区里指出了优化的方向。在此感谢他!

本文支持的语言标准是 C++14,更高版本应该也适用。

根据 CCF 所说,NOI 系列比赛 C++ 语言标准为 C++14。

题单在这:Python_enjoy 的随机化好题。

如果要看技巧,可以直接拖到最后。

前言 - 我们为什么要学习随机化

随机化是一种极好的思想,当我们想不出正解的时候,我们就可以使用随机化。

我们有的时候可以使用随机化过掉许多极难的题。

我们将会在这篇文章里,由浅入深,一步步讲解随机化。

从绿题到黑题,随机化所向披靡,骗分无数。

正文

Before we start - 了解我们要使用的工具

分为两种写法,用代码讲解。

这是 rand 的用法:

C++
#include <bits/stdc++.h>
using namespace std;

int main() {
	srand(time(0));  // rand 初始化
    n = rand();  // 将 n 赋值为一个 0 到 32767 之间的数
    cout << n << endl;
    return 0;
 } 

但是我们发现 rand 生成的数太小了,于是可以使用 mt19937:

C++
#include <bits/stdc++.h>
using namespace std;
mt19937 rnd(time(NULL));   // mt19927 初始化
int main() {
    n = rnd();  // 将 n 赋值为一个 0 到 2^31-1 之间的数
    cout << n << endl;
    return 0;
 } 

简单的随机化

其实我个人对这篇文章的定义是主要讲解模拟退火的,简单的随机化正确率并不高,适用范围也很小,所以不仔细讲解,想了解可以打开

例题

P2210 [USACO13OPEN] Haywire B

先读一下题再回来看。

这道题正解是状压 DP,但是我们可以用随机化 AC。

用一个数组 aa 来表示奶牛的位置,每次随机打乱 aa 数组并计算当前的值,答案为最小值。

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 12 + 5;
const int M = 5;
const int INF = 0x3f3f3f;
const double down = 0.996;
int n, a[N], fri[N][M];
signed main() { 
    mt19937 rnd(time(NULL));
	cin >> n;
	for (int i = 1; i <= n; i++) {
		a[i] = i;
	}
	for (int i = 1; i <= n; i++) {
		cin >> fri[i][1] >> fri[i][2] >> fri[i][3];
	}
	
	int temp = 2000000;
	int ans = INF;
	while (temp--) {
		shuffle(a + 1, a + n + 1 , rnd);
		
		int tot = 0;
		for (int i = 1; i <= n; i++) {
			for(int j = 1; j <= 3; j++) {
				tot += abs(a[i] - a[fri[i][j]]);
			}
		}
		ans = min(ans, tot / 2);
	}
	
	cout << ans;
	return 0;
}

我们再给出另外一道题。

P5870 [SEERC 2018] Modern Djinn

此题正确题面。

使用随机化。

随机第 ii 个人的心情为 moodimood_i,是 11 的时候心情好,00 的时候心情不好。代码就像下面这样:

C++
for (int i = 1; i <= n; i++) {
    mood[i] = rand() & 1;
}

然后判断这时候可以实现多少个人的愿望:

C++
int cnt = 0;
for (int i = 1; i <= m; i++) {
    if (mood[x[i]] && !mood[y[i]]) {
        ++cnt;
    }
}

当 cnt≥⌊m/4⌋+1cnt \geq \lfloor m/4 \rfloor +1 的时候输出答案:

C++
if (cnt >= m / 4 + 1) {
    printf("%d\n" ,cnt);
    for (int i = 1; i <= m; i++) {
	    if (mood[x[i]] && !mood[y[i]]) {
	        printf("%d " , i);
	    }
	}
    puts("");
    break;
}

但如果 cnt<⌊m/4⌋+1cnt < \lfloor m/4 \rfloor +1,那么就重复之前的步骤,随机人的心情。

完整 AC 代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 5;
const int M = 200000 + 5;
int n, m;
int x[M], y[M];
bool mood[N];
int qcin()
{
	int t=0,f=1;
    char c=getchar(); 
    while(c<'0' || c>'9')
    {
        if(c=='-')
        {
        	f=-1;
		}
        c=getchar();
    }
    while(c>='0' && c<='9')
    {
    	t=t*10+c-'0';
		c=getchar();
	}
    return t*f;
}
signed main() {
    srand(72183);
    int T=qcin();
    while (T--) {
        n=qcin();
        m=qcin();
        for (int i = 1; i <= m; i++) {
            x[i]=qcin();
            y[i]=qcin();
        }
        while (true) {
            for (int i = 1; i <= n; i++) {
                mood[i] = rand() & 1;
            }
            int cnt = 0;
            for (int i = 1; i <= m; i++) {
                if (mood[x[i]] && !mood[y[i]]) {
                    ++cnt;
                }
            }
            if (cnt >= m / 4 + 1) {
                printf("%d\n" ,cnt);
                for (int i = 1; i <= m; i++) {
	                if (mood[x[i]] && !mood[y[i]]) {
	                    printf("%d " , i);
	                }
	            }
                puts("");
                break;
            }
        }
    }
    return 0;
}

爬山算法

有的时候,简单的随机化无法满足我们的需求,就需要一些特别的算法。这里先介绍一个随机化算法:爬山算法。

(闲话:个人认为爬山算法要比模拟退火难理解很多,至少我就是先看懂模拟退火再看懂爬山的,所以如果看不懂可以先看模拟退火再回来看)

如果你学完模拟退火后回来看

你可以发现模拟退火到爬山只有一个区别:删掉了概率变化一段。

实际上确实如此,模拟退火这么做是防止你在一个局部的最优解上困住的,而你既然知道了这是一个单峰函数,就不需要跳出了。

摘自 OI wiki:

爬山算法一般会引入温度参数。类比地说,爬山算法就像是一只兔子喝醉了在山上跳,它每次都会朝着它所认为的更高的地方(这往往只是个不准确的趋势)跳,显然它有可能一次跳到山顶,也可能跳过头翻到对面去。不过没关系,兔子翻过去之后还会跳回来。显然这个过程很没有用,兔子永远都找不到出路,所以在这个过程中兔子冷静下来并在每次跳的时候更加谨慎,少跳一点,以到达合适的最优点。

兔子逐渐变得清醒的过程就是降温过程,即温度参数在爬山的时候会不断减小。

爬山算法只能适用在单峰函数上面。

这里给出一道例题:

P3382 三分

这题可以使用三分解决,但我更想要使用爬山算法来解决。

根据上面的思想,我们可以写出下面的代码:

C++
#include <bits/stdc++.h>
using namespace std;
int n;
double a[10005];
double dx, now, l, r;
const double sT = 4e3;  // 初始温度
const double eT = 1e-17;  // 结束温度 
const double dn = 0.996;  // 降温系数 
double energy(double x) {
	double tot = 0;
	for(int i = 0; i <= n; i++) {
		tot += a[i] * pow(x, i);
	}
	return tot;
}
void SA() {
	double T = sT;
	while (T > eT) {
		double tx = dx + (rand() * 2 - RAND_MAX) * T;  // 我们在这里随机一个 l 到 r 之间的实数 
		if (tx < l) tx = l;
		if (tx > r) tx = r;
		
      	double temp = energy(tx);
      	double delte = now - temp;
      	if(delte < 0) {
      		dx = tx;
      		now = temp;
		}
		T *= dn;
	}
}
int main() {
    srand(time(0));
	cin >> n >> l >> r;
	for (int i = 0; i <= n;  i++) {
		cin >> a[n - i];
	}
	dx = (l + r) / 2;
	now = energy(dx);
	while (((double)clock() / CLOCKS_PER_SEC) < 0.9)  // 这个其实就是一个卡时限的,因为我们一次爬山包括后面的退火一次不一定能够到达最优解,于是要做多次
	    SA();
	cout << fixed << setprecision(7) << dx << endl;
	return 0;
} 

另外给出一道例题,也是正解三分。

P1883 【模板】三分 / 函数 / [ICPC-Chengdu 2010] Error Curves

容易判断这是一个单峰函数,使用爬山算法。

代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
int n;
struct node{
	int x, y, w;
}a[10005];
double dx,now;
double energy(double x) {
	double tot = -1e20;
	for (int i = 1; i <= n; i++) {
		tot = max(tot, a[i].x * x * x + a[i].y * x + a[i].w);
	}
	return tot;
}
const double sT = 3e3;
const double eT = 1e-17;
const double dn = 0.985;
void hillclimb() {
	double t = sT;
	while (t > eT) {
		double tx = dx + (rand() * 2 - RAND_MAX) * t;
		if (tx < 0) tx = 0;
		if (tx > 1000) tx = 1000;
		
      	double temp = energy(tx);
      	double delte = temp - now;
      	if (delte < 0) {
      		dx = tx;
      		now = temp;
		}
		t *= dn;
	}
}
void solve() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i].x >> a[i].y >> a[i].w;
	}
	dx = 500;
	now = energy(dx);
	hillclimb();
	cout << fixed << setprecision(4) << energy(dx) << endl;
}
int main() {
	int T;
	cin >> T;
	while (T--) {
		solve();
	}
	return 0;
} 

至于我们为什么要用它而不是三分,我们在后面讲解。

模拟退火

模拟退火,就是对爬山算法进行了一点改进,从而可以适用于多峰函数。

看过《锻刀大赛》吗?如果有,你一定记得退火,将金属加热到合适温度,保温一定时间,然后‌随炉缓慢冷却‌,选手们用他们来加固刀剑,我们用来加固程序。

不用人话来讲,模拟退火源于冶金学中的退火工艺。固体在高温下粒子无序运动(高能量),缓慢冷却时粒子逐渐趋于有序排列,最终在常温下达到能量最低的晶体基态。

我们设一个温度,当前温度有一个状态,我们进行了一次变化(一般依赖于温度),创造出一个新的状态,如果这个解我们接受,状态就变为我们的新状态。最后降温。

什么时候我们接受这个解?我们使用 Metropolis 接受准则:

  • Metropolis 接受准则:对于当前解 xx 和新解 x′x',能量差 ΔE=f(x′)−f(x)\Delta E = f(x') - f(x):
    • 若 ΔE<0\Delta E < 0(新解更优),无条件接受;
    • 若 ΔE≥0\Delta E \ge 0(新解更劣),以概率 P=exp⁡(−ΔE/T)P = \exp(-\Delta E / T) 接受。 这一机制赋予了算法在高温阶段“容忍劣解”的能力,使其能主动跨越能量势垒,跳出局部最优陷阱。

想想看就可以知道,这样做最后状态就会落到全局最优解附近。

这里给出一个视频,有助于理解。

为什么模拟退火是对的?这很难说,说起来很复杂(其实是笔者也不懂),于是让 Qwen 生成了一份,可以点开看(不过没必要)。

正确性

模拟退火之所以被认为具有极高的正确性和鲁棒性,并非仅凭经验,而是有严格的数学理论支撑:

  • 马尔可夫链模型与遍历性: 算法在每个固定温度下的状态转移构成一个有限状态、不可约、非周期的齐次马尔可夫链。理论证明表明,该链满足细致平衡条件(Detailed Balance Condition),其平稳分布服从玻尔兹曼分布(Gibbs Distribution):πi(T)∝exp⁡(−Ei/T)\pi_i(T) \propto \exp(-E_i / T)。这意味着在热平衡状态下,系统处于低能量状态的概率显著高于高能量状态。
  • 渐近全局收敛定理: 整个降温过程构成了一个非齐次马尔可夫链。Aarts、Korst 及 Laarhoven 等学者在20世纪80年代末严格证明:只要降温速度足够慢(例如满足对数冷却律 Tk≥Γln⁡(k+1)T_k \ge \frac{\Gamma}{\ln(k+1)},其中 Γ\Gamma 为与能量景观相关的常数),且在每个温度下进行充分的迭代以达到热平衡,算法将以概率 1 收敛到全局最优解集。这一结论是现代智能优化理论的基石之一。
  • 逃逸局部最优的数学保证: 根据 Eyring-Kramers 定律等相关理论,Metropolis 准则使得算法穿越高度为 ΔE\Delta E 的势垒所需的时间与 exp⁡(ΔE/T)\exp(\Delta E / T) 成正比。只要温度 TT 不为零,算法就有非零概率逃离任何局部极小值。相比之下,梯度下降等确定性算法一旦落入梯度为零的区域即永久停滞,而遗传算法等群体智能方法缺乏这种基于温度的精确概率控制,易发生早熟收敛。
  • 探索与利用的动态平衡: 温度参数 TT 显式地调节了“探索”(Exploration)与“利用”(Exploitation)的权衡。高温时 exp⁡(−ΔE/T)≈1\exp(-\Delta E / T) \approx 1,算法近似于随机游走,广泛探索解空间;低温时 exp⁡(−ΔE/T)≈0\exp(-\Delta E / T) \approx 0,算法聚焦于当前最优邻域进行精细开发。这种连续的、可控的相变过程是其优于许多其他启发式算法的根本原因。

尽管模拟退火在理论上具备“概率1收敛”的完美性质,但这依赖于“无限缓慢降温”和“无限长迭代时间”的理想假设。在实际工程应用中,受限于计算资源,通常采用更快的降温策略(如几何降温),此时算法只能保证以“高概率”找到全局最优或高质量近似解,而非绝对必然。此外,收敛速率随问题维度增加呈指数级下降,这与全局优化问题本身的 NP-hard 性质一致。

按照现在 AI 流行的一句话总结就是:模拟退火就是如果新状态的解更优就直接接受这个状态,否则以一定概率接受新状态。

这么说讲不清楚,结合一道经典例题来说吧。


P1337 [JSOI2004] 平衡点 / 吊打XXX

这道题爬山算法是这么写:

C++
#include <bits/stdc++.h>
using namespace std;
int n;
struct node{
	double x, y, w;
}a[1005];
double dx, dy, now;
double energy(double x,double y) {
	double tot = 0;
	for (int i = 1; i <= n; i++) {
		tot += sqrt((a[i].x - x) * (a[i].x - x) + (a[i].y - y) * (a[i].y - y)) * a[i].w;
	}
	return tot;
}
const double sT = 4e3;
const double eT = 1e-15;
const double dn = 0.996;
void hillclimb() {
	double T = sT;
	while (T > eT) {
		double tx = dx + (rand() * 2 - RAND_MAX) * T;
      	double ty = dy + (rand() * 2 - RAND_MAX) * T;
      	double temp = energy(tx, ty);
      	double delte = temp - now;
      	if (delte < 0) {
      		dx = tx;
      		dy = ty;
      		now = temp;
      	}
		T *= dn;
	}
}
int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i].x >> a[i].y >> a[i].w;
		dx += a[i].x;
		dy += a[i].y;
	}
	dx /= n, dy /= n;
	now = energy(dx, dy);
	while (((double)clock() / CLOCKS_PER_SEC) < 0.9) 
		hillclimb();
	cout << fixed << setprecision(3) << dx << " " << dy;
	return 0;
} 

这个代码只能拿 67 分,我们要使用模拟退火优化。其实模拟退火没有什么改变,就是在 hillclimb 做出了一点改变,但是为了区分算法,我们就把 hillclimb 改成 SA 吧(Simulated annealing 的英语缩写)。

SA 的代码如下:

C++
#include <bits/stdc++.h>
using namespace std;
mt19937 rnd(time(NULL));
int n;
struct node{
	double x, y, w;
}a[1005];
double dx, dy, now;
double ax, ay, best;
double energy(double x, double y) {
	double tot = 0;
	for (int i = 1; i <= n; i++) {
		tot += sqrt((a[i].x - x) * (a[i].x - x) + (a[i].y - y) * (a[i].y - y)) * a[i].w;
	}
	if (tot < best) {  // 模拟退火有概率接受看起来更劣的解,所以我们就要随时记录最优解 
		best = tot;
		ax = x;
		ay = y;
	}
	return tot;
}
const double sT = 4e3;
const double eT = 1e-15;
const double dn = 0.996;
void SA() {
	double T = sT;
	while (T > eT) {
		double tx = dx + 1.0 * (rand() * 2 - RAND_MAX) * T;
      	double ty = dy + 1.0 * (rand() * 2 - RAND_MAX) * T;
      	double temp = energy(tx, ty);
      	double delta = temp - now;
      	if (delta < 0) {
      		dx = tx;
      		dy = ty;
      		now = temp;
      	}
      	else if (exp(-delta / T) * RAND_MAX > rand()) {   //  这里体现了概率最受更劣解 
			dx = tx;
			dy = ty;
		}
		T *= dn;
	}
}
int main() {
	srand(time(0));
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i].x >> a[i].y >> a[i].w;
		dx += a[i].x;
		dy += a[i].y;
	}
	best = 1e18;
	dx /= n, dy /= n;
	now = energy(dx, dy);
	
	while (((double)clock() / CLOCKS_PER_SEC) < 0.9) 
		SA();
	cout << fixed << setprecision(3) << ax << " " << ay;
	return 0;
} 

选择使用哪个算法

有的时候,我们需要使用模拟退火,但有的时候使用爬山算法,更有的时候简单的随机化就可以搞定。这需要我们的考虑。下面给出几个例题。


P1064 [NOIP 2006 提高组] 金明的预算方案

没错,这道经典的分组背包的题可以使用模拟退火(绝不是因为我打不出背包),虽然我调了半年(因为小时候没开智打错了)。

对这题进行分析,发现 m≤60m\leq60,很小,果断选择模拟退火。

直接暴力求就可以了,然后你大概会写出这样的代码:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 60 + 5;
int n, v[N], p[N], q[N], m;
int h[N];
int now;
int best;
int energy() {
	for (int i = 1; i <=m; i++) {
		if(h[i]) {
			if(h[q[i]]==0) {
				return -1;
			}
		}
	}
	int tot = 0;
	int ans = 0;
	for(int i = 1; i <= m; i++) {
		if(h[i]) {
			ans += v[i] * p[i];
			tot +=v[i];
		}
		if(tot > n) {
			return -1;
		}
	}
	return ans;
}

const double sT = 1e3;
const double eT = 1e-7;
const double dn = 0.9;
void SA() {
	double T = sT;
	while (T > eT) {
		int dx = rand() % m + 1;
		h[dx] = !h[dx];
		int temp = energy();
		h[dx] = !h[dx];
		if(temp == -1) {
			continue;
		}
		int delta = now - temp;
		best = max(best, temp);
		if (delta < 0) {
			now = temp;
			h[dx] = !h[dx];
		}
		else if (exp(-delta / T) * RAND_MAX > rand()) {
			h[dx] = !h[dx];
		}
		T *= dn;
	}
}
signed main() {
	srand(time(0));
	h[0] = true;
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		cin >> v[i] >> p[i] >> q[i];
	}
	while (((double)clock()/CLOCKS_PER_SEC) < 0.98) {
		SA();
	}
	cout << best;
	return 0;
} 

可以发现只有 80pts,原因在这一行:

C++
else if (exp(-delta / T) * RAND_MAX > rand()) {
	h[dx] = !h[dx];
}

注意到这里变化很大,可以将其改为一下形式:

C++
else if (100 * exp(-delta / T) * RAND_MAX > rand()) {
	h[dx] = !h[dx];
}

然后?AC 了。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 60 + 5;
int n, v[N], p[N], q[N], m;
int h[N];
int now;
int best;
int energy() {
	for (int i = 1; i <=m; i++) {
		if(h[i]) {
			if(h[q[i]]==0) {
				return -1;
			}
		}
	}
	int tot = 0;
	int ans = 0;
	for(int i = 1; i <= m; i++) {
		if(h[i]) {
			ans += v[i] * p[i];
			tot +=v[i];
		}
		if(tot > n) {
			return -1;
		}
	}
	return ans;
}

const double sT = 1e3;
const double eT = 1e-7;
const double dn = 0.9;
void SA() {
	double T = sT;
	while (T > eT) {
		int dx = rand() % m + 1;
		h[dx] = !h[dx];
		int temp = energy();
		h[dx] = !h[dx];
		if(temp == -1) {
			continue;
		}
		int delta = now - temp;
		best = max(best, temp);
		if (delta < 0) {
			now = temp;
			h[dx] = !h[dx];
		}
		else if (100 * exp(-delta / T) * RAND_MAX > rand()) {
			h[dx] = !h[dx];
		}
		T *= dn;
	}
}
signed main() {
	srand(time(0));
	h[0] = true;
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		cin >> v[i] >> p[i] >> q[i];
	}
	while (((double)clock()/CLOCKS_PER_SEC) < 0.98) {
		SA();
	}
	cout << best;
	return 0;
} 

P2503 [HAOI2006] 均分数据

很明显,这道题数据小的可怕,一般来说简单的随机化就可以搞定。思路确定了,直接给出代码:

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 20 + 5;
const int INF = 0x3f3f3f;
const double down = 0.996;
int n, a[N], b[N], m;
signed main() {
	cin >> n >> m;
	double x_ = 0;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
		x_ += a[i];
	}
	x_ /= m;
	
	int temp = 500000;
	double ans = INF;
	while (temp--) {
		random_shuffle(a + 1, a + n + 1);
		memset(b, 0, sizeof(b));
		for (int i = 1; i <= n; i++) {
			int k = 1;
            for (int j = 2; j <= m; j++) {
                if (b[k] > b[j]) {
                	k = j;
				}
			}
            b[k] += a[i];
		}
		double tot = 0;
		for (int i = 1; i <= m; i++) {
			tot += (b[i] - x_) * (b[i] - x_);
		}
		tot /= m;
		if (tot < ans) {
			ans = tot;
		}
	}
	
	cout << fixed << setprecision(2) << sqrt(ans);
	return 0;
}

P3878 [TJOI2010] 分金币

这道题我们注意到这题没有任何单峰函数的迹象可言,又因为数据过于庞大,直接使用模拟退火。

又由于这题又多组数据不好卡时间,我们直接只让每一个数据的模拟退火运行 5050 遍。

代码如下:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 30 + 5;
const double down = 0.996;
const int INF = 2e10;
int n, a[N], now;
int energy() {
	double tot1 = 0, tot2 = 0;
	for (int i = 1; i <= (n + 1) / 2; i++) {
		tot1 += a[i];
	}
	for (int i = (n + 1) / 2 + 1; i <= n; i++) {
		tot2 += a[i];
	}
	
	return abs(tot1 - tot2);
}
void SA() {
	double t = 4000;
	while (t > 1e-15)
	{
		int tx=(rand()) % ((n + 1) / 2) + 1;
		int ty=(rand()) % ((n + 1) / 2) + ((n + 1) / 2);
		swap(a[tx], a[ty]);
		int temp = energy();
		int delte = temp - now;
		if (delte < 0) {
			now = temp;
		}
		else if (exp(-delte / t) * RAND_MAX < rand()) {
			swap(a[tx], a[ty]);
		}
		
		t *= down;
	}
}
void solve() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
	}
	
	now = INF;
	
	int cs = 50;
	while (cs--) {
		SA();
	}
	
	cout << now << endl;
}
signed main() {
	int t;
	cin >> t;
	while(t--) {
		solve();
	}
	return 0;
}

P5544 [JSOI2016] 炸弹攻击1

这题很明显是一道模拟退火,直接按照模板写出代码来。

但是这样过不了 HACK,我们开始乱搞:

首先,我们可以先以 {∑i=1mpim,∑i=1mqim}\left \{ \frac{\sum_{i=1}^{m} p_i}{m} ,\frac{\sum_{i=1}^{m} q_i}{m} \right \} 为初始点位进行一次模拟退火,然后分别将每一个敌人设为初始点位进行一次模拟退火,这样会让答案越来越接近最优解。但是如果只这样做了话,会 TLE 一堆点,得不偿失。

我们随便动一下参数,再进行去重,然后让设置每一个敌人为初始点位进行一次模拟退火的概率为 34\frac{3}{4}。这样就可以过 HACK 了。

AC 代码:

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 10 + 5;
const int M = 1e3 + 5;
const double down = 0.999;
int n, m, R, ans;
struct peo{
	double x, y;
}b[M];
struct bui{
	double x, y, r;
}a[N];
int bst;
double tx, ty;
double dist(double x1, double y1, double x2, double y2) {
	return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
int energy(double x, double y) {
	double r = R;
	for (int i = 1; i <= n; i++) {
		r = min(r, dist(x, y, a[i].x, a[i].y) - a[i].r);
	}
	int tot = 0;
	for (int i = 1; i <= m; i++) {
		if(dist(x, y, b[i].x, b[i].y) <= r) {
			tot++;
		}
	}
	return tot;
}
void SA() {
	double t = 2000;
	while (t > 1e-10) {
		double dx = tx + (rand() * 2 - RAND_MAX) * t;
		double dy = ty + (rand() * 2 - RAND_MAX) * t;
		int now = energy(dx, dy);
		double delta = bst - now;
		if (delta < 0) {
			tx = dx;
			ty = dy;
			bst = now;
			ans =max(ans, now);
		}
		else if (exp(delta / t) * RAND_MAX < rand()) {
			tx = dx;
			ty = dy;
			bst = now;
		}
		t *= down;
	}
}
map<pair<int, int>, bool> vis;
signed main() {
	srand(132052);
	cin >> n >> m >> R;
	for (int i = 1; i <= n; i++) {
		cin >> a[i].x >> a[i].y >> a[i].r;
	}
	for (int i = 1; i <= m; i++) {
		cin >> b[i].x >> b[i].y;
		tx += b[i].x;
		ty += b[i].y;
	}
	tx /= m;
	ty /= m;
	bst = max(bst, energy(tx, ty));
	SA();
	for (int i = 1; i <= m; i++) {
		tx = b[i].x;
		ty = b[i].y;
		if (((double)clock() / CLOCKS_PER_SEC) > 0.9) break;
		if(!vis[{tx, ty}] && rand() % 4 != 0) {
			SA();
			vis[{tx, ty}] = true;
		}
		
	}
		
	cout << ans;
	return 0;
}

P6505 Run Away

这题看上去是一道黑题,但今天我要撕破她的黑大衣,让大家看到她的绿题真面目。

首先我们看一看这道题:

这道题题面清晰易懂,我们思考可以使用什么算法:如果你往计算几何找,你几乎想不到任何做法(除非你了解笔者看了一眼就马上爆炸的三角剖分或 Voronoi 图)。如果你思路清奇,往经典算法想,你或许能够想到二分答案。但是以上的三种做法都挺难实现的,码量极大,思路极复杂。于是,我们选择了第四条路线:随机化。

那使用模拟退火还是爬山算法呢?如果你运气极佳且不愿思考了话,我的建议是模拟退火。但是我们应该严谨分析一下。

分析一下函数,最高峰点旁的其他点,这个点必定劣于先前的点。那么,搜索的点越接近最高峰,值便越大,所以这是单峰函数。综上,爬山算法,启动!

确认的算法,基本就没什么好说的了,使用模板就可以了:

C++
#include <bits/stdc++.h>
using namespace std;
const int N = 1000 + 5;
const double down = 0.9975;
int w, h, n;
int x[N], y[N];
double dis(double x_1, double y_1, double x_2, double y_2) {
    return sqrt((x_1 - x_2) * (x_1 - x_2) + (y_1 - y_2) * (y_1 - y_2));
}
int rand(int l, int r) {
    return rand() % (r - l + 1) + l;
}

double best;
double tx, ty;

double energy(double x0, double y0) {
    double tot = 2e9;
    for (int i = 1; i <= n; i++) {
        tot = min(tot, dis(x0, y0, x[i], y[i]));
    }
    return tot;
}

void work() {
    tx = rand(0, w), ty = rand(0, h);
    double good = -1;
    double t = 3000;
    while (t > 1e-10) {
        double dx = tx + (rand() * 2 - RAND_MAX) * t;
        double dy = ty + (rand() * 2 - RAND_MAX) * t;
        if (dx < 0) {
            dx = 0;
        }
        if (dy < 0) {
            dy = 0;
        }
        if (dx > w) {
            dx = w;
        }
        if (dy > h) {
            dy = h;
        }
        
        double now = energy(dx, dy);
        if (now > good) {
            tx = dx, ty = dy;
            good = now;
            best = max(best, now);
        }
        t *= down;
    }
}
int main() {
    srand(time(0));
    cin >> w >> h >> n;
    for (int i = 1; i <= n; i++) {
        cin >> x[i] >> y[i];
    }
    while(((double)clock() / CLOCKS_PER_SEC) < 0.9) {
        work();
    }
    cout << fixed << setprecision(7) << best;
    return 0;
}

技巧

应试技巧极为重要,尤其是你刚入门的时候,基于我的经验列了一些:

如果是跟序列或整数有关,可以尝试 sT=4e3,eT=1e−7,dn=0.9976sT = 4e3,eT=1e-7,dn=0.9976,正确性不好时可以 sT=1e3sT = 1e3。否则可以尝试 sT=4e3,eT=1e−17,dn=0.9976sT = 4e3,eT=1e-17,dn=0.9976。

如果你认为此题变化较多容易陷入局部陷阱,可以将变化改为:

C++
else if (200 * exp(-delta / T) * RAND_MAX > rand()) {
	// changes
}

后记

重构文章挺累的,点个赞吧。

本文章总字数:19859 字

原文