ACM第二次练习—1002

来源:互联网 发布:快手怎么上传网络视频 编辑:程序博客网 时间:2024/05/15 23:50

题意:函数F(x) = 6 * x^7+8*x^6+7*x^3+5*x^2-y*x ,输入y的值,输出它在(0,100)内的极小值。

思路:不难发现F'(x)=0在(0,100)内有唯一解X,当x>X时F'(x)>0,当x<X时F'(x)<0。所以编写两个函数计算F(x)和F'(x)然后对F'(x)进行二分搜索,找到X,输出F(X)即可。

感想:一开始以为要用到三分搜索,后来研究了一下给出的函数,发现二分搜索就可以实现,所以有时候编程要联系数学知识。

代码:

#include<cmath>
#include<stdio.h> 
using namespace std; 
double F(double x,double y)  
{  
    double res=-(y*x),t=x;  
    t*=x;
res+=5*t;   
    t*=x;
res+=7*t;  
t*=t; 
    res+=8*t;
t*=x;
res+=6*t;  
    return res;  

double f(double x,double y)  
{  
    double res=-y,t=x;  
res+=10*t;   
    t*=x;
res+=21*t;  
t*=t*x; 
    res+=48*t;
t*=x;
res+=42*t;  
    return res;  

int main()  
{  
     int T;
     double y;
     scanf("%d",&T);
     while(T--)
     {
      scanf("%lf",&y);
double l=0.0,r=100.0,mid,res;  
        while(l<r)  
        {  
            mid=(l+r)/2.0;  
            res=f(mid,y);  
            if(fabs(res)<1e-10)  
                break;  
            if(res>0)  
                r=mid;  
            else  
                l=mid;  
    }
printf("%.4lf\n",F(mid,y));
}
return 0;
}   

0 0