三分

在实数域上的三分,设置精度值eps
三分的中间值取1/3区间长度就行
#include<bits/stdc++.h>
using namespace std;
#define _f(i,a,b) for(register int i=a;i<=b;++i)
#define f_(i,a,b) for(register int i=a;i>=b;--i)
#define chu printf
#define ll long long
#define rint register int
#define ull unsigned long long
inline ll re()
{
    ll x=0,h=1;
    char ch=getchar();
    while(ch<'0'||ch>'9')
    {
        if(ch=='-')h=-1;
        ch=getchar();
    }
    while(ch<='9'&&ch>='0')
    {
        x=(x<<1)+(x<<3)+(ch^48);
        ch=getchar();
    }
    return x*h;
}
const int N=510;
int n;
double l,r,mid1,mid2;
double xs[15];
#define eps 1e-6
inline double calc(double x)
{
    double ans=xs[n+1];double my=x;
    f_(i,n,1)
    {
        ans=ans+my*xs[i];
        my=my*x;
    }
    return ans;
}
int main()
{
  // freopen("1.in","r",stdin);
  // freopen("1.out","w",stdout);
    n=re();    
    scanf("%lf",&l);
    scanf("%lf",&r);
    _f(i,1,n+1)scanf("%lf",&xs[i]);

    while((r-l)>eps)
    {
        mid1=l+(r-l)/3,mid2=r-(r-l)/3;
        if(calc(mid1)<calc(mid2))l=mid1;
        else r=mid2;
    }
    chu("%lf",l);
    return 0;
}
/*
3 -0.9981 0.5
1 -3 -3 1
*/
如果是整数域三分,区间长度取r-l>2,留出2~3个值来就跳出,外面取最优,否则会死循环
    int l = 1, r = mx, mid1, mid2;
    while ((r - l) > 2) {
        // cout << l << ' ' << r << ' ' << check(mid1) << ' ' << check(mid2) << endl;
    //    mid1 = (l + r >> 1), mid2 = mid1 + 1;
        mid1=l+(r-l)*1.0/3;mid2=r-(r-l)*1.0/3;
        if (check(mid1) >= check(mid2)) l = mid1;
        else r = mid2;
    } 
    cout << min(min(check(l), check(l+1)), check(l+2)) << endl;
posted on 2022-09-29 19:12  HZOI-曹蓉  阅读(228)  评论(0编辑  收藏  举报