题解:B2049 最大数输出

· · 题解

省流:模拟退火板子题

思路

我们考虑这道题的加强版:给定一个序列 a ,求这个序列的 最大值。

一个很明显的是,我们钦定 f_x 为序列中比 a_x 大的元素个数,则就可以把 f_x 定为这道题的目标函数。

值得注意的一点是这个函数不是单调的,所以不能使用爬山等算法。

考虑模拟退火,每次随机选择一个点与当前最优解的目标函数值做比较,然后就是套板子了。

回到这道题,由于序列 a 只有 3 个数,所以模拟退火的成功率非常高,参数随便设就可以。

代码

#include<bits/stdc++.h>
#define cen cout << endl
#define c1 cout << 1 << " "
#define cs cout << " ";
using namespace std;
double Rand1(double a,double b){static mt19937 t(random_device{}());uniform_real_distribution<double> f(a,b);return f(t);}
int Rand2(int a,int b){static mt19937 t(random_device{}());uniform_int_distribution<int> f(a,b);return f(t);}
bool use(int a,int b,int t){return (1.0*exp(a-b))/t<(Rand1(0.0,1.0));}
long long    times=1e9;
const double time_second=0.99;
const double temp_end=1e-16;
const double temp_begin=1e7;
const double temp=0.99;
int ar[9];
int f(int x){
    int ans=0;
    for(int i=0;i<3;i++){
        if(ar[i]<x){
            ans++;
        }
    }
    return ans;
}
int main(){
    for(int i=0;i<3;i++){
        cin >> ar[i];
    }
    int ans=ar[0];
    while((clock()/(1.0*CLOCKS_PER_SEC))<time_second&&times--){
        int tans=ans;
        for(double i=temp_begin;i>=temp_end;i*=temp){
            int x=Rand2(0,2);
            int tempans=tans;
            tans=ar[x];
            if(f(tans)>f(ans)){
                ans=tans;
            }
            if(!use(tans,ans,temp)){
                tans=tempans;
            }
            if(f(ans)==2){
                cout << ans;
                return 0;
            }
        }
    }
    return 0;
}