Question
The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.
At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.
You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn’t need to have integer coordinate.
Input
The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends.
The second line contains n integers x1, x2, …, xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters.
The third line contains n integers v1, v2, …, vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second
Output
Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road.
Your answer will be considered correct, if its absolute or relative error isn’t greater than 10 - 6. Formally, let your answer be a, while jury’s answer be b. Your answer will be considered correct if holds.
Example
Input
3
7 1 3
1 2 1
Output
2.00000000000
Input
4
5 10 3 2
2 3 2 4
Output
1.400000000000
Code 1
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
double a[60005],b[60005];
int main()
{
int n;
int i,j,k;
double l,r,mid1,mid2,t1,t2;
cin>>n;
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
cin>>b[i];
l=0;r=1e9+5;
while(l+0.000001<r)
{
t1=t2=0;
mid1=l+(r-l)/2;
mid2=mid1+(r-mid1)/2;
for(i=0;i<n;i++)
{
t1=max(t1,fabs(mid1-a[i])/b[i]);
t2=max(t2,fabs(mid2-a[i])/b[i]);
}
if(t1<t2)
r=mid2;
else
l=mid1;
}
printf("%.12lf\n",min(t1,t2));
return 0;
Code 2
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#include <cstdio>
using namespace std;
struct ss
{
double a,b;
};
bool comp(const ss &a,const ss &b)
{
return a.a<b.a;
}
int main()
{
vector<ss>v;
ss ab[60005];
int i,j,k,n;
double l,r,mid1,mid2;
double t1,t2;
cin>>n;
for(i=0;i<n;i++)
cin>>ab[i].a;
for(i=0;i<n;i++)
cin>>ab[i].b;
v.clear();
for(i=0;i<n;i++)
v.push_back(ab[i]);
sort(v.begin(),v.end(),comp);
l=v[0].a;r=1e9+5;
while(l+0.000001<r)
{
t1=t2=0;
mid1=l+(r-l)/2;
mid2=mid1+(r-mid1)/2;
for(i=0;i<n;i++)
{
t1=max(t1,fabs(mid1-v[i].a)/v[i].b);
t2=max(t2,fabs(mid2-v[i].a)/v[i].b);
}
if(t1<t2)
r=mid2;
else
l=mid1;
}
printf("%.12lf\n",min(t1,t2));
return 0;
}
这两个代码都是对集合点进行二分,着最小时间。
实际上这题并不用排序,所以第二题的方法麻烦了一些,但其中对结构体排序的方法还是不错的。
ps:这题我只想强调一点,最后输出的时候 用cout<<r<<endl;
或printf("%lf\n",r);
会WA。
因为这样输出是默认输出保留小数点6位后输出,即四舍五入到小数点后6位再输出。(这一点,价值三个小时!!!)