b_tx_手机有电的最长时间(二分)

有n个快没电的手机,当前剩余电量分别为a[i],每秒耗电量为b[i]。现仅有一个充电器为这些手机提供充电服务,每i秒可以充i*w的电量。现在想知道,所有手机共享这一个充电器的情况下,所有手机都有电的时间最长可以维持多久?

第一行正整数T,每组的第一行两个正整数,手机数量n ,每秒充电量w;
T组的n行,每行两个正整数,初始电量a[i],每秒耗电量b[i]

输入
1
3 5
3 4
2 5
1 6
输出:0.5
手机3冲0.4s,手机2冲0.1s,所有手机都有电最长可维持0.5秒
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+5;
int n, w, a[N], b[N];
bool chk(double t) {
    double need = 0;
    for (int i=0; i<n; i++) {
        double x = a[i] / b[i]; //手机i原有电量可维持的开机时间
        if (x < t) { 
            if (x < need) return false; //如果第i台手机在前面i-1台手机没有冲完的情况下就没电了,false
            double y = ((t * b[i]) - a[i]) / w; //额外充电量需要的时间
            need += y;
        }
    }
    return true;
}
int main() {
    std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
    int t; cin>>t;
    while (t--) {
        cin>>n>>w;
        for (int i=0; i<n; i++) cin>>a[i]>>b[i];
        double l = 0, r = 1e6;
        while (l < r) {
            double m = (l + r) / 2.0;
            if (chk(m)) {
                l = m;
            } else {
                r = m - 1e-5;
            }
        }
        string s = to_string(l);
        if (l < 1) {
            s = s.substr(0,3);
        } else {
            s = s.substr(0,2);
        }
        cout << s << '
';
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wdt1/p/14617634.html