A.Voltage Keepsake 二分/贪心
题目
已知有n个设备,还有一个每秒钟能充p电量的电池;
现在给出n个设备每秒需要的电量a和初始电量b;
现在要求出一个时间x,使得第一个灭掉的设备时间尽可能的晚。
注意:电池一次只能给一个设备充电。
方法一 二分
每次二分能撑到的时间x,然后去检验所有的设备是否能苟到那个时间。
注意:能活无限长时间的条件是p≥sum(a[i]),因为b最小值是1不是0,所以此时无限换充电器。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <iomanip>
using namespace std;
#define INIT(x) memset(x,0,sizeof(x))
#define eps 1e-5
#define next next_
typedef long long ll;
typedef unsigned long long ull;
const int INF = 0x7fffffff;
const int inf = 0x3f3f3f3f;
const int maxn = 200005;
const int N = 105;
inline void read(ll &x) {
ll f=1;
x=0;
char s=getchar();
while(s<'0'||s>'9') {
if(s=='-')f=-1;
s=getchar();
}
while(s>='0'&&s<='9') {
x=x*10+s-'0';
s=getchar();
}
x*=f;
}
ll n;
double p,sum;
struct node {
double a,b,c;
bool operator<(const node &f)const {
return c<f.c;
}
} e[maxn];
bool check(double x) {
double res=0;
for(int i = 0; i < n; i++)
if (e[i].a * x > e[i].b)
res += (e[i].a * x - e[i].b) / p;
if(x-res《eps) return false;
return true;
}
int main() {
read(n);
cin>>p;
for(int i=0; i<n; i++) {
scanf("%lf%lf",&e[i].a,&e[i].b);
e[i].c = e[i].b / e[i].a;
sum += e[i].a;
}
if(p>=sum) {
cout<<-1<<endl;
return 0;
}
double l = 0, r = 1e15;
while(r-l>eps) {
double mid = (l+r) / 2;
if(check(mid)) r = mid;
else l = mid;
}
if(abs(r-(1e15))<eps) {
cout<<"-1"<<endl;
return 0;
} else {
cout<<fixed<<setprecision(8)<<r<<endl;
}
return 0;
}