1. 程式人生 > >HDU 2899 求導+二分

HDU 2899 求導+二分

指定區間不滿足單調性   先求導

一階導數=0的時候就是極大值或者極小值,先要把導數求取來,這時候的變數代進函式,就可以求出極值。具體問題還要看時間情況,是最大值還是最小值
#include<stdio.h>
#include<string.h>
#include<math.h>
#define eps 1e-7

double compute1(double x)
{
	double ans = 42*pow(x,6.0) + 48*pow(x,5.0) + 21*x*x + 10*x;
	return ans;
}

double compute2(double x, double y)
{
	double ans = 6*pow(x,7.0) + 8*pow(x,6.0) + 7*pow(x,3.0) + 5*x*x - y*x;
	return ans;
}

double binarySearch(double y)
{
	double l = 0, r = 100.0, mid;
	while(fabs(r - l) >= eps)
	{
		mid =(r + l) / 2.0;
		if( compute1(mid) - y > eps )
			r = mid - eps;
		else if( compute1(mid) - y < -eps )
			l = mid + eps;
	}
	return mid;
}

int main()
{
	int t;
	double x, y, ans;
	scanf("%d", &t);
	while(t--)
	{
		scanf("%lf", &y);
		x = binarySearch(y);
		ans = compute2(x, y);
		printf("%.4lf\n", ans);
	}
	return 0;
}