HihoCoder - 1142 三分·三分求极值

题目链接

三分求函数的最小值;

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;

int main()
{
    ios::sync_with_stdio(false);
    double a,b,c,x,y;
    while(cin>>a>>b>>c>>x>>y){
        double l = -200,r = 200;
        double lm,rm,dl,dr;
        while(r-l>1e-8){//控制精度
            lm = l+(r-l)/3,rm=r-(r-l)/3;
            dl = sqrt((lm-x)*(lm-x)+(a*lm*lm+b*lm+c-y)*(a*lm*lm+b*lm+c-y));
            dr = sqrt((rm-x)*(rm-x)+(a*rm*rm+b*rm+c-y)*(a*rm*rm+b*rm+c-y));
            if(dl < dr) r = rm;
//dl小于dr,则最小值一定在l和rm之间
            else  l = lm;
        }
         double d = sqrt((l-x)*(l-x)+(a*l*l+b*l+c-y)*(a*l*l+b*l+c-y));
         printf("%.3f\n",d);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42754600/article/details/81735708