三分法求单峰函数函数给定区间内最大值

//求 An * x^n + A(n-1) * x^(n-1) + ... + A1 * x^1 + A0 * x^0 在[l,r]上最大值
//保证函数在[l,r]是单峰函数
#include
using namespace std;
const int MAXN = 15;
const double eps = 1e-6;
int n;
double l, r, cf[MAXN];//cf为系数

double check(double mid)
{
	double ret = 0, now = 1;
	for(int i = 0; i <= n; i++)
		ret += cf[i] * now, now *= mid;
	return ret;
}

int main ()
{
    scanf("%d%lf%lf", &n, &l, &r);
	for(int i = n; ~i; i--) scanf("%lf", &cf[i]);
	while(r-l > eps)
	{
		double mid1 = (l*2 + r) / 3;
		double mid2 = (l + r*2) / 3;
		if(check(mid1) <= check(mid2)) l = mid1;
		else r = mid2 - eps;
	}
	printf("%.5lf\n", l);
}

题目 : Luogu传送门 P3382

你可能感兴趣的:(其它模板)