题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5105
f(x)=|a∗x3+b∗x2+c∗x+d|, 求最大值。令g(x)=a∗x3+b∗x2+c∗x+d,f(x)的最大值即为g(x)的正最大值,或者是负最小值。a!=0时,g′(x)=3∗a∗x2+2∗b∗x+c 求出g′(x)的根(若存在,x1,x2,由导数的性质知零点处有极值。ans=max(f(xi)|L≤xi≤R).然后考虑两个端点的特殊性有ans=max(ans,f(L),f(R)).
代码:#include <iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
double a,b,c,d,L,R,A,x1,x2,y1,y2,y3,y4,ans;
while(scanf("%lf %lf %lf %lf %lf %lf",&a,&b,&c,&d,&L,&R)!=EOF)
{
y1=0;
y2=0;
y3=0;
y4=0;
if(a==0)
{
if(b==0)
{
y3=a*L*L*L+b*L*L+c*L+d;
if(y3<0)
y3=-y3;
y4=a*R*R*R+b*R*R+c*R+d;
if(y4<0)
y4=-y4;
ans=max(y3,y4);
}
else
{
x1=-c/(2*b);
if(x1<=R && x1>=L)
y1=a*x1*x1*x1+b*x1*x1+c*x1+d;
if(y1<0)
y1=-y1;
y3=a*L*L*L+b*L*L+c*L+d;
if(y3<0)
y3=-y3;
y4=a*R*R*R+b*R*R+c*R+d;
if(y4<0)
y4=-y4;
ans=max(max(y1,y3),y4);
}
}
else
{
A=4*b*b-12*a*c;
if(A>=0)
{
x1=(-2*b+sqrt(A))/(6*a);
x2=(-2*b-sqrt(A))/(6*a);
if(x1<=R && x1>=L)
y1=a*x1*x1*x1+b*x1*x1+c*x1+d;
if(y1<0)
y1=-y1;
if(x2<=R && x2>=L)
y2=a*x2*x2*x2+b*x2*x2+c*x2+d;
if(y2<0)
y2=-y2;
y3=a*L*L*L+b*L*L+c*L+d;
if(y3<0)
y3=-y3;
y4=a*R*R*R+b*R*R+c*R+d;
if(y4<0)
y4=-y4;
ans=max(max(max(y1,y2),y3),y4);
}
else
{
y3=a*L*L*L+b*L*L+c*L+d;
if(y3<0)
y3=-y3;
y4=a*R*R*R+b*R*R+c*R+d;
if(y4<0)
y4=-y4;
ans=max(y3,y4);
}
}
printf("%.2lf\n",ans);
}
return 0;
}