二分搜索 HDOJ 2289 Cup
1 /*
2 二分搜索:枚举高度,计算体积与给出的比较。
3 */
4 #include <cstdio>
5 #include <algorithm>
6 #include <cstring>
7 #include <cmath>
8 using namespace std;
9
10 const int MAXN = 1e3 + 10;
11 const int INF = 0x3f3f3f3f;
12 const double EPS = 1e-8;
13 const double PI = acos (-1.0);
14 double r, R, H, V;
15 double x;
16
17 double cal(double h1) {
18 double u = r + (R - r) * h1 / H; //上底
19 double V1 = PI / 3.0 * h1 * (r * r + r * u + u * u); //圆台计算公式
20 return V1;
21 }
22
23 int main(void) { //HDOJ 2289 Cup
24 //freopen ("HDOJ_2289.in", "r", stdin);
25
26 int T; scanf ("%d", &T);
27 while (T--) {
28 scanf ("%lf%lf%lf%lf", &r, &R, &H, &V);
29 double mid;
30 double low = 0, upp = H;
31 while (upp - low > EPS) {
32 mid = (low + upp) / 2;
33 if (cal (mid) - V > EPS) upp = mid;
34 else low = mid;
35 }
36 printf ("%.6f\n", mid);
37 }
38
39 return 0;
40 }
编译人生,运行世界!