码迷,mamicode.com
首页 > 其他好文 > 详细

Bestcoder round 18----B题(一元三次方程确定区间的最大值(包含极值比较))

时间:2014-11-15 21:40:04      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   color   ar   os   sp   java   

Math Problem


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


Problem Description
Here has an function:
  f(x)=|ax3+bx2+cx+d|(LxR)
Please figure out the maximum result of f(x).
 
Input
Multiple test cases(less than 100). For each test case, there will be only 1 line contains 6 numbers a, b, c, d, L and R. (10a,b,c,d10,100LR100)
 
Output
For each test case, print the answer that was rounded to 2 digits after decimal point in 1 line.
 
Sample Input
1.00 2.00 3.00 4.00 5.00 6.00
 
Sample Output
310.00
 
 
代码:
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

// f(x)=|a∗x3+b∗x2+c∗x+d|(L≤x≤R)

int main()
{
    double a, b, c, d, ll, r;
    double mm, dd, ff;
    double gg, hh;

    while(cin>>a)
    {
        cin>>b>>c>>d>>ll>>r;

        dd=(a*pow(ll, 3.0)+b*pow(ll, 2.0)+c*ll+d);
        if(dd<0)
          dd=-dd;
        ff=(a*pow(r, 3.0)+b*pow(r, 2.0)+c*r+d);
        if(ff<0)
          ff=-ff;
        mm=max(dd, ff);

        if((4*b*b - 12*a*c)<0)
        {
            //无解
            printf("%.2lf\n", mm);
            continue;
        }
        else if( (4*b*b - 12*a*c)==0 )
        {
            //有一个解
            if( (-(b)/(3*a))>=ll && (-(b)/(3*a))<=r )
            {
                 gg=-1*(b/3*a);
                 hh=a*pow(gg,3)+b*pow(gg, 2)+c*gg+d;
                 if(hh<0)
                   hh=-hh;
                 if(hh>mm)
                 mm=hh;
                 printf("%.2lf\n", mm);
                 continue;
            }
        }
        else
        {
            //有2个解
            gg=(-b+sqrt(b*b-4*a*c))/2*a;
            if( gg>=ll && gg<=r )
            {
                double q;
            q=a*pow(gg,3)+b*pow(gg, 2)+c*gg+d;
            if(q<0)
              q=-q;
            if(q>mm)
              mm=q;
            }

            hh=(-b*sqrt(b*b-4*a*c))/2*a;
            if(hh>=ll && hh<=r)
            {
               double w;
            w=a*pow(hh,3)+b*pow(hh, 2)+c*hh+d;
            if(w<0)
              w=-w;
            if(w>mm)
              mm=w;
            }

            printf("%.2lf\n", mm);
        }
    }

    return 0;
}

 

Bestcoder round 18----B题(一元三次方程确定区间的最大值(包含极值比较))

标签:des   style   blog   io   color   ar   os   sp   java   

原文地址:http://www.cnblogs.com/yspworld/p/4100206.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!