首页 > 其他分享 >HDU2199 Can you solve this equation? (二分查找)

HDU2199 Can you solve this equation? (二分查找)

时间:2023-03-08 16:31:54浏览次数:45  
标签:HDU2199 No double equation mid solution solve 100


Can you solve this equation?

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 12794    Accepted Submission(s): 5715


 

Problem Description

Now,given the equation 8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,can you find its solution between 0 and 100;
Now please try your lucky.

 

 

Input

The first line of the input contains an integer T(1<=T<=100) which means the number of test cases. Then T lines follow, each line has a real number Y (fabs(Y) <= 1e10);

 

 

Output

For each test case, you should just output one real number(accurate up to 4 decimal places),which is the solution of the equation,or “No solution!”,if there is no solution for the equation between 0 and 100.

 

 

Sample Input

 

 

2
100
-4

Sample Output

 

1.6152
No solution!

本题的大致意思是:8*x^4 + 7*x^3 + 2*x^2 + 3*x + 6 == Y,给出一个Y,算出的X如果在0到100之间,就输出,否则就输出No solution!

题解:题目很简单,但是一开始根本没有思路。此时博主在学二分查找专题,就往二分查找上面想,自己也想不出来。看了大神题解才知道,可以二分x,下限为0,上限为100.用软件画了这个函数,它在0到100之间是单调的,当x等于0最小,Y等于6,当x等于100最大,Y等于807020306.所以等Y<6或者Y>807020306时,输出No solution!如果Y值在这之间,就二分x,在0到100之间,如果x带入公式比Y小,那就放大x,反之就放小x。结束的条件为上限减去下限不大于1e-10(最小数).

误解:将x带入公式算出来的值,很少有情况会等于Y,或者说在double精确范围下,根本不会使得带入x算出的值等于Y,只能让算出的值无限接近Y,那这个x就是答案(x精确度为1e-10)。

具体代码如下:

#include<iostream>
#include<cmath>
#include<cstdio>
int t=0;
using namespace std;
double Search(double y,double low,double high)//在【0,100】内二分x
{
double mid=(high+low)/2.0;
if(high-low>1e-8)
{
if(8.0*pow(mid,4)+7.0*pow(mid,3)+2.0*pow(mid,2)+3.0*mid+6.0>y)
return Search(y,low,mid);
return Search(y,mid,high);

}
return mid;
}
int main()
{
int n;
cin>>n;
while(n--)
{
double y;
cin>>y;
t=0;
if(y<6||y>807020306)
printf("No solution!\n");
else
printf("%.4f\n",Search(y,0,100));
}
}

 

标签:HDU2199,No,double,equation,mid,solution,solve,100
From: https://blog.51cto.com/u_15998011/6108470

相关文章