We need to interpret the problem: We have n devices, each device i uses a_i power per second continuously (discharge rate). Initially it has b_i stored energy. We can charge any device at rate p (units per second) by plugging the charger into it. We can switch arbitrarily, with no downtime. All devices can store arbitrary amount of energy, so no upper limit.
We want to maximize the time T such that we can schedule charging over [0, T] (maybe switching) so that for all devices i, the energy never drops to 0. Actually we want the maximum possible time before any device hits 0. Starting at t=0, all devices have initial energy b_i. As time passes, each device continuously drains at rate a_i unless it is being charged (in which case net change is a_i - p if charging, else net -a_i). Actually when charging, the device gains p units per second, but still uses a_i per second, so net rate of change is -a_i + p = p - a_i. If p > a_i, net gain. If p == a_i, net zero. If p < a_i, net loss even while charging.
We can switch charging among devices arbitrarily. We need to ensure that the energy of each device remains >= 0 for all t < T, and at T perhaps some device hits exactly 0? The problem: "maximum amount of time you can use the devices until one of them hits 0 units of power." Means we want the supremum of times T such that there exists a charging strategy that keeps all devices alive (energy > 0) for all t < T, and at time T at least one hits 0? Actually "maximum amount of time before any one device hits 0 power." If we can achieve arbitrarily large T (i.e., indefinite), output -1. So we are to compute the maximum possible time T we can guarantee that no device runs out, under optimal charging strategy. The devices are continuously draining, we can allocate charging. This is reminiscent of resource allocation: we have total "required power" sum a_i, and we have a charger that can supply p. If p >= sum a_i, we can keep all devices alive forever because total energy never depletes? Actually initial stored energy matters. Even if p >= sum a_i, we could potentially charge enough to keep all devices alive indefinitely by distributing charging appropriately. But initial stored energy might be insufficient to bridge the time until the charger can build up enough? Wait, consider total energy in system: sum of energies of all devices. Without charger, total energy decreases at rate sum a_i. With charger, when charger is plugged into device i, total energy increases at rate p (since charger adds energy to the system) and decreases at rate sum a_i (all devices consume). But energy is not transferred between devices; the charger adds new energy. So total energy derivative: dE_total/dt = p - sum a_i when charger is active? Actually careful: Charger adds p to a specific device, so total energy of all devices increases by p per second from charger. Simultaneously each device consumes a_i per second, so total consumption is sum a_i always, regardless of which device is being charged. So net change in total energy = p - sum a_i. If p >= sum a_i, total energy never decreases; it may increase or stay constant. However initial total energy sum b_i is finite. If p >= sum a_i, net rate >= 0, so total energy is non-decreasing. That means total energy never goes to zero; but could an individual device run out? Possibly, if we don't charge it enough, its own energy could drop to zero even though total energy is high. But we can control charging. With p >= sum a_i, we can keep all devices alive indefinitely? Let's think: We need to keep each device's energy nonnegative. Since total energy is non-decreasing and always >= sum b_i, but individual devices could deplete if we don't allocate charging. But can we schedule charging such that each device never runs out? This is like we have a single server (charger) that can allocate time fractions to devices. The consumption rates are a_i. The charger provides p to the device it's on. The net effect over time: For each device i, the average rate of change of its energy is (charging fraction) * p - a_i. If we allocate fraction f_i of the charger time to device i (sum f_i = 1), then long-term average net rate = f_i p - a_i. For indefinite operation, we need for each device i, the energy not to go to negative; we need that over time, the average net rate is at least 0? Actually to keep energy bounded away from -infinity, we need that for each device, the long-term average net intake >= 0, i.e., f_i p >= a_i. But sum over i of f_i p = p. So we require p >= sum a_i for such fractions to exist. That's necessary. Is it sufficient? If p >= sum a_i, we can choose f_i = a_i / p (if p>0) so that f_i p = a_i exactly, making net zero on average. But we also need to handle initial energies and ensure that no device hits zero before the average works out. With infinite time horizon, if we can set fractions exactly and switch appropriately, we might need to prevent transient shortages. Since we can start charging devices with low initial energy first, we can probably manage to keep all positive if p >= sum a_i. However, consider the case n=1, a1=1, b1=1, p=100. p >= a1, indeed 100 >=1. We can keep it alive indefinitely because we can charge it enough from the start? Actually the device consumes at rate 1, charger adds at 100, net gain 99. So its energy will increase over time, never run out. So it's indefinite. In the sample, n=1, a=1, b=1, p=100 gives -1. So that matches.
What if p >= sum a_i but some devices have very small initial energy? Could they run out before we start charging them? Since we can switch arbitrarily fast, we can give them some charge immediately. But the charger can only be on one device at a time. So if a device has extremely low initial energy, we need to allocate some charging to it before it depletes. Since we can start charging it from time 0, we can keep it from depleting if its net rate when charging is positive (p > a_i). But if p < a_i, then even while charging it still loses energy, just slower. So if p < a_i, we cannot prevent its energy from decreasing; but if p >= sum a_i, some a_i might be larger than p? Wait sum a_i >= a_i, so if p >= sum a_i then p >= a_i for each i individually because sum a_i >= a_i. So indeed if p >= sum a_i, then p >= a_i for all i. So each device, when charging, net rate = p - a_i >= 0. So it's non-decreasing while charging. So we could simply charge each device in turn to boost them. But still, if a device initially has zero energy? Actually b_i >=1. So initially all positive. We could start by charging the device with smallest ratio b_i / a_i? Actually we want to ensure none hits zero. Since each device while not being charged is losing energy at rate a_i. So we need to give it enough charge before its energy would hit zero. Since we can charge them sequentially, we can keep all alive as long as we can eventually keep them above zero. This is reminiscent of the "feasibility" of scheduling tasks with deadlines.
Let's think: The problem is to find the maximum T such that there exists a charging schedule over [0,T] that keeps all energies >= 0. The charger can be switched arbitrarily; we can model it as for each device i, we need to allocate a total charging time t_i (how long the charger is connected to device i) over [0,T]. The energy of device i at time t is: b_i + (p * amount of time spent charging i up to t) - a_i * t. Because it consumes a_i continuously, and gains p only during its charging intervals.
Let u_i(t) = total time charger is on device i up to time t (non-decreasing, 0 <= u_i(t) <= t). Since charger can only be on one device at a time, we have sum_i u_i'(t) <= 1 for almost all t (since at any moment, charger is either idle or on one device; but we can assume we always charge something when possible? Actually we may idle, but idling doesn't help, so optimal schedule will always charge some device if needed. So we can assume sum_i u_i'(t) = 1 for all t except maybe at switching points). However, we can also consider aggregate: Over the whole interval [0,T], let x_i = total time charger spends on device i. Then sum_i x_i = T (assuming we use charger all the time; if we idle, sum x_i < T, but that would be suboptimal because we can always charge some device to increase energies, so for maximizing T, we will use charger continuously). So we assume charger always on exactly one device: sum_i x_i = T.
Now the energy of device i at time T is: E_i(T) = b_i + p x_i - a_i T. We require E_i(T) >= 0? Actually we need that for all t in [0,T], the energy never hits 0. But if we can guarantee that the final energies are non-negative and the process didn't dip below, maybe we can always adjust schedule to avoid dips? The maximum T achievable might be limited by the condition that there exists a schedule of charging times (x_i) and a dynamic assignment such that for all t, E_i(t) >= 0. However, often the worst constraint comes from the requirement that at each time, the energy must be non-negative. This is similar to "feasible schedule with deadlines" where each device has initial energy b_i and consumes at rate a_i; we can supply charge at rate p but only to one at a time. This is like a single server with tasks that have "minimum processing requirement" to keep them alive. The known approach for these problems (like "how long can you keep all devices alive?") is to consider that the total energy in the system (sum b_i) plus total charge added (p T) must be at least total consumption (sum a_i T) to not run out of total energy? Actually that's necessary: sum_i b_i + p T >= sum_i a_i T => sum b_i >= (sum a_i - p) T. But that's not sufficient individually.
We need to find maximum T such that there exists a schedule. This is reminiscent of a classic problem: given devices with power consumption a_i and initial battery b_i, charger rate p, what's the maximum time to keep all alive? It's often solved by binary search on T and checking feasibility. Feasibility can be checked by computing for each device the required charging time to last T: because to last T, the device i must have at the start b_i, and over time T it consumes a_i T, but can be charged for some total time x_i, gaining p x_i. So we need b_i + p x_i >= a_i T => x_i >= max(0, (a_i T - b_i) / p). And we have sum_i x_i <= T (since we can only charge one at a time). Additionally, there are temporal constraints: we cannot charge a device before its energy would hit zero, but perhaps we can schedule charging in a way that respects the ordering. However, it's known that for such problems with linear consumption and charging, if we can satisfy the total time constraint (sum needed charging time <= T) and also each needed x_i <= T (obviously), then a schedule exists? Not always. Consider two devices: a1=100, b1=1; a2=1, b2=100; p=10. Want to survive T. The required x1 = max(0, (100T - 1)/10); for T just above 0.01, x1 becomes positive. Sum x_i might be <= T? But we also need to consider that device 1 has very low initial energy and high consumption; even if we allocate total charging time to it, it might run out before we can charge it enough because it consumes quickly. This is a timing constraint: we need to provide the charging to device 1 early enough so that its energy never goes negative. So the feasibility is not just about totals; the schedule must respect that for each device, the amount of charging it receives by any time t must be sufficient to cover its consumption up to that time, given its initial energy.
Thus, the problem becomes: find the maximum T such that there exists a function of time allocating charger, so that for all i and for all t in [0,T], b_i + p * (charging time for i up to t) - a_i t >= 0.
This is a classic "fluid model" / "real-time scheduling" problem. It's similar to "uniprocessor scheduling with deadlines" where each task has a "deadline" equal to its zero-energy time if not charged, and we have a "processor" (charger) that can serve tasks (charge) to extend their lifetime. Alternatively, we can think of each device as having an initial "battery" and we can supply energy. Equivalent to we have a server that can process jobs; each job has a processing requirement (the amount of charge needed) and a deadline (the time when its battery would run out if not processed). But here the job (charging) can be preempted arbitrarily.
Let's define for device i, its energy at time t: b_i - a_i t + p * C_i(t) where C_i(t) is cumulative charging time for i up to t. We need >= 0. The condition can be rearranged: p C_i(t) >= a_i t - b_i. So the required cumulative charging time for i by time t is at least max(0, (a_i t - b_i) / p). This function is piecewise: zero until t <= b_i / a_i (the time it would run out without any charge), then linear increasing with slope a_i/p.
Thus, we need to schedule the charger (which can serve at most 1 unit of processing at any moment) such that for each i, C_i(t) >= required(t). C_i(t) are cumulative, non-decreasing, with sum_i C_i(t) <= t (since at most one device charged at a time; and if we always charge, sum_i C_i(t) = t, because charger is always on exactly one device? Actually C_i'(t) are fractions that sum to <=1; if we never idle, sum = 1. For maximizing T, we will likely keep charger busy all the time. But we could idle if we have extra energy? Idling would be suboptimal because we could charge some device to increase its buffer. So we can assume sum_i C_i(t) = t for all t (if possible; but maybe at some times we cannot charge because all devices are above their required? Actually we can always charge any device, even if it's already high; that would increase its energy, giving more leeway. So it's never harmful to charge (except maybe if we want to minimize something? But we want to maximize time, so charging more is beneficial. So we can assume charger always active, so sum_i C_i'(t) = 1, thus sum_i C_i(t) = t (if we start from zero). More precisely, C_i(0)=0, and for all t, sum_i C_i(t) = t (if charger always on). However, is it always optimal to keep charger busy? Possibly not if some devices have p < a_i, charging them still leads to net loss but slower; still, charging them yields more energy relative to not charging, so it's beneficial. So yes, always charging something is beneficial. So we can assume sum_i C_i(t) = t.
Thus, the feasibility problem is: given n "demand" functions D_i(t) = max(0, (a_i t - b_i) / p), we need to find if there exist non-decreasing functions C_i(t) with C_i(0)=0, C_i(t) non-decreasing, sum_i C_i(t)=t, and C_i(t) >= D_i(t) for all t in [0,T]. This is like we have a cumulative "service" that must meet cumulative demand curves.
In scheduling theory, this is analogous to the problem of "feasibility of preemptive schedule on a single machine with release times and deadlines", but here demands start at time r_i = b_i/a_i? Actually D_i(t) becomes positive after t > b_i/a_i. So we can think of device i requiring processing (charging) at rate at least a_i/p after its "deadline"? Hmm.
We can consider each device i requires that the total amount of charger time allocated to it by time t must be at least (a_i t - b_i)/p for t >= b_i/a_i. Equivalently, the "lag" or "laxity".
A known necessary and sufficient condition for such a fluid schedule to exist is that for all subsets of devices, the total demand by time t does not exceed t, i.e., sum_i D_i(t) <= t for all t in [0,T]. Also, sum_i D_i(T) <= T (which is the same at t=T). But also we need that D_i(t) are non-decreasing convex? Actually it's a classic result: For a single machine, if we have tasks with "minimum cumulative service" constraints (i.e., they require at least a certain amount of processing by each time, and we can allocate service arbitrarily), the condition that the sum of demands never exceeds total available processing time (i.e., t) is sufficient to construct a schedule (by the "Earliest Deadline First" or "processor sharing" concept). More precisely, if we define the required service curves, the necessary and sufficient condition for feasibility is that for all t, sum_i D_i(t) <= t. Because we can always serve the "most urgent" demand first, akin to the "Max pressure" or "fluid model" scheduling. Indeed, consider the function F(t) = t - sum_i D_i(t). This must be non-negative for all t. Then we can set C_i(t) = D_i(t) + some allocation of the surplus F(t) (which can be distributed arbitrarily, e.g., to devices that have not yet reached their demand). There is known concept of "feasibility of cumulative real-time constraints" in real-time calculus. Provided that the demand functions are absolutely continuous and non-decreasing, and the total capacity is 1, the condition sum_i D_i(t) <= t for all t is sufficient to construct a feasible schedule (e.g., by using the "Earliest Deadline First" or "Least Laxity First" dynamic policy). Actually, we need to check that if we serve according to the "minimum remaining time to deadline" (or similar), we can meet the constraints. But it's plausible.
Let's test with counterexample: two devices: a1=100, b1=1; a2=1, b2=100; p=10. Compute D_i(t). For device1: D1(t) = max(0, (100t -1)/10) = max(0, 10t - 0.1). So after t=0.01, it requires charging. For device2: D2(t) = max(0, (1*t -100)/10) = max(0, 0.1t -10). This becomes positive after t=100. So for t up to 100, D2(t)=0. So sum D_i(t) = D1(t) for t <= 100. Need D1(t) <= t -> 10t - 0.1 <= t -> 9t <= 0.1 -> t <= 0.0111... Actually for t>0.01, condition becomes 10t-0.1 <= t => 9t <= 0.1 => t <= 0.011111... So for t > ~0.0111, the condition fails. So T cannot exceed about 0.0111. But is it actually possible to survive that long? Let's simulate. Device1 starts with 1 unit, consumes at 100 units/sec, so it would run out in 0.01 sec without charging. With charger at rate 10, while charging device1, net loss = 90 per sec, so even if we charge it from the start, its energy decreases at 90 per sec, so it hits zero at time 1/90 ≈ 0.011111... seconds. That's exactly the bound: T_max = b1 / (a1 - p)? Actually if we charge it continuously, energy = b1 + (p - a1)t = 1 - 90t, zero at t=1/90 ≈ 0.011111. That's the maximum if we always charge device1. Device2 has plenty of energy. Could we do better by not charging device1 continuously? No, because device1 is the critical one; any time we don't charge it, it drains even faster. So maximum T is 1/90. That matches the condition sum D_i(t) <= t fails after that t. So the condition seems correct.
Thus, feasibility for a given T reduces to checking that for all t in [0,T], sum_i max(0, (a_i t - b_i)/p) <= t. Equivalently, for all t in [0,T], sum_i max(0, a_i t - b_i) <= p t. Since p>0, multiply both sides by p: sum_i max(0, a_i t - b_i) <= p t.
But note that max(0, a_i t - b_i) = 0 when t <= b_i / a_i. So the sum only includes devices with t > b_i / a_i. So define function f(t) = sum_{i: t > b_i/a_i} (a_i t - b_i) - p t. We need f(t) <= 0 for all t in [0,T]. f(t) is piecewise linear, with breakpoints at t_i = b_i / a_i (sorted). f(t) is continuous? At t = b_i/a_i, the term becomes 0, so f is continuous if we include the term from both sides? Actually for t just below b_i/a_i, term is 0; at t just above, term is a_i t - b_i (which tends to 0 as t approaches from above). So continuous. f(0) = -p0? Actually at t=0, sum over none =0, so f(0)=0? Wait: sum_i max(0, a_i0 - b_i) = sum_i max(0, -b_i)=0, so f(0)=0 - p*0 = 0. So f(0)=0. For t>0, initially maybe some devices have t > b_i/a_i? The smallest b_i/a_i might be >0. So f(t) may be negative or positive depending.
We need f(t) <= 0 for all t up to T. The maximum T such that this holds for all t in [0,T] is the answer. Also, if there exists no T where f(t) > 0? That is, if f(t) <= 0 for all t >=0, then we can survive indefinitely? Let's check: If for all t, sum_i max(0, a_i t - b_i) <= p t, then we can always meet demands, and we can schedule indefinitely. But is that condition also necessary for indefinite operation? If we can survive indefinitely, then for any T, there exists a schedule; thus the condition must hold for all T, meaning f(t) <=0 for all t. Conversely, if f(t) <=0 for all t, does it guarantee indefinite survival? Possibly yes, because we can always design a schedule that meets the instantaneous demands. However, we also need to consider that the schedule might need to be defined for infinite horizon; but if condition holds for all t, we can use an online policy like "always charge the device with the smallest current energy" or something to keep them alive. But is there any subtlety? The condition sum_i max(0, a_i t - b_i) <= p t for all t is equivalent to p >= sum_i a_i? Let's examine: For large t, max(0, a_i t - b_i) ~ a_i t - b_i. So f(t) ≈ (sum_i a_i - p) t - sum_i b_i. For large t, this linear function's slope is sum_i a_i - p. If sum_i a_i > p, then for sufficiently large t, f(t) becomes positive, so condition fails. So indefinite survival requires sum_i a_i <= p. But is that sufficient? Suppose sum_i a_i <= p. Then for large t, f(t) ~ (sum a_i - p) t - sum b_i, which is negative because slope negative (or zero if equal) and negative intercept? Actually if sum a_i < p, slope negative, so f(t) eventually goes to -∞, so condition holds for all large t. But there might be intermediate t where f(t) > 0 even if sum a_i <= p? Let's test with two devices: a1=2, b1=100; a2=2, b2=100; p=3. sum a_i =4 > p=3, so not indefinite. So that case fails. For sum a_i <= p, it seems plausible that f(t) <=0 for all t. Let's test a scenario where sum a_i <= p but some devices have small b_i leading to early spikes? Consider a1=10, b1=1; a2=0.1, b2=100; p=10.1? Wait sum a_i =10.1, p=10.1 exactly. So p = sum a_i. Then f(t) = sum max(0, a_i t - b_i) - p t. For t small, only device1 may be positive: for t > 0.1, device1 term = 10 t -1. Device2 term = 0 for t up to 1000? Actually b2/a2 = 100/0.1=1000. So for t in (0.1, 1000), f(t) = (10t -1) -10.1 t = -0.1 t -1 <0. For t >1000, both active: f(t)= (10t-1)+(0.1t-100) -10.1t = (10t+0.1t -10.1t) + (-1-100) = 0 + (-101) = -101 <0. So okay. What if p > sum a_i? Then slope negative, so eventually f(t) negative, but could there be a positive bump? f(t) is piecewise linear, slopes change at breakpoints. At t=0+, slope = sum of a_i for those devices with b_i=0? But b_i>=1. Initially no devices active, slope = -p? Actually f(t)= -p t when no devices active? Wait if no devices active, f(t) = 0 - p t = -p t, which is negative. So f starts at 0 and immediately negative? At t=0+, f(t) = -p t <0. But later devices become active, adding positive terms a_i t - b_i, which may increase f. Could it become positive? Possibly if many devices become active with large a_i, causing the slope to increase. Starting from negative slope -p, each time we cross a breakpoint where a device becomes active, the slope increases by a_i (since we add term a_i t - b_i, derivative increases by a_i). So the derivative of f(t) is: f'(t) = (sum of a_i over active devices) - p. Initially, derivative = -p (<0). As t increases, devices become active, derivative increases. Eventually, derivative may become positive if the sum of a_i of active devices exceeds p. If derivative becomes positive, f(t) may start increasing. It could cross zero and become positive if the increase is enough. Even if total sum a_i <= p, it's possible that at some intermediate t, the sum of a_i for active devices (i.e., those with b_i/a_i < t) exceeds p? Since total sum a_i <= p, but the active set sum could be > p if some devices have large a_i but also large b_i so they become active later? Wait total sum a_i is sum of all devices. If total sum a_i <= p, then any subset sum is <= total sum, so it cannot exceed p. Actually if total sum a_i <= p, then any subset sum is <= p, so derivative = sum_active a_i - p <= 0 always. Therefore f'(t) <= 0 for all t. And f(0)=0, so f(t) <= 0 for all t. So condition holds automatically. So indefinite survival is equivalent to sum a_i <= p.
But the sample input 2: n=1, a=1, b=1, p=100 -> sum a_i=1 <=100, so indefinite => -1. That matches.
Thus, if sum a_i <= p, answer is -1.
Otherwise, sum a_i > p, so eventually f(t) becomes positive for large t, and we need to find the maximum T such that f(t) <= 0 for all t in [0,T]. Since f(0)=0 and initially negative? Actually at t=0+, f(t) negative because no active devices? Let's compute derivative for t just above 0: active devices are those with b_i=0? But b_i>=1, a_i>=1, so b_i/a_i >= 1/ max? Actually b_i/a_i can be very small if b_i is small and a_i large. For t small, any device with b_i/a_i < t becomes active. So there may be devices with very small b_i/a_i. Suppose we have a device with b_i=1, a_i=100000, so b_i/a_i = 1e-5. For t > 1e-5, that device becomes active, adding a_i=100000 to active sum. So derivative jumps to 100000 - p. If p is much smaller, derivative becomes positive, and f(t) becomes positive quickly. So f(t) may become >0 after a very small t. The maximum T is the smallest t >0 where f(t) becomes 0? Actually we need f(t) <=0 for all t in [0,T]. Since f(0)=0, but just after 0, f(t) might become negative or positive depending. We need the condition for feasibility is f(t) <= 0 for all t in [0,T]. Usually the critical constraint is the supremum of t for which f(t) <= 0. If f(t) dips negative and then rises to zero at some t0, then for t just less than t0, it's negative, so condition holds. At t0, f(t0)=0, that's still okay (since we can have equality? At equality, the demand exactly equals capacity; we can still schedule? Possibly yes, if we can meet exactly, it's feasible). For t > t0, f(t) >0, impossible. So the maximum T is the first t > 0 where f(t) becomes 0 after being negative? Actually f(0)=0. If f(t) becomes negative immediately, then later rises to 0 at some t0, then f(t) <= 0 holds for t up to t0, including t0. So T = t0. But what if f(t) becomes positive immediately after 0? Then the maximum T might be 0? But that would mean devices cannot survive any positive time? Possibly if some device has zero initial energy? But b_i >=1, so not zero. However, if there is a device with a_i > p and b_i very small, it may be impossible to keep it from hitting zero even if we charge it continuously, because even while charging it loses energy at rate a_i - p >0. Then the maximum time would be b_i / (a_i - p). That's positive if b_i >0. That time is the time until it hits zero if we charge it all the time. If we don't charge it continuously, it dies faster. So T would be that value. Does that match our condition? Let's compute f(t) for that single device: f(t) = max(0, a_i t - b_i) - p t. For t < b_i/a_i, it's -p t (negative). For t >= b_i/a_i, f(t) = a_i t - b_i - p t = (a_i - p) t - b_i. This equals 0 at t = b_i/(a_i - p) (provided a_i > p). That's the crossing point from negative to positive? At t = b_i/a_i, f = a_i*(b_i/a_i)-b_i - p*(b_i/a_i) = - p b_i / a_i <0. So f(t) is negative at the breakpoint, then increases linearly with slope a_i - p >0, crossing zero at t = b_i/(a_i - p). So indeed the first time f(t) becomes zero is that t. For t less than that, f(t) <0, so condition holds. So T = b_i/(a_i - p) is the maximum.
Thus, the maximum T is the smallest positive root of f(t)=0? Actually we need sup{t >=0: f(s) <=0 for all s in [0,t]}. Since f is continuous, it's the first t after which f becomes positive. That is the smallest t>0 such that f(t)=0 and f'(t+) >0? But f could cross zero from below (or from negative). Since f(0)=0, but f may become negative right away then later return to zero; the first crossing after 0 might be from negative to positive, giving T as that crossing. However, if f(t) is always <=0 for all t, then T infinite. So we need to find the smallest t > 0 such that f(t) = 0 and for any ε>0 small, f(t+ε)>0? But careful: f could touch zero at multiple points. For piecewise linear f, we can compute f(t) and find the first time after which it becomes positive. Since f(0)=0 and f may go negative immediately, we need to find the smallest t > 0 where f(t) = 0 and f is about to become positive. But is it possible that f(t) is zero at some t but negative after? That would mean f crosses zero downwards, but since f starts at 0 and goes negative, then later could come up, cross zero at t1, go positive, then maybe come down again? Since f is piecewise linear, but slopes can only increase as more devices become active. Once devices are active, they remain active (since for larger t, a_i t - b_i increases). So the set of active devices is monotonic: as t increases, devices only get added. So the derivative f'(t) = sum_active a_i - p. As t increases, the set of active devices expands, so derivative is non-decreasing (since we add non-negative a_i). So f'(t) is piecewise constant and non-decreasing. f(0) = 0. f'(0+) = -p (if no device active at t=0+). Actually at t just >0, the active set includes devices with b_i = 0? But b_i >=1, so for very small t, if any device has b_i=0, it would be active; but none have b_i=0. So active set empty initially, so f'(t) = -p for t < min_i (b_i/a_i). So f(t) = -p t for t in [0, t_min), where t_min = min_i b_i/a_i. So f goes negative linearly. Then at t = t_min, a device becomes active, derivative jumps by +a_i. So after that, derivative = a_i - p. If a_i > p, derivative becomes positive, so f starts increasing. So f will eventually cross zero from below at some t = t0 > t_min. If after adding more devices, derivative becomes even larger, f increases faster. So f will cross zero at most once? It could cross zero, then if derivative stays positive, f stays positive. Could f cross zero, then later become negative again? For that, derivative would need to decrease, but derivative is non-decreasing (since we only add devices, never remove). So once derivative becomes positive, it stays >= that positive value, so f will be increasing after that point. Therefore f can only cross zero at most once after it starts increasing. Since it starts at 0, goes negative, then eventually may increase and cross zero at a unique t0 >0. So the maximum T is that t0. However, it is also possible that derivative never becomes positive: that is, sum_active a_i <= p for all t, which implies sum a_i <= p, so f always <=0, indefinite.
But what if some devices have a_i = p? Then derivative may become zero after adding that device if sum_active = p. If derivative becomes zero and stays zero for a while, f may be constant. But if derivative is zero and f is negative constant, it will never cross zero. So indefinite? Not necessarily: if f is negative constant, that's okay. But if f is negative constant, total demand sum D_i(t) = t - constant? Wait f(t) = sum D_i(t) - t? Actually we had sum D_i(t) <= t equivalent to f(t) <=0. So if f(t) is negative constant, then sum D_i(t) = t - constant < t, so capacity surplus. So feasible indefinite if condition holds for all t. So if sum_active a_i never exceeds p, then f'(t) <=0 always? Actually if sum_active a_i <= p, then f'(t) = sum_active a_i - p <= 0, so f is non-increasing. Since f(0)=0, then f(t) <=0 for all t, good.
Thus, the answer T is the smallest t > 0 such that f(t) = 0 and f'(t+) > 0? Actually if f(t) never becomes positive, answer is -1. Else, the unique root of f(t)=0 for t>0.
But wait, is it always that f(t) crosses zero exactly at the point where sum_active a_i exceeds p? Not exactly; even if derivative becomes positive at some t, f may still be negative at that t and only cross zero later. The crossing point is where the accumulated area (negative then positive) balances out.
So we need to compute T such that sum_i max(0, a_i T - b_i) = p T. Because at T, equality holds? But recall condition for feasibility is sum_i max(0, a_i t - b_i) <= p t for all t in [0,T]. If at T we have equality and for t<T it's < (or <=), then T is the maximum time before the condition fails. If at T it's < p T, we could potentially go a bit further? Actually the critical point is the smallest t where sum_i max(0, a_i t - b_i) > p t (strictly greater). Since f is continuous, that t is the root of equality, provided after that it becomes >. So T is the solution to sum_i max(0, a_i T - b_i) = p T, and for all t<T, sum_i max(0, a_i t - b_i) < p t (strict). But could it be that at the root, the inequality holds with equality and then for t slightly larger it becomes less again? As argued, derivative non-decreasing, so once it becomes positive, it stays >= positive, so after crossing zero, f becomes positive and stays positive. So the root is unique.
Thus, we can find T by solving equation: ∑_{i=1}^n max(0, a_i T - b_i) = p T.
But is that sufficient? Let's test with sample 1: n=2, p=1, devices: (2,2) and (2,1000). Compute sum max: For T such that 2T -2 >0 => T>1. For second: 2T-1000>0 => T>500. So for T between 1 and 500, only first device contributes: max1=2T-2, max2=0. Equation: 2T-2 = 1*T => 2T-2 = T => T=2. So T=2. That matches sample output.
Sample 3: n=3, p=5, devices: (4,3), (5,2), (6,1). Compute breakpoints: b_i/a_i: 3/4=0.75, 2/5=0.4, 1/6≈0.1667. So sorted: t1=0.1667 (i3), t2=0.4 (i2), t3=0.75 (i1). For T in [0,0.1667], all max=0 => sum=0, eq: 0=5T -> T=0 only. So not positive. For T in [0.1667,0.4], only device3 contributes: max3 = 6T -1. Equation: 6T -1 =5T => T=1. But T=1 is >0.4, so not in this interval. So need consider next interval. For T in [0.4,0.75], devices 2 and 3 contribute: max2=5T-2, max3=6T-1. Sum =11T -3. Equation: 11T-3 =5T => 6T =3 => T=0.5. That's within [0.4,0.75], so T=0.5. That matches sample.
Thus, solving that equation in appropriate interval yields answer.
Now we need to verify that condition f(t)<=0 for all t<T is equivalent to the existence of a schedule. We argued that the feasibility condition for a fluid schedule is that for all t, sum_i max(0, a_i t - b_i) <= p t. But is this also sufficient? I think yes, by a "greedy" policy: always charge the device with the smallest current energy (or the one with the earliest "deadline"). This is akin to the "EDF" or "least laxity" scheduling. In fluid terms, we can define a schedule where at each instant we allocate charger to the device with the largest "deficit" relative to its required cumulative charging? Actually we can construct a schedule using the concept of "minimal feasible cumulative charging functions" which satisfy C_i(t) >= D_i(t) and sum_i C_i(t) = t. The condition sum_i D_i(t) <= t ensures that we can set C_i(t) = D_i(t) + α_i(t) where α_i(t) are nonnegative and sum α_i(t) = t - sum D_i(t) (the surplus). The surplus can be allocated arbitrarily, for instance, in proportion to a_i or equally. The issue is to ensure that C_i(t) are non-decreasing and that there exists a feasible instantaneous allocation (C_i'(t) >=0 and sum C_i'(t)=1). Given D_i(t) are non-decreasing, and we have slack, we can simply set C_i(t) = D_i(t) + (t - sum_j D_j(t)) * w_i(t) where w_i(t) are non-negative and sum to 1, and we need C_i'(t) to be achievable. However, it's known that if sum D_i(t) <= t for all t, then the set of cumulative service curves is feasible and there exists a scheduling policy (like the "earliest deadline first" or "processor sharing") that meets the constraints. In fact, this is a classic result in real-time systems: given a set of tasks with arrival curves (here D_i(t) are like minimal service requirements), the necessary and sufficient condition for a single server with capacity 1 to satisfy these service curves is that for all t, the sum of required service up to t does not exceed t. This is because the service curves are "minimum guaranteed" and the server offers a "service curve" of rate 1. For a detailed treatment, see network calculus: the condition for schedulability under arbitrary multiplexing is the "Zhang's test" etc. But I'm convinced.
Thus, our problem reduces to solving for T the equation ∑ max(0, a_i T - b_i) = p T, and also ensuring that for all t < T, the inequality holds (which will be true if we find the smallest positive solution). Then if sum a_i <= p, output -1.
But wait, is there any scenario where the equation has multiple roots, and the smallest positive root is not the maximum feasible T? Let's think: f(t) = sum max(0, a_i t - b_i) - p t. At t=0, f(0)=0. For small t>0, if any device has b_i=0, then f(t) = (a_i t) - p t = (a_i - p) t. If a_i > p, f becomes positive immediately, so the equation f(t)=0 has only t=0? But f(t)>0 for any t>0, meaning condition fails immediately, so maximum T is 0? But b_i must be >=1, so b_i=0 not possible. But consider a device with b_i extremely small; then for t just above b_i/a_i, term becomes positive. f(t) after adding that device may become positive quickly. But f(t) at small t might be negative because before that device activates, f(t) = -p t negative. So f goes negative first, then later may cross zero. So there will be a positive root. Could there be a situation where f(t) never goes negative, i.e., f(t) >=0 for all t>0? That would mean that for all t>0, sum max(0, a_i t - b_i) >= p t. But at t very small, max(0, a_i t - b_i)=0 for all i because t < min_i b_i/a_i, so sum =0, and p t >0, so 0 >= p t? No, that's false. So f(t) = -p t <0 for small t. So f is initially negative. Then as t increases, f may increase and cross zero. Since f is continuous, there will be at least one positive root if f eventually becomes positive. If f never becomes positive, then it stays <=0; that's the indefinite case. So there is at most one positive root (since derivative non-decreasing, f is convex? Actually linear pieces, non-decreasing derivative, so f is convex? Sum of max(0, a_i t - b_i) is convex (since each term is convex, and -p t is linear, so f is convex). Convex function with f(0)=0 and eventually positive may have two roots? Convex can cross zero, become positive, and stay positive. Could it cross zero, then go negative again? No, convex means the function lies above its tangents; if derivative is non-decreasing, once derivative becomes positive, function is increasing, so cannot come back down. So indeed unique positive root (if any) beyond the point where derivative becomes positive.
Thus, we can find T by solving the equation. However, careful: f(t) could be exactly zero over an interval? That would happen if after some point, f(t) = 0 for a range of t. For that to happen, we would need f'(t)=0 and f(t)=0 over that interval. Since f(0)=0 and if derivative remains 0, then f stays 0. But derivative starts at -p, negative, so cannot be 0 initially. Could become 0 after some devices activate? Suppose at some t0, sum_active a_i = p, and f(t0)=0. Then for t>t0, if no new devices activate, derivative =0, so f stays 0. But if new devices activate later, derivative becomes positive, and f would become positive. So there could be an interval where f=0? But if f(t0)=0 and derivative=0, and then later a new device activates, derivative becomes positive, f will increase from 0 to positive. So the boundary of feasible T would be the start of the interval where f becomes >0? Actually if f(t)=0 for t in [t1, t2] and then becomes positive after t2, then for any T up to t2, condition holds (since for t<=t2, f(t)<=0). So maximum T would be t2, the point where it becomes positive. But since at t2, f(t2)=0 (the end of the zero interval), the equation f(T)=0 would have multiple solutions (the whole interval). The maximum feasible T would be the supremum of t where f(t)<=0, which would be t2. And at t2, f(t2)=0, so it's okay. So we need to find the largest t such that f(t) <= 0. That is the root of f(t)=0 where after that f(t)>0. If there is a flat interval where f=0, the largest t in that interval is the boundary before positive. So effectively we need to find the smallest t such that f(t) > 0? Actually we need sup{t: f(s) <=0 ∀ s in [0,t]}. Since f(0)=0 and f is negative for small t, the condition "for all s in [0,t]" requires f(s) <=0 for all s <= t. If f becomes positive at some t0, then for t > t0, the condition fails because at t0, f(t0)>0, but s=t0 is <= t, so condition violated. So the supremum is exactly the first time at which f(t) becomes >0 (or possibly if f jumps from negative to positive, at the jump point it might be 0? Typically continuous). So we need t* = inf{ t>0 : f(t) > 0 } (the first crossing). Since f is continuous, inf = min and equals the unique root where f changes sign from negative to positive (or the left endpoint of a zero interval that ends with positive). Actually if there's an interval where f=0, then for t in that interval, f(t)=0 <=0, so condition holds. The first t where f(t)>0 is after that interval. So t* = end of the zero interval. That end point is also a root (since at the end, f=0). So we can compute the largest t such that f(t) <=0. That's the answer.
Thus, we need to compute T = sup{ t >= 0 | ∑ max(0, a_i t - b_i) <= p t }.
If sum a_i <= p, then f(t) <=0 for all t (as argued), so T infinite -> -1.
Otherwise, we need to find T as the unique solution of ∑ max(0, a_i t - b_i) = p t, but careful: In the case where f(t) = 0 over an interval, the equation holds for many t, we need the largest among them. But does such a situation occur? For f to be zero on an interval, we need that after some t0, f(t)=0 and derivative =0. That requires that sum_active a_i = p exactly, and also that f(t0)=0. Let's see if that can happen. f(t) = ∑_{i in S} (a_i t - b_i) - p t = (∑_S a_i - p) t - ∑_S b_i, where S is set of devices with t > b_i/a_i. So for t in an interval where S is constant, f is linear. For f to be zero on an interval, we need both coefficient (∑_S a_i - p) = 0 and constant term -∑_S b_i = 0, i.e., ∑_S b_i = 0. But b_i >= 1, so ∑_S b_i >0. Therefore f cannot be identically zero over an interval unless the constant term is zero, which is impossible. Wait but consider that S could change? Actually if S changes, the expression changes. So for an interval where S is constant, f is linear. For it to be zero on the whole interval, the linear function must be identically zero, which requires both slope and intercept zero, impossible because intercept = -∑_S b_i <0. So f cannot be zero over a nontrivial interval. Could f be zero at a single point? Yes. So no flat zero segment. Therefore T is simply the unique positive root.
Thus, we can solve ∑ max(0, a_i t - b_i) = p t.
Now the question: How to compute T efficiently given n up to 100k? The breakpoints are at t_i = b_i / a_i. For a given t, we can compute sum over i of (a_i t - b_i) for those i with t > b_i / a_i. That's a piecewise linear function. We can sort devices by b_i / a_i (i.e., increasing "deadline"). Then for each interval between sorted breakpoints, the set of active devices is fixed (those with breakpoint less than t). Actually as t increases, devices become active when t passes b_i/a_i and stay active. So if we sort by b_i/a_i, then for t in [t_k, t_{k+1}) where t_k are sorted breakpoints, the active set is the first k devices (if we sort ascending). However, careful: The breakpoints are b_i/a_i. We need to sort devices by this ratio. Then for t in (t_k, t_{k+1}) (where t_0=0, t_{n+1}=∞), the active devices are those with b_i/a_i <= t, i.e., the first k devices (if sorted ascending, and assuming no ties). So