简单题两道(三分求极值)

来源:互联网 发布:网络时髦用语2017最新 编辑:程序博客网 时间:2024/05/22 06:52

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
2100200
 
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;
}


原创粉丝点击