hdu 2199:Can you solve this equation?(二分搜索)
Can you solve this equation?
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 7493 Accepted Submission(s): 3484
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.
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!
Author
Redow
Recommend
二分搜索。
先要判断方程的单调性。可用 cal(0)<=y && y<=cal(100) 判断。
二分法不断提高精度,最后到某个精度位置输出就是正确答案。
注意题目给出的第一组测试数据是错的,AC代码出来的结果是1.6151,而不是1.6152。
代码:
1 #include <iostream>
2 #include <cmath>
3 #include <iomanip>
4 using namespace std;
5
6 double cal(double x)
7 {
8 return 8*pow(x,4) + 7*pow(x,3) + 2*pow(x,2) + 3*x + 6;
9 }
10 double GetAns(double y)
11 {
12 double a=0,b=100;
13 while(b-a>1e-6){
14 double mid=(a+b)/2;
15 cal(mid)<y?a=mid:b=mid;
16 }
17 return (a+b)/2;
18 }
19 int main()
20 {
21 int T;
22 cin>>T;
23 while(T--){
24 double y;
25 cin>>y;
26 if(cal(0)<=y && y<=cal(100)){
27 cout<<setiosflags(ios::fixed)<<setprecision(4);
28 cout<<GetAns(y)<<endl;
29 }
30 else
31 cout<<"No solution!"<<endl;
32 }
33 return 0;
34 }
Freecode : www.cnblogs.com/yym2013