P3382三分法-模拟退火

· · 题解

这道题目是今天和神仙@konjac_tbr(貌似神仙改名字了)商量温习所以写的,然后发现题目的一个奇妙性质—>貌似可以模拟退火写

所谓[l-x]单调递增,[x-r]单调递减。无非就是此函数的最大值,所以它就变成了一个给定l--r的区间,和一个n次函数,求出这段区间内函数任意取值所得最大值。

所以考虑模拟退火求最大值,如果位置溢出了就直接改为l或r,因为数据范围给的很小,所以这次退火就并不需要特别高的初温度(T),因为初温特别高的话会导致跳跃范围特别大,而至前面随机的点都是无用的。推荐的话,其实初温弄小数会比较好。

如果您不会模拟退火的话,可以理解为随机一个点去看看这个点是否是最大值—>如果不是,以一定概率接受这个点(删去),再统计沿途的所有点的最大答案。

如果您上面这一段没有看懂,其实您可以直接理解这道题的模拟退火做法为:随机一个点,判断其是否最大,如果比当前答案大就修改答案。

下面给代码:

// luogu-judger-enable-o2
#include<bits/stdc++.h>
using namespace std;
const int N = 20 + 5;
#define double long double
double T = 0.92, delta = 0.99, tt = 1e-14;
double a[N], l, r, eps = 1e-4, ans, num;
int n;
void input(){
    scanf("%d%llf%llf", &n, &l, &r);
    for(int i = 0; i <= n; i++)
        scanf("%llf", &a[i]);
    return ;
}
double get_ans(double x){
    double ans = 0, now = 1;
    for(int i = n; i >= 0; i--){
        ans = ans + a[i] * now;
        now = now * x; 
    }
    return ans;
}
void SA(){
    double now = (l + r) / 2;
    double t = T;
    while(t > tt){
        double temp = now + (rand() * 2 - RAND_MAX) * t;//随机一个点,保证其为正负数—//(rand()*2 - RAND_MAX)
        if(temp < l) temp = l;
        if(temp > r) temp = r;
        double new_ans = get_ans(temp);
        double DE = new_ans - ans;
        if(DE > 0){//如果新答案更优
            ans = new_ans;
            num = temp;
            now = temp;
        }
        t *= delta;
        /*else if(exp(DE/t) * RAND_MAX > rand()){
            now = temp;
        }*///一一定概率接受,这段可删去,一样能过
    }
}
void solve(){
    ans = -999999999;//y一开始ans应该特别小
    int qwq = 12;//跑12次
    while(qwq--){
        SA();
    }
    double x = num;
    printf("%.5llf\n", num);
}
signed main()
{
    srand(time(0));
    input();
    solve();
    return 0;
}