三分法入門題。
題目大意:給出圓錐的表面積,求最大體積的圓錐的高和底面半徑。附鏈接:http://poj.org/problem?id=3737
大體思路:這道題由圓錐體積可知,當高h不變時,體積和底面半徑 r 有二次關係,直接用三分法求出體積最大時的底面半徑。或者數學好的話可以直接求出表面積和圓錐高、體積、底面半徑的公式,在poj的 Disscus 看到的,見識了,還可以這樣求,厲害厲害。
以下是ac代碼:
#include<iostream>
#include<cmath>
#include<cstring>
#include<stdio.h>
using namespace std;
const double error=1e-4;
const double pi=acos(-1.0);
int main(){
double s;
while(~scanf("%lf",&s)){
double r1,r2,h1,h2;
double left=0;
double right=sqrt(s/pi);
double v1,v2;
while(right-left>error){
r1=left+(right-left)/3.0;
h1=sqrt((s/pi/r1-r1)*(s/pi/r1-r1)-r1*r1);
r2=right-(right-left)/3.0;
h2=sqrt((s/pi/r2-r2)*(s/pi/r2-r2)-r2*r2);
v1=pi*r1*r1*h1/3.0;
v2=pi*r2*r2*h2/3.0;
if(v1<v2)
left=r1;
else
right=r2;
}
printf("%.2lf\n%.2lf\n%.2lf\n",v1,h1,r1);
}
return 0;
}
這代碼在 oj 上用C++提交,如果用G++會wa,原因是編譯器自身的問題,這裏就不解釋了,自行百度吧(我也是踩坑過來的)。