【二分搜索】HDU-2199 Can you solve this equation?

代码

#include <iostream>
#include <math.h>

using namespace std;

//此题卡精度,这里如果定义成1e-5或者1e-6会报Wrong Answer!
const double L = 1e-8;

double binarySearch(double Y) {
	double left = 0;
	double right = 100;

	while(right-left>L) {
		double mid = (left+right)/2.0;
		double tmp = 8*pow(mid, 4) + 7*pow(mid, 3) + 2*pow(mid, 2) + 3*mid + 6;
		if(tmp-Y>L) {
			right = mid;
		} else if(tmp-Y<-1*L){
			left = mid;
		}
		else{
			return mid;
		}
	}
	return left;
}

int main() {

	int T;
	scanf("%d", &T);

	for(int i=0; i<T; i++) {
		double Y;
		scanf("%lf", &Y);
		if(Y<6 || Y>807020306) {
			printf("No solution!\n");
		} else {
			double ans = binarySearch(Y);
			printf("%.4lf\n", ans);
		}
	}

	return 0;
}

注解

1、可先对此函数求导,易知该函数在[0,100]单调增。
2、因此No solution!的范围就容易得到了。
3、如果有解,就二分搜索。需要注意的是此题卡精度,L的精度一定要设置为1e-7或者1e-8,否则会报Wrong Answer。

结果

【二分搜索】HDU-2199 Can you solve this equation?

相关文章: