hdu 5105 Math Problem BestCoder#18 1002 求最大值

f(x) = ax^3+bx^2+cx+d,最大值只会出现在几个地方:左端点,右端点,极值点。

求导后是个二次函数,可以求根,然后判断根是否在(L,R)范围内,若在范围内,直接求max(f(x),f(L),f(R))就是最大值了。

PS:要考虑a=0,b=0的情况,WA了一次ORZ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <queue>
#include <ctime>
using namespace std;
#define LL long long
#define ULL unsigned long long
//#define mod 1000000007
#define eps 1e-8
#define MP make_pair
#define REP(i,a,b) for(int i = a; i < b; ++i)
#define RREP(i,a,b) for(int i = b; i > a ; --i)
#define RE freopen("in.txt","r",stdin)
//#define WE freopen("out.txt","w",stdout)
const double INF = 99999;
double a,b,c,d,L,R;
double max(double a,double b)
{
return a>b?a:b;
}
double fun(double x)
{
return fabs(a*x*x*x+b*x*x+c*x+d);
}
int main()
{
while(~scanf("%lf %lf %lf %lf %lf %lf",&a,&b,&c,&d,&L,&R))
{
double ans;
double left = fun(L);
double right = fun(R);
double sans = max(left,right);
if(a==0)
{
if(b == 0){
ans = sans;
}else{
double x = -c/(2*b);
if(x<=R&&x>=L)
ans = fun(x);
else
ans = 0;
ans = max(ans,sans);
}
}
else{
double deta = 4*b*b - 12*a*c;
if(deta < 0){
ans = 0;
ans = max(ans,sans);
}
else{
double x1 = (sqrt(deta)-2*b)/(6*a);
double x2 = (-sqrt(deta)-2*b)/(6*a);
double k1,k2;
if(x1<=R&&x1>=L)
k1 = fun(x1);
else
k1 = 0;
if(x2<=R&&x2>=L)
k2 = fun(x2);
else
k2 = 0;
ans = max(k1,k2);
ans = max(ans,sans);
}
}
printf("%.2lf\n",ans);
}
}