Math Problem
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1078 Accepted Submission(s): 282
Problem Description
Here has an function:
f(x)=|a∗x3+b∗x2+c∗x+d|(L≤x≤R)
Please figure out the maximum result of f(x).
f(x)=|a∗x3+b∗x2+c∗x+d|(L≤x≤R)
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.
(−10≤a,b,c,d≤10,−100≤L≤R≤100)
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)=|a∗x3+b∗x2+c∗x+d|(L≤x≤R) 对于给定区间求函数的最值问题,这个是高中知识的问题,最值的可能点就是导数为0的点和两端点,这样进行推导,其实思路很清晰,但是这道题卡精度! 这就要求我们要考虑的仔细一些!#include<cstdio> #include<iostream> #include<math.h> #include<algorithm> using namespace std; const double eps=1e-9; //浮点数精度问题,定义一个误差范围! double a,b,c,d;double l,r; double get(double n) { return fabs(a*n*n*n+b*n*n+c*n+d); } double num1() { double deta=4*b*b-12*a*c; if(deta<0) return -999; return (-2*b+sqrt(deta))/(6*a); //return (-2*b+pow(deta,1/2))/(6*a); 不明白为什么这里用sqrt能过,但是用pow过不了,下面也一样! } double num2() { double deta=4*b*b-12*a*c; if(deta<0) return -999; return ((-2*b)-sqrt(deta))/(6*a); //return ((-2*b)-pow(deta,1/2))/(6*a); } int main() { while(scanf("%lf%lf%lf%lf%lf%lf",&a,&b,&c,&d,&l,&r)!=EOF) { double t1,t2,t3,t4; t1=get(l);t2=get(r);t3=-9,t4=-9; if(fabs(a)<eps) //考虑a是不是为0(这里是通过比较a的绝对值与eps大小来实现的,这个以后在考虑浮点数的精度时都必须考虑的!) { if(fabs(b)<eps) //若 a,b均为0,那么最值只可能在端点上 { printf("%.2lf\n",max(t1,t2)); } else { t3=get(-c/(2*b)); printf("%.2lf\n",max(t1,max(t2,t3))); } } else { if(num1()>=l&&num1()<=r) { t3=get(num1()); } if(num2()>=l&&num2()<=r) { t4=get(num2()); } printf("%.2lf\n",max(t1,max(t2,max(t3,t4)))); } } }