UVALive 5009

Link:click here
The question:给出n组a,b,c的值,求出函数值最大值的最小值
Solution:三分,黄金分割法(优选法),Fibonacci搜索都可求单峰函数的极值。
Conclusion:跟据题目要求判断循环的次数或者需要控制的精度 Code:

#include 
using namespace std;
const double eps = 1e-9;
int n;
int a[10004], b[10004], c[10004];
double F(double x)
{
    double ans = a[0] * x * x + b[0] * x + c[0];
    for (int i = 1; i < n; i++)
    {
        ans = max(ans, a[i] * x * x + b[i] * x + c[i]);
    }
    return ans;
}
int main()
{
    int T;
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d", &n);
        for (int i = 0; i < n; i++)
        {
            scanf("%d%d%d", &a[i], &b[i], &c[i]);
        }
        double L = 0.0, R = 1000.0;
        double m1, m2;
        while (R - L > eps)
        {
            m1 = L + (R - L) / 3.0;
            m2 = R - (R - L) / 3.0;
            if (F(m1) < F(m2))
                R = m2;
            else
                L = m1;
        }
        printf("%.4f\n", F(L));
    }
    return 0;
}

你可能感兴趣的:(ojs)