簡單題兩道(三分求極值)

HDU 2899 Strange fuction


Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8055    Accepted Submission(s): 5535

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<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
double a[5] = {6,8,7,5,0},b[5] = {7,6,3,2,1};
double cal(double x)
{
    double ans = 0;
    for(int i = 0;i < 5; ++i)
    {
        ans += a[i] * pow(x,b[i]);
    }
    return ans;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lf",&a[4]);
        a[4] *= -1;
        double lmid,rmid,l = 0,r = 100;
        while(r - l > 0.000001)
        {
            lmid = l + (r - l) / 3;
            rmid = r - (r - l) / 3;
            if(cal(lmid) > cal(rmid)) l = lmid;
            else r = rmid;
        }
        printf("%.4f\n",cal(lmid));
    }
    return 0;
}

hihoCoder 1142 三分·三分求極值

時間限制:10000ms
單點時限:1000ms
內存限制:256MB

描述

這一次我們就簡單一點了,題目在此:

在直角座標系中有一條拋物線y=ax^2+bx+c和一個點P(x,y),求點P到拋物線的最短距離d。

提示:三分法

輸入

第1行:5個整數a,b,c,x,y。前三個數構成拋物線的參數,後兩個數x,y表示P點座標。-200≤a,b,c,x,y≤200

輸出

第1行:1個實數d,保留3位小數(四捨五入)

樣例輸入
2 8 2 -2 6
樣例輸出
2.437
題意跟它的題目名字一樣樸實,同樣是三分求極小值的模板題。


#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;

double a,b,c,xx,yy;
double cal(double x)
{
    double ans = 0;
    return pow((x - xx),2) + pow((a * x * x + b * x + c - yy),2);
}
double solve()
{
    scanf("%lf %lf %lf %lf %lf",&a,&b,&c,&xx,&yy);
    double l = -200,r = 200,lmid,rmid;
    while(r - l > 0.00001)
    {
        lmid = l + (r - l) / 3;
        rmid = r - (r - l) / 3;
        if(cal(lmid) > cal(rmid)) l = lmid;
        else r = rmid;
    }
    printf("%.3f\n",sqrt(cal(rmid)));
}
int main()
{
    solve();
    return 0;
}


發佈了123 篇原創文章 · 獲贊 14 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章