跳到正文

算法·理论

模板代码——三分

wbqhasvcf约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年11月28日
收录
2026年11月26日
更新
2026年11月26日
篇幅
约 1 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
#define db double 
using namespace std;
const int N=1e4+5;
const db eps=1e-9;

int t,n,a[N],b[N],c[N];
db f(db x)//f函数
{
    db ret=-1e9;
    for(int i=1;i<=n;i++)
        ret=max(ret,a[i]*x*x+b[i]*x+c[i]);
    return ret;
}
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>n;
        for(int i=1;i<=n;i++)
            cin>>a[i]>>b[i]>>c[i];
		//三分求单峰函数最值 
        db l=0,r=1000;
        while(r-l>eps)
        {
            db lmid=l+(r-l)/3,rmid=r-(r-l)/3;
            if(f(lmid)<=f(rmid)) r=rmid;
            else l=lmid;        
        }
        cout<<fixed<<setprecision(4)<<f(l)<<endl;          
    }
    return 0;
}
原文