设两人分别为甲乙,则最优方案市甲先乘车到达C后下车步行,小车回头接已经走了一段距离的乙,假设车与乙在D相遇,乙乘车到达B时甲正好步行到达,这样的花费时间最短。
此题具有二分性质,bot,top表示起点终点。建立mid,然后计算time甲和time乙,如果甲大于乙,bot=mid,否则top更新。
#include<bits/stdc++.h>
using namespace std;
int s;
int v_car;
int v_fot;
int main()
{
cin>>s;
cin>>v_fot>>v_car;
float t_jq,t_jh,t_yq,t_yh;//甲前半段,后半段,乙前半段,后半段
float tj;//甲的总时间
float ty;//乙的总时间
float bot=0;
float top=s;
do
{
float mid=(bot+top)/2.0;
t_jq=mid/v_car;
t_jh=(s-mid)/v_fot;
tj=t_jq+t_jh;
t_yq=(mid-t_jq*v_fot)/(v_fot+v_car);//乙与车相遇所需的时间
ty=t_jq+t_yq+(s-(t_jq+t_yq)*v_fot)/v_car;
if(tj<ty) top=mid;
else bot=mid;
}while(fabs(tj-ty)>1e-4);//这里得用dowhile,直接用while行不通
printf("%.2lf",tj);
return 0;
}