三分求极值

1142 : 三分·三分求极值

题目传送:hihoCoder - 1142 - 三分·三分求极值

二分适用于单调函数,对于需要逼近的区间做二等分,来求解某点的值等。
三分适用于凸形函数,对于需要逼近的区间做三等分。

AC代码:

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <complex>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#include <functional>
#define LL long long
#define INF 0x7fffffff
using namespace std;

double a, b, c, x, y;

double get_dist(double xx) {
    double yy = a * xx * xx + b * xx + c;
    return sqrt((xx - x) * (xx - x) + (yy - y) * (yy - y));
}

int main() {
    double l = -500, r = 500;
    scanf("%lf %lf %lf %lf %lf", &a, &b, &c, &x, &y);
    while(r - l > 0.000001) {//这里为了保证精度,尽量开小点,因为是分治,即使再小也能够承受
        double d = (r - l) / 3;
        double rm = r - d;
        double lm = l + d;
        if(get_dist(lm) < get_dist(rm)) {
            r = rm;
        }
        else l = lm;
    }
    printf("%.3lf\n", get_dist(l));
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值