BestCoder Round #18 1002 Math Problem 题解

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)=|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) 对于给定区间求函数的最值问题,这个是高中知识的问题,最值的可能点就是导数为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))));
	}
	} 
}

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值