HDU 5105 Math Problem(BestCoder Round #18)

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
 
题意:求给出的三次方程绝对值( f(x)=|ax3+bx2+cx+d|(LxR))的区间最大值。将这个三次方程求导得3a*x^2+2*b*x+c,解这个二次方程得到两个解x1,x2,在x1,x2处就是f(x)的最大值,那么我们只需要判断这两个点是否在区间[l,r]中,并且判断区间端点的f[l],f[r],和f[x1],f[x2]的大小即可。
#include<stdio.h>
#include<string.h>
#include<queue>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;

const int N=1e4+10;
const int INF=0x3f3f3f3f;
const int MOD=1e9+7;

typedef long long LL;

void Solve(double &x1, double &x2, int &flag, double a, double b, double c) ///求解二次方程
{
    if (a == 0) ///要是二次项系数为0,只有一个根,且不能用求根公式
    {
        x1 = x2 = -c/b;
        flag = 1; ///flag标记该方程是否有根
        return ;
    }
    if (b*b-4*a*c >= 0)
    {
        x1 = (-b-sqrt(b*b-4*a*c))/(2*a);
        x2 = (-b+sqrt(b*b-4*a*c))/(2*a);
        flag = 1;
    }
}

void Result(double a, double b, double c, double d, double l, double r, double x, double &Max) 
{ ///代入求函数值
    if(x >= l && x <= r)
        Max = max(Max, fabs(a*x*x*x+b*x*x+c*x+d));
}

int main ()
{
    double a, b, c, d, l, r, x1, x2, Max;
    int flag;

    while (scanf("%lf %lf %lf %lf %lf %lf", &a, &b, &c, &d, &l, &r) != EOF)
    {
        Max = -INF;
        flag = 0;

        Solve(x1, x2, flag, 3*a, 2*b, c);

        Result(a, b, c, d, l, r, l, Max);
        Result(a, b, c, d, l, r, r, Max);

        if (flag)
        {
            Result(a, b, c, d, l, r, x1, Max);
            Result(a, b, c, d, l, r, x2, Max);
        }

        printf("%.2f\n", Max);
    }

    return 0;
}
posted @ 2015-11-05 13:05  搁浅の记忆  阅读(154)  评论(0编辑  收藏  举报