YT14-HDU-三分查詢求F(x)的最小值

不被看好的青春叫成長發表於2015-02-25

Problem Description

Now, here is a fuction:
  F(x) = 6 * x^7+8*x^6+7*x^3+5*x^2-y*x (0 <= x <=100)
Can you find the minimum value when x is between 0 and 100.

Input

The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has only one real numbers Y.(0 < Y <1e10)

Output

Just the minimum value (accurate up to 4 decimal places),when x is between 0 and 100.

Sample Input

2
100
200

Sample Output

-74.4291
-178.8534

程式碼如下:

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double Equ(double x,double Y)
{
    return 6*pow(x,7)+8*pow(x,6)+7*pow(x,3)+5*pow(x,2)-Y*x;        //返回F(x)
}

int main()
{
    int T,i;
    double Y,low,high,t1,t2;
    cin>>T;
    while (T--)
    {
        cin>>Y;
        low=0,high=100;  
        for (i=1;i<=200;i++)                   //確定三分查詢的次數
        {
            t1=(low+high)/2;
            t2=(t1+high)/2;                   //將0到100分為3份,逐漸縮小查詢範圍
            if (Equ(t1,Y)<Equ(t2,Y))
                high=t2;
            else
                low=t1;
        }
        cout<<setiosflags(ios::fixed)<<setprecision(4)<<Equ(t1,Y)<<endl;    //控制輸出格式
    }
    return 0;
}


解題思路:

題目大意是輸入Y,求F(x)在x屬於【0,100】間的最小值。

用的是三分查詢,二分查詢也可以,但由於不確定F(x)在0到100間的單調性,所以還是三分查詢更適用。




相關文章