1. 程式人生 > >hdu 2298 二分+三分

hdu 2298 二分+三分

對於這種 先遞增後遞減的情況,採用三分找到最大值點,再二分求解

三分模板見程式碼

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define MS(x,y) memset(x,y,sizeof(x))
#define pi acos(-1.0)
using namespace std;
void fre(){freopen("t.txt","r",stdin);}
typedef long long LL;
typedef unsigned long long ULL;
const int maxn = 1000005;
const int inf = (1<<63)-1;
const double eps = 1e-8;
double x,y,v;
double calc(double n)
{
    return x*tan(n) - 0.5*9.8*x*x/v/v/cos(n)/cos(n);
}
double three_div(double l,double r)
{
    double m1,m2;
    while(r - l > eps)
    {
        m1 = l + (r-l)/3;
        m2 = r - (r-l)/3;
        if(calc(m1) < calc(m2)) l = m1;
        else r = m2;
    }
    return (l+r)/2;
}
double two_div(double x,double l,double r)
{
    double m;
    while(r - l > eps)
    {
        m = (l+r)/2;
        if(calc(m) < x) l = m;
        else r = m;
    }
    return (l+r)/2;
}
int main()
{
  //  fre();
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lf%lf%lf",&x,&y,&v);
        double maxx = three_div(0,pi/2);
        if(calc(maxx) < y) {printf("-1\n");continue;}
        else printf("%.6lf\n",two_div(y,0,maxx));
    }
    return 0;
}