UVA - 10341 Solve It (二分)

Solve the equation:
p ∗ e
−x + q ∗ sin(x) + r ∗ cos(x) + s ∗ tan(x) + t ∗ x
2 + u = 0
where 0 ≤ x ≤ 1.
Input
Input consists of multiple test cases and terminated by an EOF. Each test case consists of 6 integers in
a single line: p, q, r, s, t and u (where 0 ≤ p, r ≤ 20 and −20 ≤ q, s, t ≤ 0). There will be maximum
2100 lines in the input file.
Output
For each set of input, there should be a line containing the value of x, correct up to 4 decimal places,
or the string ‘No solution’, whichever is applicable.
Sample Input
0 0 0 0 -2 1
1 0 0 0 -1 2
1 -1 1 -1 -1 1
Sample Output
0.7071
No solution
0.7554

题意很简单,就是求出这个公司的x的解,x的范围在0-1之间,找不到输出No solution.
最开始没有看出这个方程是单调的,而且只要保证精度在0.0001即可,所以最开始想着采用枚举,每次加0.0001算了一下时间复杂度。刚好可以。比赛时没有处理好精度,刚才试了一下枚举发现可以过。当然最正确的解法依然时二分,因为只有左端点结果大于0,右端点结果小于0才会有解,所以我们可以用这个条件把No solution的情况判断出来,然后再二分。代码如下:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
double p,q,r,s,t,u;
const double eps = 1e-7;
double E = exp(1);
double Get(double x){
    double res = p*pow(E,-x)+q*sin(x)+r*cos(x)+s*tan(x)+t*x*x + u;
    return res;
}
int main(void){
    while(scanf("%lf%lf%lf%lf%lf%lf",&p,&q,&r,&s,&t,&u) != EOF){
        double ans;
        double l = 0,r = 1;
        if(Get(0) < 0 || Get(1) > 0){
            printf("No solution\n");
            continue;
        }
        while(r - l - eps >  0){
            double mid = (l+r)/2;
            double res = Get(mid);
            if(res > eps){
                l = mid;
            }
            else{
                r = mid;
            }
        }
        printf("%.4lf\n",l);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhao5502169/article/details/79829997