【模板】三分求函数极值

P3382 【模板】三分法

#include <bits/stdc++.h>
using namespace std;

const double EPS = 1e-7;
double a[50];
int n; 

double check(double x)
{
	double res = 0.0, t = 1.0;
	
	for(int i = 0; i <= n; i ++){
		res += t * a[i];
		t *= x;
//		cout << res << "
";
	}
// 	puts("");
	return res;
}
int main()
{
	double l, r;
	
	scanf("%d%lf%lf", &n, &l, &r);
	
	for(int i = n; i >= 0; i --){
		scanf("%lf", &a[i]);
	}
	
	while(r - l >= EPS){
		double mid1 = l + (r - l) / 3.0, mid2 = l + (r - l) / 3.0 * 2;
//			cout << check(mid1) << " " << check(mid2) << "
"; 
		if(check(mid1) > check(mid2))    r = mid2;
	
		else    l = mid1;
	}
	
	printf("%.5lf", l);
	return 0;
}

今天的ICPC南京站F题琳雅大佬推出了函数,我居然没想到求极值的方法。。。唉,二分导数找零点也可以啊,居然。。。。。

原文地址:https://www.cnblogs.com/satchelpp/p/14165256.html