poj3737

三分法求单峰函数极值

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<cmath>
using namespace std;

#define pi acos(double(-1))
#define eps 10E-11

double s;

int dblcmp(double &a, double &b)
{
if (a - eps > b)
return 1;
if (a + eps < b)
return -1;
return 0;
}

double cal(double &r)
{
double R = s / pi / r - r;
double h = sqrt(R * R - r * r);
return r * r * pi * h / 3;
}

int main()
{
//freopen("t.txt", "r", stdin);
while (scanf("%lf", &s) != EOF)
{
double l = 0;
double r = sqrt(s / pi);
while (dblcmp(l, r) < 0)
{
double r1 = l + (r - l) / 3;
double r2 = r - (r - l) / 3;
double vol1 = cal(r1);
double vol2 = cal(r2);
if (dblcmp(vol1, vol2) < 0)
l
= r1;
else
r
= r2;
}
double R = s / pi / r - r;
double h = sqrt(R * R - r * r);
double vol = r * r * pi * h / 3;
printf(
"%.2f\n%.2f\n%.2f\n", vol, h, r);
}
return 0;
}

你可能感兴趣的:(poj)