原创题:B(B)
【题目描述】
用二分法求函数 f(x)=a0*x^n+a1*x^(n-1)+...+an 在区间 [l,r] (保证为单峰)内的最大值。
【输入】
第一行包含三个数,n,l,r 第二行包含 n+1 个数,从 a0 到 an
【输出】
输出包含若干行 每行三个实数,l,r,m。
最后一行为一个实数,即在区间 [l,r] 内 f(x) 取到最大值时的 x。
【样例输入】
3 -0.9981 0.5
1 -3 -3 1
【样例输出】
-1.00 0.50 -0.25
-1.00 -0.25 -0.62
-0.62 -0.25 -0.44
-0.44 -0.25 -0.34
-0.44 -0.34 -0.39
-0.44 -0.39 -0.41
-0.44 -0.41 -0.42
-0.42 -0.41 -0.42
-0.42 -0.41 -0.42
-0.42 -0.41 -0.41
-0.41 -0.41 -0.41
-0.41
【分析】
方法一:直接求导,由于原函数为单峰函数,所以导函数一定具有单调性。故二分导函数即可。
方法二:判断中点处的斜率(增减情况)。
【代码】
#include<bits/stdc++.h>
using namespace std;
const double eps=1e-3;
int n;
double a[13],b[13];
inline double f ( const double x )
{
double tmp=0;
for ( int i=n;i;i-- ) tmp=tmp*x+b[i];
return tmp;
}
int main()
{
double l,r,m;
scanf("%d%lf%lf",&n,&l,&r);
for ( int i=n;i;i-- ) scanf("%lf",a+i),b[i]=a[i]*i;
while ( l+eps<r )
{
m=(l+r)/2;
printf("%.2lf %.2lf %.2lf\n",l,r,m);
if ( f(m)>0 ) l=m;
else r=m;
}
printf("%.2lf\n",l);
}