uva 1476 Error Curves(三分)

題目地址:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4222

思路:

幾個函數圖像相交所形成的圖像仍爲下凸的(若不爲下凸,則在交點處存在先增後減,而由於取局部最大值,不應該選擇遞減部分,矛盾,所以圖像全部爲下凸),下凸函數最小值可用三分法解決:取區間[l,r]的兩個三分點m1和m2,比較F(m1)和F(m2)大小。若F(m1)<F(m2),則解在[l,m2]中;否則解在[m1,r]中。

#include<cmath>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
#define debug
using namespace std;
const double eps=1e-6;
const int maxn=1e4+50;
int n;
double a[maxn],b[maxn],c[maxn];
double val(double x)
{
  double tmp=a[0]*x*x+b[0]*x+c[0];
  for(int i=1;i<n;i++)
  {
    tmp=max(tmp,a[i]*x*x+b[i]*x+c[i]);
  }
  return tmp;
}
int main()
{
#ifdef debu
    freopen("in.txt","r",stdin);
#endif // debug
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(int i=0; i<n; i++)
        {
            scanf("%lf%lf%lf",&a[i],&b[i],&c[i]);
        }
        double l=0.0,r=1000.0,ans;
        for(int step=0;step<1000;step++)
        {
          double mid1=l+(r-l)/3;
          double mid2=r-(r-l)/3;
          if(val(mid1)<val(mid2))
          {
            r=mid2;
          }
          else
          {
            l=mid1;
            ans=l;
          }
        }
        printf("%.4f\n",val(ans));
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章