跳到正文

题解

题解:CF2041C Cube

_O_u_O_约 4 分钟
原文

这是 2026年8月7日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2026年8月7日
更新
2026年8月10日
篇幅
约 4 分钟
题目
CF2041C

版本

  1. v2当前
  2. v1

n≤12n \le 12,直接模拟退火。

什么是模拟退火

模拟退火的原理也和金属退火的原理近似:将热力学的理论套用到统计学上,将搜寻空间内每一点想像成空气内的分子;分子的能量,就是它本身的动能;而搜寻空间内的每一点,也像空气分子一样带有“能量”,以表示该点对命题的合适程度。演算法先以搜寻空间内一个任意点作起始:每一步先选择一个“邻居”,然后再计算从现有位置到达“邻居”的概率。 —— 百度百科

他的核心思想就是先随机一组解,如果解比现在的情况优秀,我们就使用这组解,否则我们以一定的概率去使用这组解,而这个概率是 e−dtte^{\frac{-dt}{t}},ee 是自然常数,dtdt 是现在和新的解的差,tt 是当前温度。

当你在跑结束一次退火后,如果你还有时间可以多跑,当然你可以这样写,但请保证你的单次退火时间加上你设的上限最后不会超时。

C++
while(clock() * 1.0 / CLOCKS_PER_SEC <= 0.99){
		g();
}

代码

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 50;
int a[N][N][N];
int n;
struct node{
    int x,y,z;
}team[N];
int ans = 1e18,kk;
int g(){
    int sum = 0;
    for(int i = 1;i <= n;i++){
        sum += a[team[i].x][team[i].y][team[i].z];
    }
    if(ans >= sum){
        ans = sum;
    }
    return sum;
}
double randd(){
    return rand() * 1.0 / RAND_MAX;
}
void f(){
    node back[N];
    memcpy(back, team, sizeof(team));
    for(double t = 1e5;t >= 1e-4;t *= 0.999){
        memcpy(team, back, sizeof(team));
        int tp = rand() % 3 + 1;
        int xx = rand() % n + 1, yy = 0;
        do{
            yy = rand() % n + 1;
        }while(yy == xx);
        int dx = xx, dy = yy;
        if(tp == 1){
            swap(team[dx].x, team[dy].x);
        }
        else if(tp == 2){
            swap(team[dx].y, team[dy].y);
        }
        else if(tp == 3){
            swap(team[dx].z, team[dy].z);
        }
        int cnt = g();
        int dt = cnt - kk;
        if(dt < 0 || exp(-dt / t) > randd()){
            kk = cnt;
            memcpy(back, team, sizeof(team));
        }
    }
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(nullptr);
    cin >> n;
    srand(time(nullptr));
    for(int x = 1; x <= n; x++){
        for(int y = 1; y <= n; y++){
            for(int z = 1; z <= n; z++){
                cin >> a[x][y][z];
            }
        }
    }
    for(int i = 1; i <= n; i++){
        team[i] = {i, i, i};
    }
    random_shuffle(team + 1, team + n + 1);
    kk = g();
    while((double)clock() / CLOCKS_PER_SEC < 2.95){
        f();
    }
    cout << ans;
    return 0;
}

轻松 AC