Sheila made a careful record of a recent journey and wants to use this to compute c . The journey consisted of n segments. In the ith segment she traveled a distance of di and the speedometer read si for the entire segment. This whole journey took time t . Help Sheila by computing c .
Note that while Sheila’s speedometer might have negative readings, her true speed was greater than zero for each segment of the journey.
Input
The first line of input contains two integers n ( 1≤n≤1000 ), the number of sections in Sheila’s journey, and t ( 1≤t≤106 ), the total time. This is followed by n lines, each describing one segment of Sheila’s journey. The ith of these lines contains two integers di ( 1≤di≤1000 ) and si ( |si|≤1000 ), the distance and speedometer reading for the ith segment of the journey. Time is specified in hours, distance in miles, and speed in miles per hour.
Output
Display the constant c in miles per hour. Your answer should have an absolute or relative error of less than 10−6 .
直接二分就好了,注意每一组加完之后的速度都不能是负数,如果是出现负数就可以直接往右找了
ac代
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
double a[1003][2];
int main()
{
int n,m;
while(cin>>n>>m)
{
for(int i=0;i<n;i++)
{
scanf("%lf%lf",&a[i][0],&a[i][1]);
}
double l=-10000000,r=10000000;
double mid;
while(r-l>0.0000001)
{
mid=(l+r)/2;
double sum=0;
for(int i=0;i<n;i++)
{
if(a[i][1]+mid<0)
{
sum=100000000;
break;
}
sum+=(a[i][0]/(a[i][1]+mid));
}
if(sum<m)
r=mid;
else
l=mid;
}
printf("%.7lf\n",l);
}
return 0;
}