You have n devices that you want to use simultaneously.
The i-th device uses ai units of power per second. This usage is continuous. That is, in λ seconds, the device will use λ·ai units of power. The i-th device currently has bi units of power stored. All devices can store an arbitrary amount of power.
You have a single charger that can plug to any single device. The charger will add p units of power per second to a device. This charging is continuous. That is, if you plug in a device for λ seconds, it will gain λ·p units of power. You can switch which device is charging at any arbitrary unit of time (including real numbers), and the time it takes to switch is negligible.
You are wondering, what is the maximum amount of time you can use the devices until one of them hits 0 units of power.
If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
The first line contains two integers, n and p (1 ≤ n ≤ 100 000, 1 ≤ p ≤ 109) — the number of devices and the power of the charger.
This is followed by n lines which contain two integers each. Line i contains the integers ai and bi (1 ≤ ai, bi ≤ 100 000) — the power of the device and the amount of power stored in the device in the beginning.
If you can use the devices indefinitely, print -1. Otherwise, print the maximum amount of time before any one device hits 0 power.
Your answer will be considered correct if its absolute or relative error does not exceed 10 - 4.
Namely, let's assume that your answer is a and the answer of the jury is b. The checker program will consider your answer correct if .
2 1 2 2 2 1000
2.0000000000
1 100 1 1
-1
3 5 4 3 5 2 6 1
0.5000000000
In sample test 1, you can charge the first device for the entire time until it hits zero power. The second device has enough power to last this time without being charged.
In sample test 2, you can use the device indefinitely.
In sample test 3, we can charge the third device for 2 / 5 of a second, then switch to charge the second device for a 1 / 10 of a second
二分答案,注意double类型足够大,二分的边界与精度是需要注意的.
#include<iostream>
#include <stdio.h>
#include <string.h>
#include <map>
#include <set>
#include <vector>
#include <algorithm>
#include <math.h>
using namespace std;
const int INF=1e9+7;
struct ttt{
double a,b;
};
ttt qq[105000];
int main(){
//freopen("in.txt","r",stdin);
int i,j,k,f1,f2,f3,t1,t2,t3,t4,f4;
long long n,m;
int r,c;
cin >> n >> m;
long long sum1=0;
for(i=1;i<=n;i++){
cin >> qq[i].a >> qq[i].b;
sum1+=qq[i].a;
}
if(m>=sum1){
cout << "-1" << endl;return 0;
}
double left1,right1,mid1;
left1=0;right1=1e14+7; //二分的前后边界一定要囊括全部,double类型是64位,足够大
double max1=0;
while(right1-left1>=0.000000001){
mid1=(right1+left1)/2;
double sum2=0;
for(i=1;i<=n;i++){
if(qq[i].a*mid1>qq[i].b){ //???????
sum2+=qq[i].a*mid1-qq[i].b;
}
}
double ff1=m*mid1-sum2;
if(ff1>=0){//???sum2,??????????
left1=mid1;
max1=max(max1,mid1);
}else{
right1=mid1;
}
}
printf("%.10llf\n",max1);
return 0;
}