Need for Speed(二分)

题目链接:Need for Speed

Sheila is a student and she drives a typical student car: it is old, slow, rusty, and falling apart. Recently, the needle on the speedometer fell off. She glued it back on, but she might have placed it at the wrong angle. Thus, when the speedometer reads s, her true speed is s+c, where c is an unknown constant (possibly negative).
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.

Sample Input 1
3 5
4 -1
4 0
10 3
Sample Output 1
3.000000000
Sample Input 2
4 10
5 3
2 2
3 6
3 1
Sample Output 2
-0.508653377

思路:二分,只不过要在分母是负数的时候,让左端点=mid(这一点直接就崩了,没想到)。
这一题的差值要小于1e-9,虽然误差是1e-6。

代码:

#include<stdio.h>
#include<string.h>
#include<queue>
#include<math.h>
#include<string>
#include<algorithm>
using namespace std;
#define PI acos(-1.0)
#define inf 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;

const double ans=1e-9;
const int maxn=1009;

struct node
{
    int di,si;
}edge[maxn];
int n;
double doo(double f)
{
    double sum=0.0;
    for(int i=0;i<n;i++)
    {
        if((f+edge[i].si*1.0)<=0)
            return inf*1.0;
        else sum+=edge[i].di*1.0/(f+edge[i].si*1.0);
    }
    return sum;
}
int main()
{
    int t;
    while(~scanf("%d%d",&n,&t))
    {
        for(int i=0;i<n;i++)
            scanf("%d%d",&edge[i].di,&edge[i].si);
        double tt=inf;
        double s=-tt;
        while(tt-s>ans)
        {
            double mid=(s+tt)/2.0;
            if(doo(mid)>t*1.0)
                s=mid;
            else tt=mid;
        }
        printf("%.9lf\n",s);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值