跳到正文

题解

P9025 [CCC2021 S3] Lunch Concert 题解

Comet387约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟
获赞
3
题目
P9025

版本

  1. v1当前

前言

模拟赛有这道题,赛后 A 了,写篇题解纪念一下。

思路

考虑对 cc 模拟退火。

什么是模拟退火?

模拟退火是一种随机化算法。当一个问题的方案数量极大(甚至是无穷的)而且不是一个单峰函数时,我们常使用模拟退火求解。

模拟退火如何实现?

如果新状态的解更优则修改答案,否则以一定概率接受新状态。

我们定义当前温度为 TT,新状态与已知状态(由已知状态通过随机的方式得到)之间的能量(值)差为 ΔE\Delta E(ΔE≥0\Delta E\geq0),则发生状态转移(修改最优解)的概率为:

P(ΔE)={1the new status is bettere−ΔETotherwiseP(\Delta E)=\begin{cases}1&\text{the new status is better}\\e^{\frac{-\Delta E}{T}}&\text{otherwise}\end{cases}

但是,我们需要注意:

  1. 最后输出的是每个人移动时间之和的最小值,而不是 cc;
  2. 退火次数太少会 WA,建议退到即将超过时限再输出。

代码

C++
#include<bits/stdc++.h>
#define int long long  // 一定要开 long long
#define re register
#define rep(i,a,b) for(re int i=(a);i<=(b);++i)
using namespace std;
// 以下是快读
template <typename T> inline void read(T &x) {
    x = 0; re char ch = getchar(); re int f = 1;
    while (!isdigit(ch) && ch ^ '-') ch = getchar();
    if (ch == '-') f = -1, ch = getchar();
    while (isdigit(ch)) x = x * 10 + ch - 48, ch = getchar(); x *= f;
}
// 以上是快读
int n,w[200001],d[200001],p[200001],mx=-9e18,mn=9e18,ansx,ans=9e18;
mt19937 rnd(1145141919);
int chk(int pos) // 计算当 c=pos 时,每个人移动时间之和
{
	int res=0;
	rep(i,1,n) res+=max(abs(p[i]-pos)-d[i],0ll)*w[i];
	return res;
}
void SA() // 模拟退火
{
	double T=100000;
	int nowx=ansx,nxtx,now=ans,nxt;
	while(T>1e-3)
	{
		nxtx=nowx+((rand()*1.0/RAND_MAX)*2-1)*T*100,nxt=chk(nxtx);
		if(nxt<now) now=ans=nxt,ansx=nowx=nxtx;
		if(exp((now-nxt)*1.0/T)>rand()*1.0/RAND_MAX) now=nxt,nowx=nxtx;
		T*=.93;
	}
}
signed main()
{
	cin>>n;
	rep(i,1,n) read(p[i]),read(w[i]),read(d[i]),mx=max(mx,p[i]),mn=min(mn,p[i]);
	while(clock()*1.0/CLOCKS_PER_SEC<.95) SA();
	cout<<ans;
	return 0;
}

后记

其实不难发现答案一定是一个单峰函数,因此也可以使用爬山算法或三分求解,代码留给读者自己编写。

原文