2013湘潭赛 Hurry Up 三分算法

三分算法讲解

hurry up题目链接

用min函数和max函数写不过,自己手写比较函数通过了,貌似比赛也是这样的~~囧

最后就是 比较两条路线的路径最短,第二条路线是一条满足


#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<stdlib.h>
using namespace std;
const double eps=1e-8;
struct node{
    double x,y;
} ori,des,center;
double car,peo;
double dis(node a,node b){
    return sqrt( (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

double  three_divide(){
    node mid,midmid;
    mid.y=0;
    midmid.y=0;
    double ans_mid,ans_midmid;
    double left,right;
    if(ori.x<des.x){
        left=ori.x;
        right=des.x;
    }
    else {
        left=des.x;
        right=ori.x;
    }
    while(right-left>eps){
         mid.x=(left+right)/2;      //三分算法的关键步骤
         midmid.x=(mid.x+right)/2;
         ans_mid=dis(ori,mid)/peo+dis(des,mid)/car;
         ans_midmid=dis(ori,midmid)/peo+dis(des,midmid)/car;
         if(ans_mid<ans_midmid) right=midmid.x;
         else left=mid.x;
    }
    mid.x=left;
    return dis(ori,mid)/peo+dis(des,mid)/car;
}



int main()
{
    int n;
    scanf("%d",&n);
    while(n--){
        scanf("%lf%lf%lf%lf%lf%lf",&ori.x,&ori.y,&des.x,&des.y,&peo,&car);
        double ans1=dis(ori,des)/peo,ans2;
        ans2=three_divide();
        printf("%.2lf\n",ans1>ans2?ans2:ans1);
    }

    return 0;
}




你可能感兴趣的:(算法)