[Template] Find thirds

Find thirds and almost binary search, is to some sections were divided into three sections instead of two.

Look for the third convex function, i.e. there is a vertex, the sides of an monotonic function (for example a quadratic function).

For a period of interval of l ~ r, it is divided into l ~ L, L ~ R, R ~ r three sections.

In an example case where the apex is at a maximum,

If f (L) <f (R), the highest point, or L ~ R R ~ r in.

If f (L)> f (R), the highest point or l ~ L L ~ R in

while(r-l>=1e-6) {
    double k = (r-l)/3.0;
    double L = l+k;
    double R = r-k;
    if(f(L) < f(R)) l = L;
    else r = R;
}
printf("%.5lf",l);

 

Example: Luogu 3382 [template] trichotomy

PS: About Polynomial law, there is a simple algorithm called Horner's method.

example:

 $10x^5+9x^4+8x^3+7x^2+6x+5$

$=x(10x^4+9x^3+8x^2+7x+6)+5$

$=x(x(10x^3+9x^2+8x+7)+6)+5$

$=x(x(x(10x^2+9x+8)+7)+6)+5$

$=x(x(x(x(10x+9)+8)+7)+6)+5$

$=x(x(x(x(x(10)+9)+8)+7)+6)+5$

Use code to write is so qwq

ans = 0;
for(int i = 0; i <= n; i++)
    ans = ans*x+a[i];

This question is then complete code follows ..

 

#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#define MogeKo qwq
using namespace std;
int n;
double a[15],l,r;

double f(double x){
    double ret = 0;
    for(int i = 0;i <= n;i++)
        ret = ret*x+a[i];
    return ret;
}

int main(){
    scanf("%d%lf%lf",&n,&l,&r);
    for(int i = 0;i <= n;i++)
        scanf("%lf",&a[i]);
    while(r-l>=1e-6){
        double k = (r-l)/3.0;
        double L = l+k;
        double R = r-k;
        if(f(L) < f(R)) l = L;
        else r = R;
    }
    printf("%.5lf",l);
    return 0;
}
View Code

 

 

 

Guess you like

Origin www.cnblogs.com/mogeko/p/10992952.html