We need to parse the problem: There's one hero (index 0) and n enemies (1..n). Each has stats: health h, attack a, defense d, agility s. Agilities are all distinct.
Battle: Turn-based, each turn all surviving characters take an action in descending order of agility. The enemies always attack the hero. The hero can choose which enemy to attack each turn. When a character attacks, damage dealt is max(attacker's a - defender's d, 0). Damage accumulates; when total damage taken >= health, that character is immediately incapacitated (so removed from battle at that moment? It says: "The total damage received is greater than or equal to the value of physical strength. The character becomes incapacitated immediately." So at the moment when the damage taken reaches or exceeds health, the character is removed. Since it's immediate, presumably that character stops acting in the same turn? Usually in such turn-based simulations, if a character is killed before its turn in the order, it doesn't get to act that turn. Need to interpret correctly: The battle proceeds in turns. At the start of each turn, we have a set of surviving characters. They all attack in order of descending agility. If a character is killed earlier in the same turn, they are removed and thus won't get to attack if their turn hasn't occurred yet. Similarly, if the hero dies during an enemy attack, the battle ends immediately (since it says battle ends when main character becomes incapacitated, or when all enemies become incapacitated). So we need to consider the order within a turn.
Given that all actions happen in each turn: we need to compute the minimum total damage the hero takes over the course of battle, assuming the hero can choose which enemy to attack each turn optimally, and the enemies always attack the hero. The hero wants to survive and kill all enemies while minimizing total damage taken? But the output is: "When the hero is sure to be incapacitated, output -1. Otherwise, output the minimum total damage to the hero in one line." So if there is any possibility that the hero can win (kill all enemies without dying) regardless of enemy actions? Actually enemy actions are deterministic: they always attack the hero. So it's not a "possibility" but deterministic given hero's choices. So if there is a strategy for the hero to kill all enemies before he dies, we can compute the minimum possible total damage taken over all such strategies? Or maybe the hero can't influence damage taken except by choosing which enemy to attack, which affects how many enemy attacks happen before they die. So we need to compute, for a given set of enemy stats, whether the hero can guarantee victory (i.e., there exists a sequence of attacks that results in all enemies dead before hero health reaches zero) and among those strategies, the minimum total damage the hero receives (the cumulative damage taken before all enemies are dead; hero may survive with remaining health). If the hero cannot survive no matter what, output -1.
But we need to be careful: The battle ends when hero dies OR all enemies die. So if hero dies at the same time that the last enemy dies? Typically if hero kills the last enemy, but then an enemy attack might have already occurred earlier in the turn? Let's consider ordering: Within a turn, characters attack in descending agility. Suppose hero's agility may be higher or lower than enemies. The hero could kill an enemy during his attack; if that enemy's agility is lower than hero's, the hero would attack before that enemy (since higher agility goes first). So that enemy might not get to attack that turn. Conversely, if an enemy has higher agility than hero, it will attack before hero in the turn. So the order matters.
Thus we need to simulate an optimal strategy? With up to 40,000 enemies, we need an efficient method, likely based on sorting and some kind of priority selection.
Let's define:
- Hero stats: H0, A0, D0, S0.
- Enemy i: Hi, Ai, Di, Si.
All Si distinct.
Damage dealt by attacker to defender: max( A_attacker - D_defender, 0 ). So effective attack damage = max(0, A - D_def). For hero attacking enemy i, damage per hit = dmg0i = max(A0 - Di, 0). For enemy i attacking hero, damage per hit = dmg_i0 = max(Ai - D0, 0). (Note: if attack <= defense, damage is 0, so that character cannot hurt the opponent; they'd be useless except maybe for something else? They can still act but do no damage.)
Now, the battle proceeds in turns until termination. In each turn, surviving characters act in order of decreasing agility. The hero can choose which enemy to attack (if any? If all enemies dead, battle ends). The enemies always attack the hero. If an enemy dies during the turn before its attack, it doesn't attack.
Goal: find if hero can kill all enemies before his health reaches <=0. And minimize total damage taken.
Observation: The hero's actions are only to choose which enemy to target each turn. The rest is deterministic. So this is like a scheduling problem: we need to decide an order to kill enemies, possibly interleaving with enemy attacks based on agility ordering. The damage taken by the hero is the sum of damage from each enemy attack that actually occurs before the hero dies.
Because each enemy can potentially attack multiple times before being killed. The number of times enemy i attacks depends on: (1) The turn in which the hero starts targeting it, (2) how many turns it takes to kill it (based on its health and hero's damage per hit), (3) the relative agility order: if enemy i's agility > hero's, it may attack before the hero each turn, so it gets an attack in the turn it is killed? Actually careful: Suppose hero decides to focus on enemy i until it's dead. In each turn, the order is: all characters with agility > hero (including maybe some enemies) act first, then hero acts (if his agility is lower than them), then characters with agility < hero act after. Actually it's descending order: sort all survivors by agility decreasing, then each in order attacks. So hero's position in that order depends on his agility relative to each enemy. For each enemy, if enemy's agility > hero's agility, that enemy attacks before hero in each turn. If enemy's agility < hero's, enemy attacks after hero.
Thus, when focusing on enemy i, the number of attacks enemy i gets before it dies depends on whether it attacks before or after hero in the turn. Let's denote:
- For an enemy with higher agility than hero (S_i > S0): In each turn, enemy i will attack before hero. So if the hero needs T hits to kill enemy i (number of hero attacks required), then enemy i will get to attack T times (each turn, before the hero's attack). Additionally, before the hero starts attacking enemy i (i.e., while hero is attacking other enemies), enemy i will also attack each turn. But if we are focusing on it from the start? We can choose to kill enemies in some order.
Alternatively, for an enemy with lower agility than hero (S_i < S0): In each turn, hero attacks before enemy i. So if the hero kills enemy i in a turn, the enemy i will not get to attack in that same turn, because hero attacks first and kills it before its turn. So enemy i gets (number of hero attacks on it minus 1?) Actually need to consider: Hero attacks it each turn; if hero kills it during his attack, it dies immediately and is removed, so it does not get to attack later in that turn. So for lower agility enemies, they get one fewer attack than the number of turns in which they are alive at the start of the turn? Let's formalize:
Suppose hero will perform attacks on enemy i across multiple turns. Let t be the number of turns in which the hero attacks enemy i. In each turn, the order is: hero attacks (since hero agility > enemy) then enemy attacks (if still alive). But if hero kills enemy during his attack in turn t, enemy won't attack in that turn. So enemy i attacks in the first t-1 turns (when it survives after hero's attack, then it attacks), and does not attack in the final turn (when it dies). So total attacks from enemy i = max(t - 1, 0). However, if t=0 (not attacked), then it never gets attacked but it's alive and will attack each turn while hero is attacking others; but that is counted in the pre-phase.
Better to consider overall timeline: We have a sequence of hero actions (each turn one attack on some enemy). Enemies attack each turn according to the order, depending on if they are alive at the moment of their turn.
We want to minimize total damage to hero. The hero's health is limited, but we just need the minimal total damage incurred while achieving victory. Since damage taken is cumulative, we can think of the hero's health as a resource: we want to ensure the total damage does not exceed H0 - 1 (since if reaches H0, hero dies). But we aim to minimize that total damage; however if we can achieve victory, we might want to minimize damage taken, which might involve killing enemies in a certain order to reduce number of attacks from dangerous enemies.
Essentially we need to schedule the order of killing enemies (each enemy requires a certain number of hero attacks to kill, given hero's damage per hit to that enemy) to minimize the total damage taken, where each enemy i inflicts damage d_i = max(A_i - D0, 0) each time it attacks. The attacks from enemy i occur at specific times depending on relative agility and the schedule.
This resembles a classic "turn-based battle with agility" problem. I've seen problems like "Hero vs monsters" where you decide order to minimize damage, often solved by sorting by some ratio or priority.
Let's attempt to model the damage taken as a function of the order.
Assume we decide an order to kill the enemies: permutation π of {1..n}. The hero will focus on the first enemy in the order, attack it repeatedly until it dies, then move to the next, etc. However, is it optimal to focus on one enemy at a time? Possibly yes: Because switching targets could cause extra damage? Typically in such problems, it's optimal to kill enemies one by one because damage is additive and there's no benefit to splitting attacks. But need to verify: Could it be beneficial to partially damage multiple enemies to reduce their attacks? But attacks are per turn, and each enemy attacks each turn (unless killed). So if you partially damage an enemy, it still attacks each turn. So you only stop its attacks when it is dead. So it's always beneficial to kill an enemy as soon as possible, i.e., focus on one until death. However, the hero can only attack once per turn. So if you attack enemy A one turn and then enemy B next, you are delaying the death of both, causing both to attack more turns. So focusing on one at a time seems optimal. But we must consider that the hero may have limited damage per hit; and if some enemies have very high health, they might require many attacks, but maybe there is a scenario where attacking a high-damage enemy early reduces damage even if it takes long? Actually the decision is which enemy to kill first. So focusing on one at a time is reasonable.
Thus, the hero's strategy reduces to choosing an order to eliminate enemies sequentially, fully killing each before moving to the next. We need to check if this is always optimal; I think it is, because the damage taken per turn is the sum of damages from all alive enemies that get to attack that turn. Since the damage per turn is additive, the total damage is sum over turns of total damage from all alive enemies (that attack). The hero wants to minimize that sum. This is akin to scheduling jobs (enemies) where each job has a processing time (number of attacks needed to kill it) and a weight (damage per turn it contributes while alive). However, there is twist: due to agility order, an enemy's attack may not occur in the turn it is killed if its agility is lower than hero's. So the "weight" contributed in the final turn might be zero for that enemy. But this can be accounted by adjusting the damage count for the kill turn.
Specifically, for an enemy with higher agility (faster than hero), it will attack before hero's attack each turn. So if the hero kills it in a certain turn, that enemy will still attack in that turn (because it acts before hero). So it contributes damage on every turn that it is alive at the start of the turn, including the turn it dies.
For an enemy with lower agility (slower than hero), it attacks after hero. So if hero kills it in a turn, it won't attack in that turn. So it contributes damage on each turn that it is alive at the start of the turn, except the turn it dies (because it dies before its attack). Equivalent: It attacks in each turn that it survives the hero's attack.
Therefore, the total number of attacks from enemy i, given that it is killed after receiving T hero attacks (i.e., T turns in which hero attacks it) is:
- If S_i > S0: number of attacks = T (since it attacks each turn before hero, including the turn it dies).
- If S_i < S0: number of attacks = T - 1 (since it does not attack in the turn it dies).
But careful: What if T=0? That cannot happen because to kill it need at least 1 attack if dmg0i > 0? Actually if hero does zero damage to it (A0 <= Di), then it can't be killed. In that case victory impossible? Unless hero has some other way? But hero only attacks, can't kill if damage <= defense. So if for any enemy, dmg0i == 0, then hero cannot kill it, so answer is -1 (unless it's already dead? But it's alive initially). So we must check that for all enemies, A0 > Di? Actually damage is max(A0-Di, 0). So if A0 <= Di, hero does zero damage, can't kill. So if any enemy has Di >= A0, then hero can't kill it, so answer -1. Also, hero may be able to kill enemies with zero damage? No. So if any enemy has Di >= A0, impossible. However, there is nuance: maybe hero's attack is 0 but enemy's health may be 0? Health is at least 1 per constraints. So impossible.
Similarly, if for hero, some enemies may have Ai <= D0, they do zero damage to hero; they are harmless. They can be ignored? But they still need to be killed because all enemies must be incapacitated. But they do no damage, so they don't contribute to hero's damage. However they may still require attacks to kill, but those attacks take time and allow other harmful enemies to attack more. So they still affect the schedule, but have zero weight.
Now, what about enemies that have S_i equal to S0? But si are all distinct, so no ties.
Thus we can partition enemies into two groups: fast enemies (S_i > S0) and slow enemies (S_i < S0). Their effect differs by 1 attack in the killing turn.
Now, consider we are to kill enemies in some order. Let's denote for each enemy i:
-
t_i: number of hero attacks required to kill it. Since hero's damage per hit to enemy i is dmg0i = max(A0 - Di, 0). We need to find smallest integer t_i such that t_i * dmg0i >= Hi. Actually damage accumulates; if hero deals dmg0i each hit, and enemy health is Hi, then number of hits needed = ceil(Hi / dmg0i). Since immediate incapacitation when damage >= health. So t_i = ceil(Hi / dmg0i). Note: dmg0i must be > 0; else impossible.
-
w_i: damage inflicted to hero per attack by enemy i, w_i = max(Ai - D0, 0). Could be zero.
Now, suppose we schedule enemies in order π(1), π(2), ..., π(n). While we are focusing on an enemy, we are attacking it each turn. The total damage taken is the sum over all turns of the sum of w_i for enemies that are alive and get to attack in that turn.
Given the order, the timeline: Initially all enemies are alive. The hero will first attack enemy π(1) for t_{π(1)} turns (consecutive). Then enemy π(1) dies at the end of the t_{π(1)}-th attack (or maybe during the attack). After that, hero moves to enemy π(2), attacks it for t_{π(2)} turns, etc.
We need to compute total damage received.
Let’s denote total time (turns) = T_total = sum_{i=1}^{n} t_i. Because each turn hero attacks exactly once, and total attacks needed to kill all enemies is sum t_i. However, note that after the last enemy is killed, the battle ends immediately; the hero may not get to act after? Actually the battle ends when all enemies become incapacitated. That can happen in the middle of a turn? If the hero kills the last enemy with his attack, then the turn ends? Or does the turn continue with remaining enemies? Since there are no enemies left, battle ends. So the hero's attack that kills the last enemy ends the battle; subsequent enemies (none) don't get to attack. So the total number of turns is exactly sum t_i, each turn consists of the hero making one attack and enemies attacking according to order.
But careful: If the hero kills the last enemy, and that enemy is fast or slow, could there be other enemies still alive? No, it's the last. So after the kill, battle ends. So no further attacks.
Now, to compute total damage, we need to sum for each turn the damage from each alive enemy that attacks in that turn. The attack pattern depends on agility relative to hero.
For a given enemy i, it will attack in a turn if:
-
It is alive at the start of that turn.
-
And either it is fast (S_i > S0) and it attacks before hero, so if it is alive at start of turn, it will attack (since hero attacks later). However, if it is killed by hero in that same turn, but because it's fast, its attack happens before hero's attack, so it will still attack because it's alive at its turn. So for fast enemies, they attack in every turn that they are alive at the beginning of the turn (which includes the turn they die, because they haven't been killed yet when their attack occurs).
-
For slow enemies (S_i < S0): They attack after hero. So if they are alive at the start of the turn, they will attack only if they survive the hero's attack. Since hero attacks before them, if hero kills them during his attack, they will not attack in that turn. So they attack in a turn only if they are alive after the hero's attack. That means they attack in turns where they are not the target being killed (i.e., they are either not the current target, or if they are the current target but hero's attack does not kill them (i.e., before the final hit), or if they are the current target but the hero's attack kills them? In that case they don't attack. So slow enemies attack in a turn if they are alive at start and either they are not the target of the hero's attack, or they are the target but the hero's attack does not finish them (i.e., it's not the final hit). So essentially, for a slow enemy, the number of attacks it makes equals the number of turns in which it is alive at start minus the number of turns in which it is killed by hero. Since it is killed exactly once, it misses exactly one attack (the turn it dies). For fast enemies, they don't miss that attack.
Thus, for a given schedule, we can compute total damage as:
Total damage = sum_{i} w_i * (number of attacks from enemy i).
Number of attacks from enemy i = (number of turns in which enemy i is alive at the start of the turn) - (if slow? 1 if it is slow, else 0). More precisely: For slow enemies, subtract 1 because the turn in which it dies, it does not attack. For fast enemies, no subtraction.
Now, what is the number of turns enemy i is alive at the start? That depends on when it gets killed.
Let the order be π(1),...,π(n). Let T_k = sum_{j=1}^{k} t_{π(j)} be cumulative attacks up to after killing the k-th enemy. So enemy π(k) is killed at the end of turn T_k (i.e., during turn T_k, the hero's attack kills it). More precisely, it dies during turn T_k, after hero's attack. So it is alive at the start of turns 1,2,...,T_k. Because before turn 1, all enemies alive. At start of turn t (1-indexed), enemies that have not been killed yet are alive. So enemy i (which is π(k)) is alive at the start of turns 1 through T_k inclusive? Or through T_k? Let's define: At beginning of turn 1, all alive. At the end of turn T_k, after hero's attack, enemy π(k) dies. Then at the start of turn T_k+1, it is dead. So it is alive at the start of turns 1,2,...,T_k. So number of starts-of-turn it is alive = T_k.
But careful: If enemy is killed during turn T_k, is it considered alive at the start of turn T_k? Yes. So it's T_k turns.
For enemy i, if it is the k-th killed, it is alive at start of T_k turns.
Thus, number of attacks from enemy i = (T_k) - (if i is slow then 1 else 0). For fast enemies: attacks = T_k. For slow: attacks = T_k - 1.
But wait: For slow enemies, they do not attack on the turn they die because hero attacks first and kills them. So they would be alive at start of turn T_k, but they don't get to attack in that turn. So indeed subtract 1.
Now, what about enemies that are not yet killed? They are alive for all turns from 1 to T_total? Actually after all enemies are dead, battle ends, so there are no further turns. So for the last enemy, after it's killed, the battle ends, so there is no turn after T_total. So for each enemy i, the number of turns where it is alive at start is exactly the cumulative turn number when it is killed (T_{pos(i)}). For enemies killed earlier, they are dead for the remaining turns. So overall, total damage = sum_{i} w_i * (T_{pos(i)} - delta_i) where delta_i = 1 if S_i < S0 (slow), else 0.
But is this correct for fast enemies? For a fast enemy, it attacks in every turn it is alive at the start (including the turn it dies). Since it attacks before hero, even though it dies in that turn, it still attacks. So attacks = T_k. Good.
Now, this formula seems to sum over enemies the number of attacks they perform. However, is there any double counting or missing? Yes, total damage is sum over enemies of w_i * (number of attacks from enemy i). So this formula yields total damage.
But we must ensure that the hero's own attacks happen each turn and that the order within the turn does not affect counts beyond the subtraction for slow enemies. Also, we need to consider if any enemy might attack after being killed by hero in the same turn due to ordering? For fast enemies, they attack before hero, so they are alive. For slow, after hero. So our logic holds.
Now, the total damage expression becomes:
Total damage = Σ_i w_i * T_{pos(i)} - Σ_{i: slow} w_i.
But note Σ_{i: slow} w_i is constant (sum of w_i over slow enemies). So minimizing total damage is equivalent to minimizing Σ_i w_i * T_{pos(i)}.
Since the constant subtraction does not affect optimization (it's a fixed offset if we can win), we need to minimize Σ_i w_i * T_{pos(i)} over permutations of the enemies. And T_{pos(i)} is the total number of turns (hero attacks) that have occurred up to and including the turn when enemy i is killed. That is, if we order enemies as a sequence, and let t_i be the processing time (number of attacks needed), then for a given order, the completion time (start-of-turn alive count) for job i is the sum of t's of all enemies up to and including i in the order. So Σ w_i * C_i where C_i is the completion time (the time when job i finishes, measured as the number of turns elapsed up to the end of its processing). This is exactly the classic scheduling problem: minimize weighted sum of completion times on a single machine, where each job has processing time t_i and weight w_i. And the optimal schedule is to order jobs by decreasing "ratio" w_i / t_i? Actually minimizing Σ w_i C_i is solved by the Smith's rule: schedule in order of decreasing ratio w_i / t_i (or equivalently, decreasing "value" of w_i/t_i) if all jobs are available at time zero. Wait, the classical problem: minimize Σ w_j C_j, where C_j is completion time. The optimal schedule for a single machine without preemption is to order jobs by the ratio of weight to processing time in non-increasing order? Let's recall: For minimizing Σ w_j C_j, the optimal order is by the ratio w_j / p_j in non-increasing order? Actually there is a known result: Weighted Shortest Processing Time (WSPT) rule: order jobs by decreasing w_j / p_j (or equivalently, increasing p_j / w_j). But I'm not entirely sure; let's derive:
The objective is Σ w_j C_j. If we have two jobs i and j adjacent, with processing times p_i, p_j and weights w_i, w_j. If we schedule i before j, contribution to the sum from these two jobs (ignoring others) is w_i * p_i + w_j * (p_i + p_j). If we schedule j before i, contribution is w_j * p_j + w_i * (p_i + p_j). The difference (i before j) minus (j before i) = w_i p_i + w_j (p_i + p_j) - [w_j p_j + w_i (p_i + p_j)] = w_i p_i + w_j p_i + w_j p_j - w_j p_j - w_i p_i - w_i p_j = w_j p_i - w_i p_j. So i before j is better (i.e., gives smaller sum) if w_j p_i < w_i p_j, i.e., w_i / p_i > w_j / p_j. So we should order by decreasing w_i / p_i. Yes, that's correct. So optimal schedule is by descending ratio w_i / t_i (if ties, any order). However, this holds when all w_i are non-negative and t_i positive. Here w_i can be zero, t_i positive. So jobs with w_i=0 have ratio 0, and can be placed anywhere (preferably last to not delay others? Actually they have zero weight, so they don't contribute to the sum regardless of their completion time, but they do affect completion times of others because they take processing time. To minimize Σ w_i C_i, we want to schedule jobs with larger w_i/t_i earlier. For zero weight, they have zero ratio, so they should be scheduled after all positive ratio jobs. But also consider that scheduling a zero-weight job earlier would increase the completion times of later (positive weight) jobs, thereby increasing total cost. So indeed they should be last.
Thus, the optimal order is: sort enemies by decreasing value of w_i / t_i (or equivalently decreasing w_i/t_i). If two have same ratio, any order; if w_i=0, ratio=0, they go last.
But wait: There's also the subtraction of constant Σ_{slow} w_i. That constant is independent of order, so it doesn't affect optimal order. However, we must consider that the formula for total damage includes that constant. So once we compute the minimal Σ w_i C_i, total damage = that sum - Σ_{slow} w_i.
But we must also check that hero actually survives: we need to ensure that at no point does the hero's cumulative damage exceed H0 - 1? Actually the battle ends if hero becomes incapacitated. We need to check if there exists an order such that total damage taken (which we compute) is less than hero's health H0? Actually the hero's health is H0. He can survive if total damage taken < H0 (since damage taken is total damage, when it reaches H0, he dies). But we want the minimum total damage achievable; if that minimum is >= H0, then the hero cannot survive (since any strategy leads to at least that much damage, and if it's >= H0, hero dies). But note: The hero could die before the end if cumulative damage reaches H0 during battle. In our calculation, total damage is the sum of damage from all enemy attacks that occur before the battle ends (when all enemies are dead). If the hero dies earlier, the battle ends earlier, and total damage might be less than what we computed? Actually if hero dies, the battle ends and we don't care about total damage? The problem asks: if hero is sure to be incapacitated, output -1. So if there is any strategy that avoids hero death, we output the minimum total damage. So we need to check if there exists a schedule such that the hero's cumulative damage never exceeds H0 - 1? Actually total damage taken might be less than H0, but is it sufficient? If the total damage is less than H0, then hero never reaches health zero because damage accumulates; but could he die earlier than final total? The damage is cumulative; if at some intermediate point, the damage sum reaches H0, hero dies. However, if the sum of all damages over the whole battle is less than H0, then at every intermediate point it's also less than H0? Not necessarily; the cumulative damage could exceed H0 during battle and then later... no, damage cannot decrease, so if the total sum at the end is less than H0, then the maximum cumulative damage (which is the final sum) is less than H0, so it never reaches H0. So it's safe: if total damage < H0, hero survives. If total damage >= H0, it's possible that hero dies exactly when it reaches H0. But could there be a schedule where the hero dies but still kills all enemies? The battle ends as soon as hero dies; if hero dies before all enemies are dead, that's a loss. So to win, we need the hero to survive until all enemies are dead; thus total damage must be strictly less than H0 (or maybe exactly H0 if death occurs at same time as last kill? But battle ends when hero becomes incapacitated; if damage equals H0 at the moment the last enemy dies, which event occurs first? That depends on order within the turn. If the last enemy is killed by hero's attack, and that same turn, enemy attacks may have occurred before or after that attack. If hero kills the last enemy, then battle ends immediately, and if hero's health was already below H0? Let's think carefully: The hero's health might be reduced by enemy attacks before his attack in that turn. Suppose after the enemy attacks in that turn (some enemies might attack before hero), hero's damage taken might reach H0, causing him to die before his attack. Then battle ends and hero doesn't get to attack, so last enemy not killed. So for hero to kill the last enemy, he must survive until his attack. So the cumulative damage before his attack in that final turn must be < H0. Then after his attack, he may take more damage from enemies that attack after him (if any). But if he kills the last enemy, and there are no enemies left, then no further attacks occur. So hero's final damage is whatever he took before his attack plus possibly attacks from enemies that acted before his attack that turn (fast enemies). After his attack, there are no enemies, so no more damage. So hero's total damage after battle is the damage taken up to that point. So to survive, we need that total damage < H0 (strictly less). If damage equals H0 at any point, hero is incapacitated, battle ends; if that happens after his attack but before enemy attacks? But if it's equal at the moment after an attack, he dies. However, if damage equals H0 exactly at the moment after his attack, but the last enemy is dead, battle ends anyway. Could that be considered a win? The problem states: "The battle ends when the main character becomes incapacitated, or when all the enemies become incapacitated." So if hero becomes incapacitated at the same time as all enemies become incapacitated, what takes precedence? Typically if both conditions happen simultaneously, it's ambiguous. But we can avoid that nuance by requiring total damage < H0 to guarantee win. However, maybe there is a scenario where total damage equals H0 but hero still wins because the fatal blow coincides with the last kill? Let's examine: Hero's health is H0. If damage taken so far is H0 - d, and then he receives an attack that deals d damage, then damage becomes H0, hero is incapacitated immediately. So if that attack comes from an enemy, hero dies before his next action. So for hero to kill the last enemy, he must not die before his attack. So the only way total damage could equal H0 and still kill all enemies is if the fatal damage occurs from an enemy attack that happens after hero's attack, but after hero's attack all enemies are dead, so there would be no enemy to deliver that fatal blow. So if all enemies are dead, there is no enemy to attack. So the fatal damage cannot happen after all enemies are dead. Could it happen exactly when hero kills the last enemy? Suppose the last enemy is fast (S_i > S0). Then in the final turn, the enemy attacks first, dealing some damage, then hero attacks and kills it. If after the enemy's attack, hero's damage becomes H0, he would die before his attack, so he wouldn't kill it. So no. Suppose the last enemy is slow. Then hero attacks first, kills it, battle ends. No enemy attacks after. So hero does not take any damage in that turn after his attack. But he could have taken damage from other enemies before? But if it's the last enemy, there are no other enemies. So the only damage in that turn could be from the last enemy if it's fast (attacking before hero). So for slow last enemy, no damage in that turn. So total damage < H0 if we survive. So safe condition: total damage must be < H0. If total damage = H0, hero dies before finishing? Possibly not: Suppose hero's health is exactly H0 and he has taken 0 damage initially. If an enemy deals 0 damage each attack, then total damage = 0 < H0, fine. If an enemy deals damage, total damage is integer? Could be exactly H0 after some attack. At that point, hero dies. So to win, total damage must be < H0. So we can set condition: minimal possible total damage (as computed) < H0. If minimal total damage >= H0, then hero cannot survive any strategy (since we found the minimum possible total damage; if it's still at least H0, then any strategy leads to at least H0 damage, so hero will die). However, is it possible that the minimal total damage we compute could be less than H0, but due to ordering of attacks within a turn, the actual damage incurred could be higher? Our formula for total damage (Σ w_i * (T_i - delta_i)) assumes that the number of attacks from each enemy is exactly as described: for slow enemies, they miss the turn they die. That is correct given our order (focus kill one at a time). But could there be a strategy that is not "focus kill one at a time" that yields lower total damage? Possibly if we interleave attacks on multiple enemies to exploit the fact that some enemies might be killed mid-turn and thus not attack if they are slow? But focusing on one at a time already yields that property: When focusing on a slow enemy, it misses its attack on the turn it dies because hero kills it. If we interleave, you might cause a slow enemy to miss its attack more times? For example, suppose you attack enemy A for a while, then switch to enemy B before killing A. A is slow. When you eventually come back to A and kill it, you might have caused A to miss an attack only on the final kill turn. But while you are attacking B, A is alive and will attack each turn (since it's slow, it attacks after hero; as long as it's alive at start, and it's not the target of the hero's attack? Actually if A is slow, its attack occurs after hero's attack regardless of which enemy hero attacks. So A will attack in every turn it is alive, except possibly the turn it is killed (if hero attacks it and kills it). So if you interleave attacks, A may be killed on a turn when you attack it, and that's the only turn it misses. So the total number of attacks from A is (number of turns A is alive at start) - 1. That's same as if you focused: it is alive for all turns from start until the turn it dies. The number of turns it is alive at start equals the turn number when it dies (since it dies during that turn). That turn number depends on when you finally kill it. So the total attacks from A is simply (completion time) - 1. So focusing or interleaving doesn't change the completion time for each enemy? The completion time is the turn number when the enemy receives the final blow. If you interleave attacks, the completion time of an enemy might be later than if you focused, because you spent turns attacking others. To minimize total damage, we want to complete high-weight enemies early (since they contribute damage each turn they are alive). This is exactly the weighted completion time objective. Interleaving does not allow completing an enemy earlier than its processing time plus the time spent on others before it; the sum of completion times weighted by w_i is minimized by ordering jobs without preemption? In single machine scheduling, preemption (i.e., splitting a job) does not improve the weighted sum of completion times for a single machine? Actually, for minimizing Σ w_j C_j with preemption allowed, the optimal schedule is still non-preemptive? I recall that for this objective, the optimal schedule is the same as without preemption: you schedule jobs in order of decreasing w_j / p_j, and you do not need to preempt. Preemption can't improve the sum because the objective is linear and the processing times are fixed. The classic result: Shortest Processing Time (SPT) for unweighted sum, Weighted Shortest Processing Time (WSPT) for weighted sum, are optimal even with preemption? Actually, for minimizing sum of completion times on a single machine, preemption doesn't help because any preempted job can be rearranged to be contiguous without increasing completion times (by exchanging pieces). The optimal schedule is non-preemptive. So focusing on one enemy at a time (non-preemptive) is optimal.
Thus, the optimal strategy is indeed to kill enemies one by one in order of decreasing w_i / t_i (Smith's rule). However, there is a nuance: The subtraction of delta_i = 1 for slow enemies means the effective weight for the completion time term is w_i, but we have a constant offset. So ordering remains same.
Therefore, the problem reduces to:
- Check if A0 > Di for all i? Actually we need dmg0i = max(A0 - Di, 0) > 0 for each enemy. If any enemy has Di >= A0, then impossible -> output -1.
- Compute t_i = ceil(Hi / dmg0i). (since hits needed)
- Compute w_i = max(Ai - D0, 0). (could be zero)
- Partition enemies into fast (S_i > S0) and slow (S_i < S0). For slow, we will subtract w_i from total damage later.
- Determine if there exists an order (permutation) such that total damage = Σ w_i * C_i - Σ_{slow} w_i < H0, where C_i is the completion time (the turn number when enemy i is killed) under that order. And we want the minimal possible total damage. Since Σ w_i C_i is minimized by ordering by decreasing w_i / t_i, we can compute the minimal total damage using that order.
- Then check if that minimal total damage < H0. If yes, output that minimal total damage; else output -1.
But is there any other factor? We must also consider that the hero may also take damage from enemies that have w_i = 0, but they still affect the schedule because they increase completion times of others. So ordering by ratio handles that.
But we need to verify the formula for total damage more carefully, especially with multiple enemies alive and the order within turn affecting the counts for each enemy. In our derivation, we assumed that each enemy i, if alive at start of turn, attacks exactly once per turn (except slow on death turn). Is that always true? Let's simulate a small example to confirm.
Consider two enemies: one fast (F) with S_f > S0, one slow (S) with S_s < S0. Hero agility S0. Turn order: descending agility: if F > hero > S. So order: F attacks, then hero, then S. All alive.
Suppose hero is focusing on F first, t_F hits needed.
- In each turn while F is alive: F attacks (since fast, always attacks), hero attacks F, S attacks (since slow, attacks after hero). But note: S is slow, so it attacks after hero; if hero kills F during his attack, then after hero's attack, F is dead. Then S attacks (since it's still alive). But F is dead, so S attacks hero. So in the turn when F dies, F attacks before hero (since fast), then hero kills F, then S attacks. So F gets an attack on its death turn, S gets an attack on that turn as well (since it's alive after hero's attack). So number of attacks from F = number of turns it was alive at start = T_F (since it dies on turn T_F). Number of attacks from S: while both are alive, S attacks each turn; after F is dead, hero attacks S for t_S turns. During those turns, S is slow, so order: hero (fast? Actually hero agility > S? Yes hero > S, so hero attacks first, then S. S will attack each turn it survives hero's attack. On the turn S dies, hero attacks first and kills it, so S does not attack. So total attacks from S = (number of turns S is alive at start) - 1. Number of turns S is alive at start = total turns until S dies = T_F + t_S. So attacks from S = (T_F + t_S) - 1 = T_F + t_S - 1.
Total damage = w_F * T_F + w_S * (T_F + t_S - 1) = w_F * T_F + w_S * T_F + w_S * t_S - w_S = (w_F + w_S) * T_F + w_S * t_S - w_S.
Our formula using completion times: C_F = T_F, C_S = T_F + t_S. Then Σ w_i C_i = w_F * T_F + w_S * (T_F + t_S) = w_F T_F + w_S T_F + w_S t_S. Then minus Σ_{slow} w_i = w_S. So total damage = Σ w_i C_i - w_S. That matches. Good.
Now consider if hero focuses on S first, then F.
Order: S first: t_S turns to kill S. Then F: t_F turns.
During first phase (while S alive): Turn order: F (fast) attacks, hero attacks S, S attacks (slow) after hero. Since S is slow, it attacks after hero. On the turn S dies (turn t_S), F attacks first, then hero attacks S and kills it, then S would attack but is dead, so no. So S attacks on turns 1..(t_S-1). So attacks_S = t_S - 1. Attacks_F = during first phase: F attacks each turn (since it's alive) = t_S (since it's alive at start of each turn, and it's fast so it attacks on its death? but it's not dying yet). So attacks_F during first phase = t_S. Then after S dead, hero attacks F for t_F turns. During these turns, order: F attacks (fast) first, then hero attacks. F will attack each turn, including the turn it dies? Since F is fast, on the turn it dies, F attacks first, then hero kills it. So F attacks on all t_F turns of second phase. So total attacks_F = t_S + t_F. Total damage = w_S * (t_S - 1) + w_F * (t_S + t_F) = w_S t_S - w_S + w_F t_S + w_F t_F.
Our formula: C_S = t_S, C_F = t_S + t_F. Σ w_i C_i = w_S t_S + w_F (t_S + t_F) = w_S t_S + w_F t_S + w_F t_F. Subtract Σ_{slow} w_i = w_S (since S is slow) gives total damage = w_S t_S + w_F t_S + w_F t_F - w_S = same as above. Good.
Thus the formula holds.
Now what about enemies that are fast? They contribute no subtraction. So total damage = Σ w_i C_i - sum_{slow} w_i.
Thus minimal total damage is (min over permutations of Σ w_i C_i) - constant.
So we need to compute min Σ w_i C_i.
Classic solution: Sort by decreasing w_i / t_i. However, we must handle large n up to 40k, but that's fine. t_i and w_i can be up to large numbers (1e9). Compute t_i = ceil(Hi / dmg0i). dmg0i = A0 - Di (since we assume dmg0i > 0). So t_i = (Hi + dmg0i - 1) // dmg0i.
Now, we need to compute Σ w_i C_i efficiently after sorting. Let order be sorted indices. Then compute cumulative time sum cum = 0, total = 0. For each enemy in order: cum += t_i; total += w_i * cum.
But careful: w_i can be up to 1e9, t_i up to maybe 1e9? Actually Hi up to 1e9, dmg0i = A0 - Di, which could be as low as 1, so t_i up to 1e9. cum can be up to sum of t_i, which is up to n * 1e9 = 4e13, fits in 64-bit (around 4e13). w_i * cum could be up to 1e9 * 4e13 = 4e22, which exceeds 64-bit (max ~9.22e18). So we need 128-bit integer? Actually constraints: hi, ai, di, si up to 1e9, n up to 40000. sum of t_i could be up to 40000 * (1e9) = 4e13. w_i up to 1e9. So product up to 4e22. That's about 4e22, which needs > 64-bit. Use 128-bit (like _int128 in C++). In Python, big integers are fine. In Java, use BigInteger or long? 4e22 > 2^63-1 ~9.22e18, so need BigInteger. But maybe we can avoid overflow by early detection if total damage exceeds H0? H0 can be up to 1e9. Actually H0 is hero health, up to 1e9. So if total damage is >= H0, we output -1. But we need to compute the minimal total damage to compare with H0. However the minimal total damage could be huge (much larger than 1e9) but if it's >= H0, we just need to know that it's >= H0; we don't need exact value? But we need to output -1 if hero cannot survive. We don't need to output the damage if it's >= H0? Actually if minimal total damage >= H0, then hero cannot survive, output -1. So we only need to compute the exact total damage if it's < H0, because we need to output it. So we can compute the weighted sum with big integers, but we can also cap at H0 (or something) to avoid overflow. But careful: we also need to subtract constant sum{slow} w_i, which might be large but still comparable. Since H0 <= 1e9, if the total damage is < 1e9, it's within 64-bit. But the intermediate weighted sum could be large but if we cap at H0 maybe we can stop early. However we need to know if total damage < H0. So we can compute with arbitrary precision but we can also do computations in 128-bit or use Python's big ints. Since we are solving conceptually, but implementation will be in C++? The problem likely expects C++ solutions, but we can use __int128. Let's see: 4e22 fits within __int128 (max ~1e38). So we can use __int128 in C++. Or we can use double with caution? But better to use 128-bit integer.
Alternatively, we can note that we only need to compare total damage to H0, which is <= 1e9. So we can compute total damage as a 128-bit and then compare. Or we can compute using 64-bit with early exit if cum > H0? No, cum is time, not damage. Weighted sum could exceed H0 even if cum is moderate. But we could cap at H0 + sum_{slow} w_i? Actually if at any point the partial total damage (including constant) already exceeds H0, we could abort because we know answer is -1? But we need to know if any ordering yields less than H0. The ordering we compute is minimal, so if its total damage >= H0, then answer -1. So we can compute the minimal total damage exactly (with big integers) and then compare to H0.
Now, there is a nuance: The constant subtraction Σ_{slow} w_i is independent of order. But is it always subtracted? For each slow enemy, we subtract one w_i because they miss the attack on the turn they die. However, is it possible that a slow enemy might be killed in a turn where it doesn't get to attack because the hero kills it, but also maybe if hero kills it in the first attack? That's covered.
But wait: Are there any other cases where an enemy might not attack due to being killed by something else? Only hero can kill. So yes.
Edge case: What about enemies with w_i = 0? They contribute zero damage regardless, but the subtraction constant for slow enemies with w_i=0 is zero anyway. So no issue.
Edge case: What about enemies that have t_i = 0? Not possible since health >=1, damage >0, so t_i >=1.
Now, we have derived the minimal total damage formula based on ordering by w_i/t_i. But is this ordering always valid when considering the subtraction constant? The constant does not affect ordering.
However, we must also consider the effect of the hero's health: While we compute total damage, we must ensure that at no point during battle the hero's health reaches zero prematurely? Actually if total damage at the end is less than H0, then cumulative damage never exceeded H0, so hero survives. But is it possible that cumulative damage exceeds H0 before the end, even though final total is less than H0? That cannot happen because cumulative damage is non-decreasing, final total is the maximum. So if final total < H0, at all times it's <= final total < H0, so safe.
Thus, condition for survival is that minimal total damage < H0.
But is the minimal total damage computed as described always achievable? We must also consider the possibility that the hero might die before finishing all enemies even if final total damage is less than H0, because the hero could receive a large amount of damage in a single turn exceeding remaining health? But that's fine; if final total < H0, then at each step cumulative damage is <= final total < H0, so never reaches H0. The damage per turn is sum of w_i for alive enemies that attack that turn. Could be large, but as long as cumulative sum after that turn < H0, hero survives. So no issue.
Now, what about enemies with w_i = 0? They cause no damage, but they might cause delay, which increases damage from others. So they should be killed last (since they have zero weight, ratio zero). That matches Smith's rule: zero weight gives ratio 0, so they go last. However, what if some enemies have w_i=0 but t_i is also zero? Not possible.
Now, confirm with the examples:
Example 1:
Input:
2
10 3 1 2 (hero: h0=10, a0=3, d0=1, s0=2)
2 4 1 3 (enemy1: h=2, a=4, d=1, s=3)
2 2 1 1 (enemy2: h=2, a=2, d=1, s=1)
First, compute dmg0i = A0 - Di = 3-1=2 for both? enemy1 d=1, enemy2 d=1 => 2. So t_i = ceil(hi/2). enemy1 h=2 => t1=1. enemy2 h=2 => t2=1.
w_i = Ai - D0 = Ai - 1. enemy1 a=4 => w1=3. enemy2 a=2 => w2=1.
S_i: enemy1 s=3 > s0=2 => fast (no subtract). enemy2 s=1 < s0=2 => slow (subtract w2 later).
Now, compute ratios: w1/t1 = 3/1 = 3; w2/t2 = 1/1 = 1. So order: enemy1 first, then enemy2.
Compute Σ w_i C_i: cum=0; after enemy1: cum=1 => add w11=3; after enemy2: cum=2 => add w22=1*2=2; total=5.
Subtract Σ_{slow} w_i = w2=1 => total damage=5-1=4. Output 4. Matches example.
Now check other order: enemy2 first then enemy1. Σ w_i C_i: cum=1 => add w21=1; cum=2 => add w12=6; total=7; minus w2=1 => 6. So 6 > 4. So 4 is minimal. Hero health=10, 4<10, so survivable.
Example 2:
Input:
1
1 1 1 1 (hero: h0=1, a0=1, d0=1, s0=1)
10000 10000 10000 10000 (enemy: h=10000, a=10000, d=10000, s=10000)
Compute dmg0i = A0 - Di = 1 - 10000 = -9999 => max(0,?) = 0. So hero cannot damage enemy (since Di >= A0). So impossible -> output -1. Matches.
Thus our approach seems correct.
But wait: Example 1's hero health 10, total damage 4, which is less, so output 4. Good.
Now, is there any scenario where ordering by w_i/t_i is not optimal due to the subtraction constant? The constant is independent of order, so it doesn't affect ordering.
But there's another nuance: For slow enemies, the number of attacks is C_i - 1, so the contribution to total damage is w_i * (C_i - 1) = w_i * C_i - w_i. For fast enemies, contribution is w_i * C_i. So indeed it's Σ w_i C_i - Σ_{slow} w_i. So the objective is to minimize Σ w_i C_i. That's the classic scheduling objective.
Thus, the problem reduces to compute:
- For each enemy i, if A0 <= Di, impossible -> -1.
- Else compute t_i = ceil(Hi / (A0 - Di))
- Compute w_i = max(Ai - D0, 0) (though if Ai <= D0, then w_i = 0)
- Partition: fast if Si > S0, slow if Si < S0. But we only need the constant sum_slow = sum over slow w_i.
- Sort enemies