CF24E 二分(應注意二分什麼和二分時的處理細節)

life4711發表於2015-01-11

http://codeforces.com/problemset/problem/24/E

E. Berland collider
time limit per test
1.5 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Recently the construction of Berland collider has been completed. Collider can be represented as a long narrow tunnel that contains nparticles. We associate with collider 1-dimensional coordinate system, going from left to right. For each particle we know its coordinate and velocity at the moment of start of the collider. The velocities of the particles don't change after the launch of the collider. Berland scientists think that the big bang will happen at the first collision of particles, whose velocities differs in directions. Help them to determine how much time elapses after the launch of the collider before the big bang happens.

Input

The first line contains single integer n (1 ≤ n ≤ 5·105) — amount of particles in the collider. Next n lines contain description of particles. Each particle is described by two integers xivi ( - 109 ≤ xi, vi ≤ 109, vi ≠ 0) — coordinate and velocity respectively. All the coordinates are distinct. The particles are listed in order of increasing of coordinates. All the coordinates are in meters, and all the velocities — in meters per second. The negative velocity means that after the start of collider the particle will move to the left, and the positive — that the particle will move to the right.

Output

If there will be no big bang, output -1. Otherwise output one number — how much time in seconds elapses after the launch of the collider before the big bang happens. Your answer must have a relative or absolute error less than 10 - 9.

Sample test(s)
input
3
-5 9
0 1
5 -1
output
1.00000000000000000000
input
6
1 3
2 3
3 3
4 -3
5 -1
6 -100
output
0.02912621359223301065
/**
CF24E 二分
題目大意:在x軸上有n個點每個點向左或向右發射子彈,知道每個點的座標和所發射子彈的飛行速度,問所有相向而行的的子彈中最短的相遇時間
解題思路:不能列舉兩方向的點,我們要採取二分時間的方式,由於精度太小可能陷入無限迴圈,我們限制一下二分的次數
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=500005;
int n,a[maxn][2];

bool judge(double t)
{
    double d=-1e20;
    for(int i=0;i<n;i++)
    {
         if(a[i][1]>0)
            d=max(d,a[i][0]+t*a[i][1]);
         else if(a[i][0]+t*a[i][1]<=d)return true;
    }
    return false;
}
int main()
{
    while(~scanf("%d",&n))
    {
        for(int i=0;i<n;i++)
            scanf("%d%d",&a[i][0],&a[i][1]);
        double l=0.0,r=1e10;
        int t=0;
        while(t<100)
        {
            t++;
            double mid=(l+r)/2;
            printf("%.20lf\n",mid);
            if(judge(mid))
                r=mid;
            else
                l=mid;
        }
        if(r==1e10)
            puts("-1");
        else
            printf("%.20lf\n",l);
    }
    return 0;
}