zoj 3366 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=3366
第一次接触三分,
二分法作为分治中最常见的方法,适用于单调函数,逼近求解某点的值。但当函数是凸性函数时,二分法就无法适用,这时三分法就可以“大显身手”~~
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> using namespace std; const double eps = 1e-10; double H,h,D,mk; int dbcmp(double x) { if (x > eps) return 1; else if (x < -eps) return -1; else return 0; } double getR(double x) { return (h*D - H*x)/(D - x) + x; } void solve() { double l = 0; double r = h*D/H; while (dbcmp(r - l) > 0) { double mid = (l + r)/2.0; double midmid = (mid + r)/2.0; if (getR(mid) >= getR(midmid)) r = midmid; else l = mid; } printf("%.3lf\n",getR(l)); } int main() { //freopen("d.txt","r",stdin); int t; scanf("%d",&t); while (t--) { scanf("%lf%lf%lf",&H,&h,&D); solve(); } return 0; }