P1883函数题解

https://www.luogu.org/problemnew/show/P1883

这道题是说在[0, 1000]中找到一个值,使得在所有函数中这个值所对应的最大值最小(可能描述的不清楚,详细看题目)。

通过画图发现,如果将最大值连接起来的话,那么所有的点将连成一个类似二次函数的图像,于是我们可以采用三分的方法,

如果进行暴力枚举的话会超时,所以使用三分法。

为什么不用二分呢?二分是不能够判断最小值在那个范围的(自己想一想)

于是用三分,重点在情况判断,对于很多情况,我们应该找到一种能够快捷描述情况的方法,以至于可以将最小值包含在范围中。

下面是代码:

// P1883
#include <iostream>
#include <cstdio>
using namespace std;
const int MAX = 1e4+10;
const double MIN = 1e-9;  
int a[MAX], b[MAX], c[MAX]; 
int T, n; 

double get_max(double pos); 

int main() {
    cin >> T; 
    while (T--) { 
        cin >> n;
        for (int i = 0; i < n; ++i) 
            cin >> a[i] >> b[i] >> c[i]; 
        double l = 0, r = 1000; 
        while (r-l > MIN) { 
            double mid1 = (l+l+r) / 3;  
            double mid2 = (l+r+r) / 3; 
            if (get_max(mid1) > get_max(mid2)) l = mid1;
            else r = mid2;
        }
        printf("%.4lf\n", get_max(l)); 
    }
    return 0;
}

double get_max(double pos) { 
    double max = 0.0;
    for (int i = 0; i < n; ++i) 
        max = max > (a[i]*pos*pos+b[i]*pos+c[i]) ? max : (a[i]*pos*pos+b[i]*pos+c[i]); 
    return max; 
}

题解写的简单,大家可以去看看三分的知识,代码容易实现。

猜你喜欢

转载自www.cnblogs.com/yifeiWa/p/10739026.html