We need to maximize joy: given capacity C (max total weight), we can take integer amounts x (red) and y (blue) such that xWr + yWb <= C, maximizing Hrx + Hby.
Constraints up to 1e9, so we can't iterate over all possibilities. This is a classic unbounded knapsack with two items (two types). Since only two items, we can use enumeration over one variable, but the bounds are huge (up to 1e9). However we can use the fact that we can consider the item with larger weight? Usually for two items, you can iterate over one type up to something like sqrt(C) or up to max weight? Actually we need to find max linear combination.
We have maximize Hr x + Hb y subject to Wr x + Wb y <= C, x,y >=0 integers.
This is integer linear programming with two variables. We can solve by considering the ratio of joy per weight, but due to integer constraints, the optimum may be near boundary.
Standard approach: since there are only two items, we can iterate over the number of items of one type, say x from 0 to C/Wr, but C/Wr could be up to 1e9, too large. However we can limit the enumeration because if both weights are large? There is known trick: for two items, the optimal solution will use at most one of the items beyond a certain bound because if you have many of one type, you can replace some with the other type if it gives better ratio. More formally, the unbounded knapsack with two items can be solved in O(sqrt(C)) or O(max(Wr, Wb)). There is known solution: iterate over the type with larger weight? Let's derive.
We want max Hr x + Hb y, with constraint. This is like: y <= (C - Wr x)/Wb, integer floor.
So joy = Hr x + Hb * floor((C - Wr x)/Wb). Define f(x) = Hr x + Hb * floor((C - Wr x)/Wb) for x in [0, floor(C/Wr)].
We need max f(x). This function is piecewise linear decreasing in x? Not exactly because floor creates steps.
We can consider two cases: If one of the items has very high efficiency (joy per weight), the optimum will take as many as possible of that efficient item and possibly adjust.
Because numbers are large, we can think in terms of linear Diophantine optimization. We can consider the possibility of using the item with larger weight as the variable to iterate up to some limit, e.g., up to sqrt(C) or up to the other weight? Known technique: For unbounded knapsack with two weights, the number of one type needed in the optimal solution is at most max(Wb, Wr) (or something). Actually, consider that if you have a solution with many red candies, you could replace Wb red candies with Wr blue candies? Hmm.
We can think of the equation modulo something. Another approach: Since we can use any integer combination, the set of achievable weights is all integers of the form Wr x + Wb y. But we need to maximize linear function. This is a linear integer programming with two variables, basically we can find the best by considering convex hull of points (weight, joy). But we have a constraint on weight, so the maximum joy for a given capacity is the maximum of the linear function over the integer lattice inside a triangle. Since we have only two variables, the optimal solution is either at a vertex of the feasible region (real) rounded, or near the boundary. Actually, the linear objective is linear, so over the continuous relaxation, the optimum is at an extreme point: either x=0, or y=0, or the intersection of the line Wr x + Wb y = C (if coefficients positive). That intersection is (C/Wr,0), (0, C/Wb), or maybe a point where both positive if the slopes are such that interior point yields higher objective. For linear objective, the maximum over the continuous nonnegative reals under linear constraint is at a boundary point: either all of one type or all of the other, unless the objective gradient is exactly parallel to the constraint, in which case any point on the line gives same value. In that case, the optimal is the same for any combination. But the continuous optimum: Since Hr, Hb, Wr, Wb >0, the objective is linear and the feasible region is a triangle. The maximum occurs at one of the two intercepts, unless the slope of the objective equals the slope of the constraint, then the whole line is optimal. Let's compute: Continuous optimum: maximize Hr x + Hb y, subject to Wr x + Wb y <= C, x,y>=0. Since increasing x,y increases objective, optimum will have weight exactly C. So we consider line Wr x + Wb y = C. Then y = (C - Wr x)/Wb. Then joy = Hr x + Hb*(C - Wr x)/Wb = (HbC)/Wb + x(Hr - HbWr/Wb). This is linear in x. So if Hr/Wr > Hb/Wb, then coefficient positive, so joy increases with x, so maximum at x as large as possible -> x = C/Wr, y=0. If Hr/Wr < Hb/Wb, joy decreases with x, so max at x=0, y = C/Wb. If equal, any combination yields same joy = HrC/Wr = Hb*C/Wb. So continuous optimum is to take all of the type with higher joy per weight.
But integer constraints may alter this: if the optimal continuous is all red, then integer solution is floor(C/Wr) red candies, but maybe we can do better by substituting some reds for blues if that frees up some weight that can be used for more red? Wait if red is more efficient (higher joy/weight), then any substitution of red for blue (i.e., replace some red with some blue) would lower joy per weight, but might allow more total weight utilization because the weights are discrete: e.g., if C is not a multiple of Wr, there will be leftover weight that could be filled with blue candies. In continuous, we'd leave leftover weight unused? Actually we assume we can't exceed C but we can use less. The continuous optimum with inequality would still use as much weight as possible? Since objective positive, we want to use as much weight as possible. So if red is more efficient, we would take as many reds as possible (floor(C/Wr)), and then we have remaining weight R = C mod Wr. We could fill that remaining weight with some blues if they fit, but if we do that, we might need to remove some reds to make space for blues? Actually we can simply add blues to the leftover capacity without removing reds, because we already have weight = floor(C/Wr)*Wr <= C. Adding a blue would increase weight by Wb, potentially exceeding C. So we need to check if we can add a blue without exceeding capacity: we would need to remove some reds to free up weight. So the best integer solution might involve not taking the maximum possible number of reds, but rather taking a few less reds to allow more blues that collectively yield higher joy. Since red is more efficient per weight, substituting reds for blues typically reduces efficiency, but if the leftover weight can be better utilized by a combination that yields higher total joy than the leftover weight wasted, it might be beneficial. But note that we cannot waste weight: in the solution with only reds, we waste R = C - floor(C/Wr)*Wr grams. If we could replace some reds with blues to reduce waste, maybe we can increase joy. This is similar to a bounded knapsack where items have values Hr, Hb and weights Wr, Wb.
Standard solution: Since there are only two items, we can iterate over the number of one type from 0 to something like min(floor(C/Wr), Wb) or vice versa. Specifically, it's known that for two items, the optimal solution either uses fewer than sqrt(C) of one type or something? Let's recall known problems like "Maximum value with two types of items" (e.g., from Codeforces). One common trick: If both weights are large, say > sqrt(C), then the number of items is at most sqrt(C) because capacity is C, so each item weight >= sqrt(C) implies number of items <= sqrt(C). So we can iterate over x from 0 to sqrt(C) and y similarly? But if one weight is small, then we can't iterate over all x because floor(C/Wr) might be huge. However we can then iterate over the other type? We need a bound on the number of one type we need to consider.
Another known trick: For the unbounded knapsack with two items, the optimal solution can be found by enumerating the number of items of the heavier type (or the one with lower efficiency) up to the weight of the other item. More precisely, consider that if you take many items of one type, you can replace a group of them with some number of the other type to improve or adjust. There's a classic lemma: For two items with weights a and b, any integer larger than a*b can be represented as combination of a and b (if gcd(a,b)=1). But here we have values also.
Idea: The optimal solution will have at most one of the item types exceeding a certain bound, say Wb (or Wr). Specifically, we can assume that the number of red candies is less than Wb (or something). Because if x >= Wb, then we could replace Wb reds with Wr blues (since Wb * Wr? Let's think: The relation between weights: If we have x reds, and we consider replacing k reds with l blues such that the total weight remains same? That would require kWr = lWb, i.e., l = k*Wr / Wb. But if Wr and Wb are not multiples, we can't keep weight same. But there is a known bound: In integer linear programming with two variables, the optimal integer solution is either at a vertex of the feasible region (floor of continuous optimum) or near it. But the continuous optimum is at an extreme point if efficiencies differ. However, due to integer constraints, we might need to consider solutions where we take a number of the less efficient item to better fill capacity. Since the less efficient item has lower joy per weight, we don't want to take many of them, just enough to fill the leftover weight optimally. So we could try all possibilities for the number of less efficient items from 0 up to some bound, and then compute the number of the other type. The bound can be the weight of the more efficient item? Let's derive.
Assume Hr/Wr >= Hb/Wb, so red is at least as efficient as blue. Then in continuous optimum we take all reds. For integer, we might consider taking some blues instead of some reds if that allows us to use more total weight, maybe increasing total joy. The idea: Let we take y blues, then we can take at most floor((C - Wby)/Wr) reds. The total joy = Hby + Hrfloor((C - Wby)/Wr). This is a function of y. Since Hr/Wr >= Hb/Wb, we expect that increasing y (taking more blues) will generally decrease joy if we keep reds maxed. But because of floor, sometimes increasing y by 1 might cause floor to drop by 0 or 1 etc. Actually we can treat y as variable and we want to maximize f(y). Since Hr/Wr >= Hb/Wb, we suspect that the optimal y is small, maybe less than Wr? Let's try to bound.
Consider the difference if we replace some reds with blues. Suppose we have a solution with x reds and y blues. If we increase y by k, to maintain weight constraint, we may need to decrease x by at least floor(kWb / Wr) (or something). The net change in joy: Δ = kHb - floor(kWb / Wr)Hr + maybe additional adjustments due to leftover weight. For this change to be beneficial, Δ > 0. But since Hr/Wr >= Hb/Wb, we have HrWb >= HbWr? Actually from Hr/Wr >= Hb/Wb => HrWb >= HbWr. So Hr * Wb >= Hb * Wr. That means replacing Wr reds with Wb blues (i.e., reducing reds by Wr and adding Wb blues) yields net joy change = HbWb - HrWr <= 0. So swapping in bulk of that proportion is not beneficial. However smaller swaps may still be beneficial due to rounding? Possibly but unlikely.
But maybe the bound is: The optimal solution will have y < Wr (or x < Wb) when red is more efficient. Because if y >= Wr, then we could replace Wr blues with Wb reds? Wait we need to be careful.
Alternative approach: Use meet-in-the-middle? Not needed.
Given that Wr, Wb <= 1e9, C <= 1e9, the values are large but still within 64-bit. The typical solution in many editorial for similar problems (e.g., Codeforces 489B, or maybe 553B? I recall problem "Om Nom and Candies" from Codeforces? Actually there is a Codeforces problem "C. Om Nom and Candies"? Wait I recall a Codeforces Round problem about two bags of candies? Possibly "C. Two Bags of Candies"? Not sure.
Let's search memory: There is Codeforces problem 436C - Dungeons and Candies? No.
But I've seen a problem: "Om Nom and Candies" from Codeforces Round #180? Might be an A2OJ? Actually I think it's Codeforces problem 526-B? Not sure.
However, standard solution for two-item unbounded knapsack with large constraints:
- If min(Wr, Wb) is small (e.g., <= sqrt(C)), we can iterate over the number of the larger weight item up to something? Actually if one weight is small, say W_small, then the number of that item can be up to C/W_small which could be large. But we can instead iterate over the number of the larger weight item because its count is limited: if W_large > sqrt(C), then its count <= sqrt(C). But if both are small (<= sqrt(C)), then both counts can be large, but we can use a different method: then we can treat it as a coin change with two coins, and we can use enumeration over the remainder modulo something.
A known approach: The optimal solution will have either x < Wb or y < Wr. Why? Suppose we have an optimal solution with x >= Wb and y >= 0. Consider replacing Wb reds with Wr blues? Actually we need to find a transformation that yields a solution with less of one type without decreasing joy, or we can show that there exists an optimal solution with either x < Wb or y < Wr. This is a typical lemma for unbounded knapsack with two items: because the equation Wrx + Wby = total weight (or <=) and you can adjust using the fact that if x >= Wb, you can reduce x by Wb and increase y by Wr (since WbWr = WrWb) and the weight remains the same. The joy changes from Hr*(x) + Hby to Hr(x - Wb) + Hb*(y + Wr) = (Hr x + Hb y) + (HbWr - HrWb). So if HbWr - HrWb > 0, this change improves joy; if it's negative, the opposite change (reducing y by Wr and increasing x by Wb) improves joy. So in an optimal solution, we can assume that such transformations do not improve joy, implying that either x < Wb or y < Wr (depending on sign). Actually, more formally:
Let D = HrWb - HbWr. If D > 0, then red is more efficient per weight? Check: Hr/Wr > Hb/Wb implies HrWb > HbWr, so D > 0. In that case, replacing Wb reds with Wr blues decreases joy (since net change = HbWr - HrWb = -D < 0). So that transformation is not beneficial. But the opposite: replacing Wr blues with Wb reds increases joy by D > 0. So if we have a solution with y >= Wr, we could replace Wr blues with Wb reds to improve joy. Therefore in an optimal solution with D>0, we must have y < Wr (since otherwise we could improve). Similarly, if D < 0, we must have x < Wb. If D = 0, any combination on the line yields same joy, so we can take either.
Thus we have a bound: For optimal solution, if red is more efficient (D>0), then the number of blue candies y is at most Wr - 1. Similarly, if blue is more efficient (D<0), then x is at most Wb - 1. If D=0, we can simply compute Hr * floor(C/Wr) (or Hb * floor(C/Wb))? Actually if Hr/Wr = Hb/Wb, then joy is proportional to weight: joy = (Hr/Wr)weight. So maximum joy is achieved by using as much weight as possible, i.e., weight = floor(C/Wr)Wr or floor(C/Wb)Wb? Actually any combination gives joy proportional to weight, but we may not be able to achieve exactly C weight, so the maximum joy is max_{x,y} (Hr x + Hb y) subject to weight <= C. Since joy/weight is constant, we want to maximize weight used. The maximum possible weight we can achieve with these two items is the largest integer <= C that can be expressed as Wrx + Wby. Since we have unlimited items, the Frobenius coin problem: the set of representable integers is all multiples of gcd(Wr, Wb) beyond the Frobenius number. But we can't assume we can achieve any weight; we can only achieve multiples of g = gcd(Wr, Wb). But we want maximum weight <= C that is a multiple of g and also can be expressed. However, for two coins with unlimited supply, the largest non-representable number is WrWb - Wr - Wb (if coprime). But since C can be up to 1e9 and weights up to 1e9, the Frobenius number may be huge (up to ~1e18). So we cannot simply take floor(C/g)g? Actually not all multiples of g are representable if g=1? Wait if gcd=1, all sufficiently large integers are representable. But we might have C smaller than the Frobenius number. So we need to compute the maximum achievable weight <= C. However, the problem asks for maximum joy, and since joy is proportional to weight, it's equivalent to maximizing weight used. But with D=0, it's essentially the same as the classic coin problem: maximize weight not exceeding C with denominations Wr, Wb. That could be solved by checking if C is large enough relative to Frobenius number, but we can also use enumeration over one variable up to Wb (or Wr). Indeed, the bound we just derived (x < Wb or y < Wr) applies also when D=0? Actually if D=0, the transformation yields no change in joy, so there are many optimal solutions. But we can still limit enumeration: we can find the maximum weight achievable by trying all y from 0 to Wr-1 (or x from 0 to Wb-1) and compute max weight = max_{0 <= y < Wr} (Wby + Wrfloor((C - Wby)/Wr) ) provided C - Wby >=0. Since Wr and Wb might be up to 1e9, but Wr could be up to 1e9, so iterating up to 1e9 is not feasible. But note that when D=0, the bound might not be directly applicable because the transformation does not change joy, but we still can limit the search to y < Wr because any solution with y >= Wr can be reduced to one with smaller y without changing joy? Actually if D=0, then replacing Wb reds with Wr blues (or vice versa) doesn't change joy, but does it change weight? The replacement keeps weight exactly the same: remove Wb reds (weight WbWr) and add Wr blues (weight WrWb) so weight unchanged. So any solution can be transformed to one with y < Wr by repeatedly replacing Wr blues with Wb reds (or the other way) until y < Wr. Since joy doesn't change, the transformed solution is also optimal. So we can still assume y < Wr (or x < Wb) for some optimal solution. So the bound holds for any sign of D, but with different justification: For D>0, we must have y<Wr because otherwise we can improve; for D<0, we must have x<Wb; for D=0, we can also enforce y<Wr without loss of optimality because we can transform any optimal solution to one with y<Wr by reducing y by multiples of Wr and increasing x accordingly, without changing joy. Actually careful: If D=0, then HrWb = Hbx + Wb(x+Wb) + Wb*(y - Wr) = WrWb + WbWr = Wry. So weight unchanged. Joy: Hry' = Hr*(x+Wb) + Hb*(y - Wr) = HrWb + HbWr = Hry + (HrWr) = Hry (since D=0). So indeed we can reduce y by Wr while increasing x by Wb, keeping joy and weight same. So we can repeatedly do this until y < Wr. So there exists an optimal solution (with maximum weight) that also has y < Wr? But careful: we want maximum joy, which equals constant times weight. So we want to maximize weight. If we have a solution achieving weight W, we can transform it to a solution with y<Wr achieving same weight. So the set of achievable weights with y<Wr covers all achievable weights. Therefore, to find the maximum weight <= C, we can just consider y from 0 to Wr-1, compute x = floor((C - Wby >=0} (Wbfloor((C - Wby + Wry)/Wr). This is the maximum weight with exactly that number of blue candies? But the optimal overall weight may be achieved with a y that is not < Wr? But we argued we can transform any optimal weight solution to one with y<Wr, so that transformed solution will have some y' in [0, Wr-1] and same weight. And that weight will be exactly Wbx' for some x' = floor((C - Wby')/Wr)? Possibly not, because we could have x' larger if there is leftover capacity; but since weight W is fixed and we are at that weight, we might be able to add more reds if there is space? Actually if we have a solution (x', y') with weight W <= C, and we can add more reds (increase x') without exceeding C, then we could increase weight, contradicting optimality of W (if W is maximum weight). So for maximum weight solution, given y', we would have x' as large as possible under constraint, i.e., x' = floor((C - Wby')/Wr) for its y' (or could have smaller x' but then we could add reds to increase weight). So it's safe to consider for each y' the maximal x. Therefore, the maximum weight can be found by iterating y from 0 to Wr-1.
Thus, in all cases, we have a bound: either we need to iterate over y up to Wr-1 (if red is more efficient or equal) or over x up to Wb-1 (if blue is more efficient). But Wr and Wb can be up to 1e9, so iterating up to 1e9 is not feasible.
So we need a tighter bound when weights are large. However, note that the bound we derived (y < Wr) came from the transformation that if y >= Wr, we could replace Wr blues with Wb reds (or vice versa) to improve joy (or keep same for D=0). But if Wr is huge (like 1e9), then y < Wr is not a useful bound. But we need to consider that if one weight is huge, the number of items of that type we can take is limited by capacity anyway. Actually, if Wr is huge (say > sqrt(C)), then the number of reds we can take is at most floor(C/Wr) which is <= sqrt(C) if Wr > sqrt(C). So in that case, we can directly iterate over x from 0 to floor(C/Wr) (which is small). Similarly, if Wb is huge. So the idea: choose the item to iterate over such that the number of iterations is manageable. Specifically, we can iterate over the type with larger weight, because its count is bounded by C / (large weight) which might be small if the weight is large. But if both weights are small (e.g., both 1), then the count can be up to C (1e9) and we cannot iterate. But then we can use the bound based on the other item's weight? Actually if both weights are small (≤ sqrt(C)), then both counts could be large, but we can then iterate over one type up to the weight of the other type, which is also small because the other weight is ≤ sqrt(C). Because if both are ≤ sqrt(C), then Wr and Wb are ≤ sqrt(C). So iterating up to max(Wr, Wb) ≤ sqrt(C) is feasible. So the combination of these two strategies gives O(sqrt(C)) complexity.
Specifically, algorithm:
Let's denote we will try both possibilities: iterate over the type with smaller weight? Let's design:
Option 1: Iterate over the number of reds (x) from 0 to min(C/Wr, limit) where limit is something like Wb? Actually from the transformation: if D > 0, then optimal y < Wr. But if Wr is huge, we can't iterate y up to Wr. But we could instead iterate over x up to Wb-1 if we invert the logic? Because if D>0 (red efficient), then we must have y < Wr. That doesn't bound x. But if Wr is huge, maybe x is bounded by capacity? But x could be up to C/Wr which might be small if Wr is huge. But if Wr is huge, then the bound y < Wr is not helpful but we can just iterate over x because floor(C/Wr) is small. Similarly, if Wr is small, then y < Wr means we can iterate over y (since Wr is small). So we can combine: if Wr is relatively small, iterate over y (since y < Wr is small); if Wr is large, we can iterate over x because the count of reds is small. But we need to know which is the efficient item? Actually the bound we derived depends on which item is more efficient. So we need to consider two cases.
Let's define:
- If Hr * Wb > Hb * Wr: red more efficient (D>0). Then optimal solution has y < Wr.
- If Hr * Wb < Hb * Wr: blue more efficient (D<0). Then optimal solution has x < Wb.
- If equal: either.
Now, we can decide to iterate over the variable that is bounded by the other weight, but that bound might be large. However, we can also note that we can choose to iterate over the type with the larger weight's count if that is smaller, or over the bounded variable if that bound is smaller.
A common approach seen in editorial: Because 1e9 is large, but sqrt(1e9) = 31623, which is fine. So we can set a threshold, say TH = sqrt(C) (or maybe 100000). Then if Wr > TH, then the number of reds we can take is at most C/Wr ≤ C/TH = sqrt(C), so we can iterate over x from 0 to floor(C/Wr). Similarly, if Wb > TH, iterate over y. If both Wr and Wb ≤ TH, then both are ≤ sqrt(C), so we can iterate over one of them up to the other weight (which is also ≤ sqrt(C)), using the bound from efficiency.
More precisely:
Method:
- Initialize ans = 0.
- For x from 0 to min(C/Wr, TH) maybe? But we need to guarantee we cover the optimum.
Alternative approach: We can decide to iterate over the item with larger weight. Because if the larger weight is > sqrt(C), then its count <= sqrt(C). If the larger weight is <= sqrt(C), then both weights are <= sqrt(C), and we can use the bound from efficiency to iterate over the less efficient item? Let's think.
But we must also consider the efficiency bound. Actually, I recall a known solution for the problem "Two Types of Items" (maybe from Codeforces 449A or similar). The solution: Let TH = 1000000 (since C up to 1e9, sqrt 1e9 = 31623). Then if Wr >= TH, iterate over x from 0 to C / Wr (which is <= C/TH <= 1e9/1e4 = 1e5? Actually 1e9/1000000=1000, if TH=1e6; but sqrt 1e9 ~31623, if we set TH=40000 then C/TH <= 25000. So we can pick TH = 100000? Might be okay but we need to be within time limit. Usually O(sqrt(C)) is fine.
But there is a more elegant method: iterate over the number of red candies from 0 to min(Wb, C/Wr) maybe? Actually the bound from transformation gave y < Wr (if red efficient) but also if we consider swapping we could bound x by Wb if blue efficient. That's symmetrical. So we have: either y < Wr or x < Wb. Since we don't know which is efficient, we can consider both: If we iterate over x from 0 to min(C/Wr, Wb) and also over y from 0 to min(C/Wb, Wr), then we are guaranteed to cover an optimal solution? Let's check: If D>0, then optimal has y < Wr. But we are iterating y up to min(C/Wb, Wr). Since y < Wr, and y cannot exceed C/Wb, iterating y up to min(C/Wb, Wr) will include the optimal y. So we can just iterate over y from 0 to min(C/Wb, Wr). That's at most Wr if Wr is small, but if Wr is large, min(C/Wb, Wr) might still be large? Because if Wr is large, say 1e9, then min(C/Wb, Wr) could be C/Wb which might also be large if Wb is small. For example, if Wr=1e9, Wb=1, then red efficient? Let's compute: Hr/Wr > Hb/Wb? Not necessarily, but we are in the case D>0, so red efficient. Then optimal y < Wr, which is 1e9, but we would iterate y up to min(C/1, 1e9) = C which could be 1e9, too large. So this direct iteration fails. However, in that scenario, red is efficient but its weight is huge (1e9), so the number of reds we can take is at most C/1e9 which is at most 1. Meanwhile, blue weight is tiny (1). In this case, maybe the optimal solution still has small y? Not necessarily; if red is efficient but very heavy, we might take zero reds and many blues because maybe reds are too heavy to fit many? But if red is efficient, we want to take as many reds as possible, but each red consumes large weight. Possibly the optimal is to take at most floor(C/Wr) reds (maybe 0 or 1) and then fill the rest with blues. That yields some joy. But could there be a solution with many blues that beats that? Since red is efficient, per weight it's better, so using reds is beneficial. But if we cannot take many reds because of weight, maybe the best is to take 0 reds and many blues? But then the per weight efficiency of blues might be lower, so total joy might be lower than taking 1 red and then many blues? Need to check.
But we can think: If red is efficient but heavy, the optimal might involve taking at most one red (or few). So we could iterate over x (red count) because it's small. So we need a strategy that covers both cases.
The typical solution from editorial (I think it's from Codeforces Round #360 Div2 C "NP-Hard Problem"? No) I'll derive a robust method.
Idea: Because there are only two items, we can attempt to enumerate the item with smaller weight, if its count can be large, then the other item's count is bounded by the weight of the smaller? Let's reason.
Case 1: If Wr and Wb are both ≤ sqrt(C) (or maybe ≤ 1e5?), we can directly iterate over one variable up to C / min(Wr, Wb) which might be huge, so not good. But we can use the transformation bound: For optimal solution, if Hr/Wr > Hb/Wb, then y < Wr. Since Wr ≤ sqrt(C), then iterating y up to Wr-1 is feasible. Similarly, if Hb/Wb > Hr/Wr, then x < Wb, and Wb ≤ sqrt(C), so iterating x up to Wb-1 is feasible. If equal, we can also iterate y up to Wr-1 (since Wr ≤ sqrt(C)). So this covers case both weights small.
Case 2: If one of the weights is > sqrt(C), say Wr > sqrt(C). Then the number of reds we can take is at most floor(C/Wr) which is < sqrt(C). So we can iterate over x from 0 to floor(C/Wr). That's at most sqrt(C) iterations. Then we can compute y = floor((C - Wr*x)/Wb) and update ans. This works regardless of efficiency because we are iterating over all possible numbers of the heavy item. Since x is bounded by sqrt(C), we are fine. But wait, what if both weights are > sqrt(C)? Then both counts are <= sqrt(C), so we could iterate over either. So overall, we can always ensure at most sqrt(C) iterations by choosing the item with larger weight to iterate over? Let's test: Suppose Wr = 100000, Wb = 100001, C=1e9. sqrt(C)≈31623. Both weights > sqrt(C)? Actually 100000 > 31623, yes. Then floor(C/Wr)=10000, floor(C/Wb)=9999. So both counts are about 1e4, which is less than 31623? 10000 < 31623, so we could iterate over reds up to 10000, which is fine. So indeed if the weight is > sqrt(C), its count <= C/weight < sqrt(C). So we can always iterate over the heavier item. But what if the heavier item is not the efficient one? That doesn't matter because we just need to check all possibilities of that item's count; the other item's count will be determined as max possible for that x. That will yield the optimum? Not necessarily, because the optimum might involve a number of the heavy item that is not the one we try? But we are iterating over all possible numbers of that heavy item from 0 to its maximum, so we cover all combinations. That is exhaustive: we consider all x from 0 to max_x, compute best y for that x, and take max. Since max_x is <= sqrt(C), it's feasible. So why not always iterate over the heavier item? Because if both weights are small (<= sqrt(C)), then max_x = floor(C/Wr) could be as large as C/min(Wr,Wb) which could be huge (e.g., both weights=1 => max_x = 1e9). So iterating over the heavier item (which in that case both are small, the heavier might be 1 as well? Actually if both are small, the heavier could be e.g., Wr=1000, Wb=2000, C=1e9, then heavier=2000, max_x = floor(C/2000)=500000, which is 5e5 > sqrt(C)=31623. So 5e5 might be acceptable? 5e5 is maybe okay? But time limit might be strict; typical CF problems require O(sqrt(C)) or about 1e6 operations. 5e5 is okay? Possibly, but in worst case Wr=1, Wb=2? Heavier=2, max_x = 5e8, too many. So we cannot just iterate over heavier if both are small.
Thus we need a hybrid: if the heavier weight > sqrt(C), iterate over it (since count small). If both weights ≤ sqrt(C), then we must use the bound from efficiency to limit the variable we iterate over. Because both weights are small, but we can use the lemma: if red is efficient, y < Wr. Since Wr ≤ sqrt(C), iterating over y up to Wr is at most sqrt(C). Or if blue efficient, iterate over x up to Wb ≤ sqrt(C). So in either case we can iterate up to sqrt(C). That gives O(sqrt(C)) overall.
But need to consider also the case where one weight is small (<= sqrt(C)) and the other is large (> sqrt(C)). Then we can simply iterate over the heavy item because its count is <= sqrt(C). So that's fine.
Thus the algorithm:
Let sqrtC = floor(sqrt(C)) maybe plus a bit. We'll compute threshold = 100000? Actually we can compute sqrtC = sqrt(C) (using integer sqrt). We'll use a constant like 100000 (since 1e9 sqrt = 31623, but to be safe we can use 100000). But we need to be precise: if max(Wr, Wb) > sqrtC, iterate over the heavier one. If both <= sqrtC, then we apply the lemma based on efficiency to decide which variable to iterate over (the less efficient one? Actually the lemma says: if Hr * Wb > Hb * Wr (red more efficient), then optimal y < Wr, so iterate over y from 0 to min(C/Wb, Wr-1) (since y cannot exceed C/Wb). Since Wr <= sqrtC, this is at most sqrtC. Similarly if Hb more efficient, iterate over x from 0 to min(C/Wr, Wb-1). If equal, we can do either (say iterate over y up to Wr-1). That's O(sqrtC).
Now, need to confirm that the lemma indeed holds for all cases, including when we might have weight not fully used? The lemma derivation assumed we could replace Wr blues with Wb reds (or vice versa) without changing weight, and that if the replacement improves joy, we would do it. But that transformation requires that we have at least Wr blues to replace. In an optimal solution, if D>0 and y >= Wr, we can reduce y by Wr and increase x by Wb, resulting in increased joy (since D>0). So any optimal solution must have y < Wr. This holds regardless of whether weight is fully used? Actually, if the solution is optimal, it may have total weight less than C, because maybe we can't add any more items without exceeding C. But the transformation we described changes (x,y) to (x+Wb, y-Wr). Does this keep weight the same? Yes, because weight change = WrWb - WbWr = 0. So the new solution also respects the weight constraint (since weight same). So if y >= Wr, the new solution is feasible and yields higher joy, contradicting optimality. So indeed y < Wr in any optimal solution. This is valid even if we are not at full capacity. Good.
Thus, the lemma is solid.
Now, the algorithm:
Read C, Hr, Hb, Wr, Wb.
Let ans = 0.
Compute sqrtC = sqrt(C) (maybe using integer sqrt). I'll use sqrtC = int(sqrt(C)) + 1 to be safe, but we'll use a threshold = 100000 (which is > sqrt(1e9) ~ 31623). However to be precise, we can compute the actual sqrt and set threshold = sqrt(C). Actually we need to decide whether to iterate over heavy or use lemma. We'll compute if max(Wr, Wb) > limit, where limit = sqrt(C) (maybe plus 1). Because if max weight > sqrtC, then the count of that item is at most C/(max weight) <= C/sqrtC = sqrtC. So we can iterate over that item.
But there is a nuance: Suppose Wr = 50000, Wb = 60000, C = 1e9, sqrtC ~ 31623. Here both weights > sqrtC? Actually 50000 > 31623, 60000 > 31623, so both > sqrtC. Then max(Wr,Wb)=60000 > sqrtC. So we can iterate over the heavier (60000) with count up to floor(C/60000) ≈ 16666, which is < sqrtC? 16666 < 31623, ok. So iterating over heavier works. That covers all.
Now, suppose Wr = 30000, Wb = 40000, sqrtC=31623. Then Wr=30000 <= sqrtC? Actually 30000 < 31623, so it's less or equal? 30000 <= sqrtC? Yes, because sqrtC=31623, so 30000 ≤ sqrtC, but 40000 > sqrtC. So max = 40000 > sqrtC. Then we can iterate over the heavier (40000) with count up to 25000, which is < 31623? 25000 < 31623, okay. So iterate over heavier works. So condition "max > sqrtC" covers many cases.
Only case left: both ≤ sqrtC. Then we must use lemma.
Now, we also need to consider that if both ≤ sqrtC, then we might also have the possibility that iterating over one variable up to its max count could be large because C/min(W) could be large. So we rely on lemma.
Implementation:
Compute limit = sqrt(C) (use integer sqrt function). Usually we can do (long long) sqrt(C) and then while (limit+1)*(limit+1) <= C increment.
Alternatively, we can set limit = 1e5 (since sqrt(1e9) ~ 31623, 1e5 is safe). But we need to be exact? Not necessary, as long as we guarantee that if max(Wr,Wb) > limit, then the count of that item is at most C/limit <= something manageable, but we might set limit = 40000 to be safe. However if we set limit too high (like 100000), then for both weights ≤ 100000, we might fall into lemma branch, but then the lemma bound might be up to 100000 which is okay. But what if one weight is 90000 and the other is 2, and C=1e9? Here max weight=90000 ≤ 100000? Actually 90000 ≤ 100000, so both ≤ limit, we go to lemma branch. But is that safe? The lemma says if red efficient? Suppose red is efficient? Let's see. In lemma branch we will iterate over either y up to Wr-1 or x up to Wb-1, depending on efficiency. Wr could be 90000, that's up to 90000 iterations, which is okay (9e4). If we instead had set limit = sqrt(C)=31623, then max weight=90000 > 31623, we would have used the heavy iteration branch, which would iterate over the heavier (say if Wr=90000) with count up to C/Wr ≈ 11111, which is smaller (11111). So both are acceptable. So it's fine.
But we need to be careful about time: iterating up to 1e5 is fine. Actually O(1e5) is trivial. But what if both weights are exactly 1e5? Then lemma branch might iterate up to 1e5. That's okay. So we can simply set a threshold TH = 100000 (or 50000) and use heavy iteration if max(Wr,Wb) > TH; else use lemma. But we must ensure that the heavy iteration's loop count is ≤ C / (max(Wr,Wb)) which might be > TH? Actually if max(Wr,Wb) > TH, then C/(max) ≤ C/TH. For TH = 100000, C=1e9 gives at most 10000. So fine. But if C=1e9 and max weight = 200000, then count = 5000. Good.
But if C=1e9 and max weight = 100001, count = floor(1e9/100001) ≈ 9999. So < TH. So heavy iteration is at most 1e4.
Now, if both weights ≤ TH, we go to lemma branch which may iterate up to TH (since bound is min(Wr, Wb?) Actually lemma says if red efficient, iterate y up to min(C/Wb, Wr-1). Since Wr ≤ TH, that's ≤ TH. If blue efficient, iterate x up to min(C/Wr, Wb-1) ≤ TH. So at most TH iterations. So total operations ≤ TH.
Thus picking TH = 100000 is safe and yields at most 1e5 operations, which is fast.
But we need to be absolutely sure that when both weights ≤ TH, the lemma's bound (y < Wr or x < Wb) guarantees the optimal is found by iterating over that variable? Yes, as argued: If red efficient (HrWb > HbWr), then any optimal solution has y < Wr. So iterating y from 0 to min(C/Wb, Wr-1) and for each compute x = floor((C - Wb*y)/Wr), we evaluate joy and take max. That covers all optimal solutions because for each possible y in that range, the best x for that y is taken. Since the optimal has y in that range, we will capture it.
Similarly for blue efficient.
If equal, we can treat as red efficient or blue efficient, and iterate over y up to Wr-1 (since we can transform to have y < Wr). Actually if equal, both transformations keep joy same, so there exists an optimal solution with y < Wr (and also one with x < Wb). So we can iterate y up to Wr-1. So we can just follow the same as red efficient? But careful: if equal, the condition HrWb > HbWr is false; it's equality. So we need to handle separately. We can just use the same bound: if HrWb >= HbWr? But if equal, we can still use the bound that y < Wr because we can transform. So we can arbitrarily decide to iterate over y when HrWb >= HbWr? That would include equality as well. But need to check: if equality, the transformation from y >= Wr to lower y does not change joy, so there exists an optimal with y < Wr, but does it guarantee that the maximum joy is achieved by some y in that range? Yes, because given any optimal solution, we can transform it to one with y < Wr without decreasing joy, so there is an optimal solution with y < Wr. Therefore iterating over y in [0, min(C/Wb, Wr-1)] will include that optimal solution, and since for each y we take maximal x, we will get at least that joy. However, we need to be careful: the transformation might change x, but we are taking maximal x for that y; that might yield a different solution with same weight? Actually the transformed solution (x', y') might have y' < Wr, and it has the same weight as original? The transformation we used (replace Wr blues with Wb reds) keeps weight exactly the same, so weight unchanged. The joy is same because D=0. So the transformed solution has same weight and joy. However, when we iterate over y', we compute x' = floor((C - Wby')/Wr). But the transformed solution's x' may not equal that floor? It must be ≤ floor((C - Wby')/Wr) because weight cannot exceed C. Since its weight is exactly the original weight W ≤ C, we have x' ≤ floor((C - Wb*y')/Wr). Actually if weight W < C, then x' could be less than the maximum possible for that y'. But the joy is proportional to weight, so if we can increase x' to the maximum (i.e., add more reds) we would increase weight and thus joy (since joy/weight constant). So the transformed solution may not be weight-maximal for that y'. But we can then add more reds if capacity allows, increasing joy. So the true maximum joy for that y' would be with maximum x. So the maximum over y of f(y) will be at least as high as the transformed solution's joy, possibly higher. So iterating over y and taking max x yields the global optimum. So it's safe.
Thus we can unify: if HrWb >= HbWr, then we consider red at least as efficient? But careful: if HrWb > HbWr, red more efficient; if equal, both equally efficient. In both cases, we can bound y < Wr? For >, it's strict; for =, we can also bound y < Wr because we can transform. So yes, we can say if HrWb >= HbWr, then optimal y < Wr. But is it always true that for equality we can guarantee y < Wr? Let's check: we have solution (x,y). If y >= Wr, we can do (x+Wb, y-Wr) which yields same weight and joy. This can be repeated until y < Wr. So yes. So we can say: if HrWb >= HbWr, there exists an optimal solution with y < Wr. So we can iterate over y.
Similarly, if HrWb <= HbWr, we could iterate over x < Wb. But if equality both hold, we can choose either.
Thus, our algorithm:
Set TH = 100000 (or maybe 1000000? Let's see, 1e5 is fine).
If max(Wr, Wb) > TH:
// heavy item iteration
if (Wr > TH) // or we can iterate over the heavier one specifically
for x = 0 to C/Wr:
y = (C - xWr) / Wb; // integer division
ans = max(ans, xHr + yHb);
else // Wb > TH
for y = 0 to C/Wb:
x = (C - yWb) / Wr;
ans = max(ans, xHr + yHb);
Else: // both <= TH
if (1LLHrWb >= 1LLHbWr) { // red more efficient or equal => iterate over y
for y = 0 to min(C/Wb, Wr-1):
x = (C - yWb) / Wr;
ans = max(ans, xHr + yHb);
} else { // blue more efficient => iterate over x
for x = 0 to min(C/Wr, Wb-1):
y = (C - xWr) / Wb;
ans = max(ans, xHr + yHb);
}
But wait: In the case both <= TH, we are using bound y < Wr or x < Wb. Since Wr,Wb <= TH, the loop size is at most TH. However, we also need to consider that if C/Wb is smaller than Wr, then the loop goes up to C/Wb, which might be less than Wr but still <= TH (since Wr <= TH, but C/Wb could be larger than TH? Actually if Wb is small, say Wb=1, then C/Wb = C = 1e9, which is > TH, but we are in the branch both <= TH, but Wb=1 ≤ TH, Wr could also be ≤ TH. In that case, we would be iterating y up to min(C/Wb, Wr-1). Since Wr-1 ≤ TH-1, that min is at most TH-1. So we are safe because we cap at Wr-1. So loop size is limited by Wr (or Wb) not by C/Wb. Good.
Now, check the heavy branch: Suppose Wr > TH, we loop x from 0 to floor(C/Wr). Since C/Wr <= C/TH <= 1e9/1e5 = 10000, that's fine. However, we need to ensure that we cover all possibilities. But is it sufficient to only iterate over the heavy item? Yes, because for each possible number of reds (if Wr heavy), we compute the maximum blues that fit, and that yields a candidate solution. Since we consider all x from 0 to max_x, we are covering all combinations (the y is determined optimally for each x). So that's exhaustive. So this branch is correct.
Potential issue: When both weights <= TH, we use the lemma branch. But what if the optimal solution involves a value of y that is >= Wr? The lemma says there exists an optimal solution with y < Wr if HrWb >= HbWr. So we are covering that range. Good.
Now, what about the case where max(Wr, Wb) > TH but the heavy item is not the one we iterate over? Our code above chooses to iterate over the item that is > TH (the heavy one). That is correct because if both > TH? Then we could pick either, but we need to ensure we pick the one that is heavier? Actually if both > TH, we could pick either because both have counts ≤ C/weight ≤ C/TH. But we should pick one. We can just check: if Wr > TH: iterate over reds; else if Wb > TH: iterate over blues. But if both > TH, both conditions true, but we will go into first if (Wr > TH). That's fine.
Now, we should also consider the possibility that TH might be set too low? If we set TH=100000, and C=1e9, then heavy item > 100000 yields count <= 1e4. That's fine. But what if C is as low as 1? Then sqrt(C)=1, but TH=100000 is huge compared to C, but then the branch classification: if max(Wr,Wb) > TH, it's false (since weights are at least 1 and <=1e9, but if C small, both weights could be > TH? Actually if C=1, both weights might be > 100000? But they could be up to 1e9. For example, C=1, Wr=1000000, Wb=2000000. Then max > TH, so we go to heavy branch. But then we iterate x from 0 to C/Wr = 0 (since C/Wr=0). That's only one iteration (x=0). Then we compute y = floor(C/Wb)=0. So ans=0. That might be correct? But maybe we can take a candy if its weight <= C? Actually if Wr=1000000 > C=1, we cannot take any candy because each candy weighs > C. So ans=0 correct. So fine.
But if both weights <= TH, but C is small, then loop size is up to TH which could be much larger than needed, but still acceptable since TH=100000, loop up to 100000 is fine even for small C. So all good.
Now we need to be careful about overflow: Hr, Hb, Wr, Wb up to 1e9, and x,y up to maybe 1e9? But in loops we only compute up to 1e5 iterations, but still we need to compute x*Hr etc. Use 64-bit (long long).
Edge Cases:
- Both weights equal? If Wr == Wb, then the problem reduces to take the candy with higher joy per candy (since weight same). Actually if weights equal, then it's optimal to take as many as possible of the candy with higher joy. But our algorithm: if Wr==Wb, then heavy branch? If both <= TH, then we check efficiency. If Hr>=Hb? Then HrWb >= HbWr becomes HrWr >= HbWr => Hr>=Hb, so true. Then we iterate y up to Wr-1. That's okay. But maybe we can simply take all reds if Hr>Hb. But the iteration will find that because for y=0, x = C/Wr, joy = Hr*x. For any y>0, it will be worse. So ans will be correct.
Now, we should test with sample: C=10, Hr=3, Hb=5, Wr=2, Wb=3.
Compute TH=100000. max(Wr,Wb)=3 ≤ TH, so both ≤ TH branch.
Check HrWb = 33=9, HbWr =52=10 => 9<10, so HrWb < HbWr, blue more efficient? Actually Hb/Wb =5/3 ≈1.666, Hr/Wr=3/2=1.5, so blue more efficient. So we go to else: iterate over x from 0 to min(C/Wr, Wb-1). C/Wr=5, Wb-1=2 => min=2. So x in 0..2.
- x=0: y= floor(10/3)=3 => joy=0+15=15.
- x=1: y= floor((10-2)/3)= floor(8/3)=2 => joy=3+10=13.
- x=2: y= floor((10-4)/3)= floor(6/3)=2 => joy=6+10=16.
Max=16. Good.
Now test other scenarios.
Consider C=10, Hr=5, Hb=3, Wr=2, Wb=3 (red more efficient). Then HrWb=15, HbWr=6, so red efficient. Then iterate over y from 0 to min(C/Wb, Wr-1)= min(3,1)=1.
- y=0: x= floor(10/2)=5 => joy=25.
- y=1: x= floor((10-3)/2)= floor(7/2)=3 => joy=5+3=8? Actually 5*3? Wait Hr=5, Hb=3: x=3 => 15, y=1 => 3, total=18. So max=25. So optimal to take only reds.
Now test case where both weights large: C=1000000000, Hr=2, Hb=3, Wr=500000000, Wb=600000000. TH=100000. max =600M > TH, so heavy branch. Wr=500M > TH? Actually both > TH, we go into if (Wr > TH) first. So iterate over x from 0 to floor(C/Wr)=2. Compute:
x=0: y= floor(1e9/600M)=1 (since 600M*1=600M, remaining 400M but can't add another because 1200M>1e9? Actually y = C/Wb = 1, floor=1) => joy=0+3=3.
x=1: y= floor((1e9-500M)/600M)= floor(500M/600M)=0 => joy=2.
x=2: y= floor((1e9-1e9)/600M)=0 => joy=4.
So max=4. Could there be better? Possibly x=0, y=1 gives 3, x=2 gives 4, x=1,y=0 gives 2. So 4 is best.
Now test case where both weights small but one efficient. Example: C=1000000000, Hr=3, Hb=5, Wr=2, Wb=3 (like sample but larger C). Then TH=100000, both <= TH? Wr=2, Wb=3 <= TH, so both small branch. HrWb=9, HbWr=10, so blue efficient. Iterate x from 0 to min(C/Wr, Wb-1)= min(500M, 2)=2. So only x=0,1,2. That seems insufficient? Let's test: For C huge, is it true that optimal x < Wb (i.e., x<3)? The lemma says if blue efficient (Hb/Wb > Hr/Wr), then in any optimal solution x < Wb, i.e., x <= 2. Is that always true for large C? Let's test numerically: Wr=2, Wb=3, Hr=3, Hb=5. So blue efficiency =5/3≈1.6667, red efficiency=1.5. So we want as many blues as possible. The optimal continuous is all blues: y = C/3, x=0, joy≈1.6667C. But integer: we can take floor(C/3) blues, weight = 3floor(C/3) <= C, leftover up to 2 grams (since mod 3). Could we improve by replacing some blues with reds to use leftover weight? For example, if we take y = floor(C/3) blues, leftover R = C mod 3, which can be 0,1,2. If R=0, perfect. If R=1, we cannot add a red (weight 2) without removing something. Maybe we could replace some blues with reds to use weight more efficiently? Suppose C=10 (sample), optimum was 2 reds + 2 blues = 16, while all blues (3 blues = 15) gave 15. So taking some reds improved. For large C, the optimal might involve a few reds to adjust the remainder. But the lemma says optimal x < Wb (=3). So we only need to consider x=0,1,2. That seems plausible because if we had x>=3, we could replace 3 reds (weight 6) with 2 blues (weight 6) and improve joy? Let's test: 3 reds give joy 9, 2 blues give joy 10, so indeed better. So any solution with x>=3 can be improved by replacing 3 reds with 2 blues, increasing joy and keeping weight same. So optimal cannot have x>=3. So indeed we only need to check x up to 2. So our algorithm works.
Now test the opposite: Hr=5, Hb=3, Wr=2, Wb=3, red efficient. Then we iterate y from 0 to min(C/Wb, Wr-1)= min(large,1)=1. So only y=0,1. That's plausible because if y>=2? Actually 2 blues weight 6, joy 6. Replace with 3 reds weight 6, joy 15 -> improvement. So y must be <2. Good.
Thus the lemma gives a strong bound.
Now we need to ensure that the heavy branch and lemma branch together cover all cases and are consistent. The heavy branch is used when one weight > TH. But if one weight > TH, could the lemma's bound also be applied? Possibly, but we don't need it because the loop over heavy is small.
But is it always safe to use heavy branch? For example, suppose Wr > TH, but Wb is very small, say 1. Then iterating over x up to C/Wr (which is small) is fine. But could the optimal solution involve a large number of reds? Since Wr is large, max reds is small anyway. So it's fine.
Now what about the case where both weights are <= TH but C is huge? Then we rely on lemma to limit the loop. That's fine.
Thus algorithm is O(TH) which is 1e5.
But we need to be careful about the threshold choice: TH = 100000 works but we must ensure that for C up to 1e9, C/TH is at most 10000, which is fine. But what if C is up to 10^18? The problem constraints say C ≤ 1e9, so fine.
Thus we can implement with TH = 100000 (or maybe sqrt(1e9) ≈ 31623 to be more efficient). Let's set TH = 40000 to be safe and still small. Actually we can compute sqrtC = sqrt(C) and set limit = sqrtC. That would be optimal. But we need to compute sqrt of up to 1e9, easy. Let's do:
long long limit = sqrt(C);
if (limit * limit < C) limit++; // ensure limit*limit >= C? Actually we want an integer such that if weight > limit, then count <= C/weight <= limit. Since sqrt(C) might not be integer, we can use limit = sqrt(C) (floor). If weight > floor(sqrt(C)), then weight >= floor(sqrt(C))+1, then count <= C/(floor(sqrt(C))+1) <= sqrt(C) (maybe). Actually need to be careful: Let s = floor(sqrt(C)). For any w > s, C/w < C/(s+1). Since s+1 > sqrt(C), C/(s+1) < sqrt(C). But we need bound on number of iterations. We can simply set threshold = 40000. But using sqrt(C) is more precise. However, there is a nuance: When both weights are <= sqrt(C), the lemma bound may be up to sqrt(C). That's fine. So we can compute s = sqrt(C) (use double then convert, but careful with precision). We'll use:
long long s = sqrt(C);
while (ss < C) s++;
while ((s-1)(s-1) >= C) s--; // but simpler: s = floor(sqrt(C)). We can use sqrtl.
Better: use sqrt((double)C) and then adjust. Or we can use integer sqrt function:
long long s = sqrt(C);
while (ss > C) s--;
while ((s+1)(s+1) <= C) s++;
We'll just use s = (long long) sqrt(C) and then if ((s+1)*(s+1) <= C) s++; Actually we want floor sqrt. Standard:
long long s = sqrt(C);
while (ss > C) s--;
while ((s+1)(s+1) <= C) s++;
But simpler: we can avoid sqrt and set a constant threshold like 100000, as argued.
Given the constraints, setting TH = 100000 yields at most 100000 iterations, which is perfectly fine. Even if we set TH = 1000000, that would be 1e6 loops, still fine? Possibly borderline but okay. But we'll use 100000 to be safe. I'd rather use 1000000? Actually 1e6 is still okay for one test case? Usually time limits allow ~1e8 operations? Not exactly; but 1e6 is trivial. However, if we set TH=1e6, then heavy branch when max weight > 1e6 gives count <= 1e3. But if both weights <= 1e6, we go lemma branch, which loops up to min(Wr,Wb?) Actually the bound is up to Wr or Wb, which could be up to 1e6. So that's up to 1e6 iterations, still okay. So we can set TH = 1e6 as well. But I'd like to keep it safe: set TH = 100000 (1e5) to ensure very fast.
But what if both weights are exactly 100000? Then lemma branch loops up to 100000, fine. If both weights are 200000? Then max weight > TH (since TH=100000) so heavy branch: if Wr > TH, we loop over x up to C/Wr. For C=1e9, C/200000=5000, fine. So all good.
Thus, we can implement with TH = 100000.
However, we need to ensure that when both weights are ≤ TH, we correctly apply the lemma. The lemma requires that the variable we iterate over (the less efficient one?) Actually if HrWb >= HbWr, we iterate y (blue) up to min(C/Wb, Wr-1). But note: In this condition, red is at least as efficient. So the less efficient item is blue. So we iterate over the less efficient item. That yields a bound on the less efficient item's count by the weight of the efficient item. So that's good.
Now, what if HrWb >= HbWr and Wr is 0? Not possible since >=1.
Now, edge case: If Wr or Wb equals 0? Not allowed because weights >=1.
Now, we should also consider the possibility that the heavy branch might miss some solutions if we only iterate over the heavy item but the heavy item is the less efficient? Actually we iterate over all possible counts of the heavy item, and for each we compute max of the other. That covers all combinations because we vary the heavy item count. So it's exhaustive. So no issue.
Now, let's double-check the lemma's correctness for all cases, including when the efficient item's weight is huge? But we only use lemma when both weights are small (≤ TH). So Wr and Wb are small, so it's fine.
Now, we need to consider integer overflow: When computing Hrx + Hby, both could be up to 1e9 * 1e5 = 1e14, fits in 64-bit (max ~9e18). So use long long.
Implementation steps:
- Read C, Hr, Hb, Wr, Wb.
- Define TH = 100000 (or maybe 1000000). I'll set TH = 100000 (100000).
- ans = 0.
- If max(Wr, Wb) > TH:
if (Wr > TH) {
max_x = C / Wr;
for (x = 0; x <= max_x; x++) {
y = (C - x * Wr) / Wb;
joy = x * Hr + y * Hb;
if (joy > ans) ans = joy;
}
} else { // Wb > TH
max_y = C / Wb;
for (y = 0; y <= max_y; y++) {
x = (C - y * Wb) / Wr;
joy = x * Hr + y * Hb;
if (joy > ans) ans = joy;
}
}
- else: // both <= TH
if (1LL * Hr * Wb >= 1LL * Hb * Wr) { // red more efficient or equal, so bound y < Wr
max_y = min(C / Wb, Wr - 1);
for (y = 0; y <= max_y; y++) {
x = (C - y * Wb) / Wr;
joy = x * Hr + y * Hb;
if (joy > ans) ans = joy;
}
} else { // blue more efficient, bound x < Wb
max_x = min(C / Wr, Wb - 1);
for (x = 0; x <= max_x; x++) {
y = (C - x * Wr) / Wb;
joy = x * Hr + y * Hb;
if (joy > ans) ans = joy;
}
}
Print ans.
Now test with some random cases to ensure no missing optimal.
Let's test a case where both weights are small but C is small enough that min(C/Wb, Wr-1) might be negative if Wr=0? Not possible. But if Wr=1, then Wr-1=0, so max_y=0, loop y=0 only. That is fine because if red efficient and Wr=1, then you can have at most y=0? Let's reason: if Wr=1, red efficient, then the bound says optimal y < Wr => y=0. So only y=0 is possible. That seems plausible: if red weight is 1 and more efficient, you should never take any blue because you could replace any blue with some reds? Actually consider Wr=1, Wb=2, Hr=10, Hb=15. Efficiencies: red 10/1=10, blue 7.5, red more efficient. Bound says y < 1 => y=0. So optimal is only reds. Is it always? If you take a blue (weight 2, joy 15), you could replace it with 2 reds (weight 2, joy 20) and increase joy. So yes, optimal has y=0. So fine.
Now, what about equality case: HrWb == HbWr, both efficiencies equal. Then our condition HrWb >= HbWr is true, so we go to first branch (iterate y up to Wr-1). But note that if both efficiencies equal, we could also iterate x up to Wb-1. Both should give same answer. We'll test: C=10, Hr=2, Hb=4, Wr=4, Wb=2 => efficiencies: 2/4=0.5, 4/2=2? Wait compute: Hr=2, Wr=4 => 0.5; Hb=4, Wb=2 => 2. So not equal. For equal: e.g., Hr=2, Hb=1, Wr=2, Wb=4 => Hr/Wr=1, Hb/Wb=0.25, not equal. Actually for equality we need HrWb = HbWr. Example: Hr=2, Wr=3; Hb=4, Wb=6 => 26=12, 43=12. So efficiencies: 2/3≈0.6667, 4/6≈0.6667. So both same. Then both items have same joy per weight. The maximum joy is achieved by maximizing weight used. In this case, the maximum weight achievable might be C if C is representable, else less. For C=10, with weights 3 and 6, we can achieve weights: 3,6,9,12,... So max ≤10 is 9. So joy = (2/3)9 = 6 (if using reds) or (4/6)9 = 6. So answer=6. Our algorithm: both weights <= TH (assuming 3,6 ≤ TH). Condition HrWb=12 >= HbWr=12 true, so iterate y from 0 to min(C/Wb, Wr-1) = min(10/6=1, 2)=1.
y=0: x = floor(10/3)=3, weight=9, joy=23+10? Actually Hr=2 => 6, Hb=1? Wait Hb=4? Actually in example we set Hb=4? Let's use Hr=2, Hb=4? For equality we need HrWb = HbWr, so if Hr=2, Wr=3; Hb=4, Wb=6 => 26=12, 43=12. So yes. Then y=0: x= floor(10/3)=3, joy=23+40=6. y=1: x= floor((10-6)/3)= floor(4/3)=1, joy=21+41=6. So max=6. Good.
Now test case where the heavy branch is used and the heavy item is the less efficient one. For example: C=100, Hr=5, Hb=100, Wr=60, Wb=61. So heavy weights > TH? TH=100000, they are < TH, actually both <= 100, so they are small (both ≤ TH). So we go to lemma branch. Which is more efficient? HrWb=561=305, HbWr=10060=6000 => Hb efficient. So we iterate over x up to min(C/Wr, Wb-1)= min(1, 60)=1. So x=0,1. Compute:
x=0: y= floor(100/61)=1 => joy=100.
x=1: y= floor((100-60)/61)= floor(40/61)=0 => joy=5.
So ans=100. But is there a better solution? Perhaps x=0, y=1 is best because weight 61 gives joy 100, and if we take x=1 (weight 60, joy 5) we could also take y=0, joy 5. So 100 is best. Could we take x=0,y=1 is optimal. So algorithm works.
Now test with heavy branch: C=1000, Hr=100, Hb=1, Wr=500, Wb=1. Here Wb=1 ≤ TH, Wr=500 ≤ TH? TH=100000, so both ≤ TH, so lemma branch. Check efficiency: HrWb=1001=100, HbWr=1500=500, so Hb efficient? Actually 100<500 so Hb more efficient? That would imply blue more efficient, but blue has low joy per weight (1 per gram) vs red 0.2 per gram? Actually Hr/Wr=0.2, Hb/Wb=1, so yes blue more efficient. So we iterate over x up to min(C/Wr, Wb-1)= min(2, 0)=0, so only x=0: y= floor(1000/1)=1000, joy=1000. That is indeed optimal? But maybe we could take some reds: Suppose take 1 red (weight 500, joy 100) and 500 blues (weight 500) total weight 1000? Actually 1 red + 500 blues weight = 500+500=1000, joy = 100 + 500 = 600, which is less than 1000. So indeed all blues is best.
Now what about a scenario where the heavy branch is used because one weight > TH but the other is tiny, and the heavy item is the efficient one? For example: C=1e9, Hr=1000, Hb=1, Wr=40000, Wb=1. Then Wb=1 ≤ TH? TH=100000, so both ≤ TH? Actually Wr=40000 ≤ 100000, Wb=1 ≤ 100000, so both ≤ TH, so lemma branch. Check efficiency: HrWb=10001=1000, HbWr=140000=40000, so Hb efficient? Actually 1000 < 40000, so blue efficient (since Hb/Wb=1, Hr/Wr=0.025). So algorithm would iterate over x (red count) up to min(C/Wr, Wb-1)= min(25000, 0)=0. So only x=0, y=1e9, joy=1e9. But is that optimal? Possibly taking many blues yields 1e9 joy, while taking reds yields at most floor(1e9/40000)=25000 reds gives 25e6 joy, far less. So correct.
Now consider heavy branch case: C=1e9, Hr=1000, Hb=1, Wr=100001, Wb=1. Then max(Wr,Wb)=100001 > TH=100000. So heavy branch: since Wr > TH, iterate over x from 0 to floor(C/Wr)= floor(1e9/100001) ≈ 9999. So loop 10000 times. For each x, y = floor((C - xWr)/Wb) = C - xWr (since Wb=1). So joy = 1000x + 1(C - xWr) = C + x(1000 - Wr). Since Wr=100001, 1000 - 100001 is negative, so joy decreases with x, max at x=0 gives joy = C = 1e9. So optimal is all blues again. So algorithm works.
Now consider a tricky case: both weights are large but one is just over TH and the other is just over TH as well. That's fine.
Now, is it always safe to use TH = 100000? Let's consider C could be as low as 1 but that doesn't matter. The only potential problem is if both weights are > TH but one weight is huge and the other is also huge but the heavy branch chooses the wrong one? But both have small counts, so either loop is small. But we need to ensure that if both > TH, we pick one and loop over it; that covers all possibilities because we are enumerating one variable completely. So it's fine.
Now, one more nuance: In the lemma branch, we iterate over the less efficient item up to bound. But suppose both efficiencies are equal, we iterate over y up to Wr-1. But what if Wr is 0? Not possible. For equality, the bound is still valid.
Now, what about the case where HrWb >= HbWr but Wr might be 1? Then we iterate y from 0 to min(C/Wb, 0) which is 0, so only y=0. That's fine.
Now, double-check the proof that when HrWb >= HbWr, we have y < Wr in some optimal solution. The proof: suppose we have an optimal solution (x, y) with y >= Wr. Then we can replace Wr blues with Wb reds: (x + Wb, y - Wr). This maintains weight (since +WbWr - WrWb = 0). The change in joy is: Δ = HrWb - HbWr. If Δ > 0 (strictly), then new solution has higher joy, contradiction. If Δ = 0, then joy is same; we can repeatedly apply to reduce y until y < Wr. So there exists an optimal solution with y < Wr. So the bound holds.
Thus, for strict >, any optimal must have y < Wr. For =, there exists an optimal with y < Wr.
Now, we need to confirm that when we iterate over y up to Wr-1, we will indeed capture an optimal solution. Since there exists an optimal solution with y in [0, Wr-1], and for that y we will consider x = floor((C - Wby)/Wr) (which is the maximum possible x given that y). Could the optimal solution with that y have x less than the maximum? Possibly if the optimal solution doesn't use full capacity? But if we can increase x without exceeding C, that would increase joy because Hr>0, so any optimal solution with a given y would maximize x (unless increasing x would exceed C). Actually, given y, the maximum joy for that y is achieved by taking as many reds as possible, because reds have positive joy per weight (and possibly more efficient). So the best for that y is x_max = floor((C - Wby)/Wr). Therefore, if there is an optimal solution with y* and some x (maybe not maximal), then the solution (x_max, y*) yields at least as much joy (since x_max >= x). So we can restrict to maximal x for each y. So iterating over y and taking x_max will include the optimal joy.
Thus algorithm correct.
Now, we should also consider the possibility that the efficient item's weight might be 0? No.
Now, we can also consider an alternative: iterate over i from 0 to TH (like 1e6) for the variable that we decide based on conditions. This is what we did.
Now, to be thorough, let's test with random values by brute force for small C to ensure algorithm matches brute force. We'll do mental testing.
Consider C=20, values: Hr=7, Hb=4, Wr=5, Wb=3.
Compute efficiencies: Hr/Wr=1.4, Hb/Wb≈1.333, red more efficient. So HrWb=21, HbWr=20, so red more efficient. Lemma says y < Wr=5, so y in 0..4.
But also max(Wr,Wb)=5 <= TH (100000), so lemma branch. We'll compute manually:
y=0: x = floor(20/5)=4 => joy=28
y=1: x = floor((20-3)/5)= floor(17/5)=3 => joy=73+4=21+4=25
y=2: x = floor((20-6)/5)= floor(14/5)=2 => joy=14+8=22
y=3: x = floor((20-9)/5)= floor(11/5)=2? Actually 11/5=2.2 floor 2 => joy=14+12=26? Wait 72=14, 43=12, total=26? But 25=10, 33=9 total 19 <=20, we could maybe add another red? Check: with y=3, used weight=9, remaining 11, max reds floor(11/5)=2, weight 10, total 19, leftover 1. So joy=14+12=26.
But is that valid? x=2, y=3 gives weight 10+9=19, joy=14+12=26.
y=4: x = floor((20-12)/5)= floor(8/5)=1 => joy=7+16=23.
Maximum among these: 28 (y=0) is highest. But maybe there is a better combination: x=2, y=3 gives 26, but not higher. x=1, y=5? But y=5 not allowed by bound; check if it could be better: y=5 weight=15, x= floor(5/5)=1 => joy=7+20=27? Actually 53=15, left 5, x=1 gives weight 5, total 20, joy=7+20=27. That's higher than 28? Actually 27 < 28. So not better. x=0,y=6? weight=18, joy=24. So 28 remains max. So algorithm gives 28.
But check if there is combination x=3, y=1 we already computed 25; x=3, y=2? Weight: 35+23=15+6=21 >20, not allowed. So 28 is optimal.
Now brute force small C? Probably fine.
Now consider a case where the less efficient item might be taken many times if the efficient item's weight doesn't divide capacity well. For example: C=100, Hr=101, Hb=100, Wr=100, Wb=1. So red efficiency = 1.01, blue efficiency = 100 (actually 100/1=100) > red, so blue is far more efficient. So we expect to take all blues. But bound: blue efficient => x < Wb? Since blue efficient means Hb/Wb > Hr/Wr, condition HrWb < HbWr? Let's compute: HrWb=1011=101, HbWr=100100=10000 => 101 < 10000 so yes blue efficient. Then bound says x < Wb = 1? Actually Wb is weight of blue? Wait careful: In the lemma, if blue efficient (i.e., Hb/Wb > Hr/Wr), then we should have x < Wb. Here Wb=1, so x < 1 => x=0. So only x=0 considered. Then y = floor(100/1)=100, joy=100*100=10000. But if we take x=1 red (weight 100, joy 101) and y=0, joy=101, which is much lower. So optimal is 10000. So algorithm yields that.
Now consider scenario where both efficiencies equal and both weights are small, but the bound may be up to Wr which could be large if Wr is large? But since both weights are small (< TH), Wr is small.
Now, we should consider if TH is set to 100000, but what if both weights are exactly 100001? Then max weight > TH, so heavy branch. Good.
Now, consider scenario where both weights are less than TH, but Wr is 100000, Wb=99999, TH=100000. Both ≤ TH? Wr=100000 ≤ TH, yes (since TH=100000). Then lemma branch. But then loop may go up to min(C/Wb, Wr-1) which could be up to 99999. That's 1e5 iterations, still fine. So TH=100000 yields at most 1e5 loops, which is fine. 1e5 is trivial.
Now, ensure that when both weights <= TH, we correctly compute max_y = min(C/Wb, Wr-1). But C/Wb could be huge (e.g., C=1e9, Wb=1 => 1e9), but we take min with Wr-1 which is <= 99999, so loop size is at most 99999. Good.
Thus algorithm is correct and efficient.
We might also consider an alternative approach: always iterate over i from 0 to 100000 for the variable determined by which weight is larger or something. But the above is fine.
Now, let's think about possible pitfalls:
-
Overflow when computing product Hr*Wb etc: use long long (64-bit).
-
Division: integer division.
-
In the heavy branch, when iterating over x from 0 to max_x, we need to ensure that we compute y correctly: y = (C - xWr) / Wb. Since C - xWr could become negative for x > max_x? But we only go up to max_x = floor(C/Wr), so C - x*Wr >= 0. Good.
-
In the lemma branch, for y loop, we compute x = (C - yWb) / Wr. Since y <= min(C/Wb, Wr-1), then yWb <= C, so non-negative.
-
Edge case: if Wr = 0 or Wb = 0 impossible.
-
The answer could be 0 if no candy can be taken (if both weights > C). But our loops will consider x=0 or y=0, which yields at least 0 joy. So ans will be 0.
Now, are we sure that the lemma holds even if the efficient item's weight is larger than the other? Yes, the proof doesn't depend on relative sizes.
Now, could there be a scenario where both weights are <= TH but the bound we use (say y < Wr) leads to a loop size up to 100000, but the optimal solution might require considering y up to something like Wr, which is fine. But what if Wr is 100000 and we iterate y from 0 to 99999, that's 100k iterations, okay. But if TH were set to 31623 and Wr=100000, then both weights <= TH? Actually 100000 > 31623, so that case would fall into heavy branch, not lemma. So the lemma branch only happens when both weights <= TH, meaning Wr <= TH, so loop at most TH. So it's consistent.
Thus final algorithm.
Now, note: The problem statement: "You can assume that each bag contains more candies that Om Nom can eat." So supply is unlimited.
Now, we should also consider potential improvements: Could we also handle the case where both weights are large but we still need to iterate over the other variable if the heavy branch chooses the wrong one? Actually heavy branch iterates over the heavy item; if both are heavy, both have small counts, but iterating over one is enough.
Now, I'll write the code in C++.
Implementation details:
- Use long long for all variables.
- Compute TH = 100000 (or maybe use sqrt(C) for adaptability). I'll go with sqrt(C) approach to be precise, but we must be careful with integer sqrt. Let's do:
long long limit = sqrt(C);
while (limit * limit < C) limit++; // to get ceil? Actually we want floor sqrt? For condition "if max(Wr,Wb) > limit" we need to ensure that if weight > limit, then count <= C/weight <= limit? If limit = floor(sqrt(C)), then for weight > floor(sqrt(C)), we have count <= C/weight < C/(sqrt(C)) = sqrt(C). Since floor(sqrt(C)) <= sqrt(C), we need to guarantee count <= something manageable. Let's analyze:
Let s = floor(sqrt(C)). For any w > s, w >= s+1. Then count = floor(C/w) <= C/(s+1). Since s+1 > sqrt(C) (because sqrt(C) >= s, but s+1 might be > sqrt(C) if sqrt(C) not integer). Actually C/(s+1) < C/sqrt(C) = sqrt(C). So count < sqrt(C). So it's bounded by roughly sqrt(C). So using s = floor(sqrt(C)) as threshold is fine. But if w = s+1, count <= C/(s+1) which is about sqrt(C) - something. So the loop size will be at most sqrt(C). So using floor sqrt is fine.
But we also have the lemma branch when both <= s. Then Wr,Wb <= s, so they are at most sqrt(C). And the loop there will be at most max(Wr,Wb) <= sqrt(C). So overall O(sqrt(C)).
So I can implement with threshold = sqrt(C). That is more precise and adapts to C.
However, when C is 1e9, sqrt = 31623, which is even smaller, good.
So I'll set:
long long limit = sqrt(C);
while ((limit+1)*(limit+1) <= C) limit++; // actually we want floor sqrt. Let's compute floor:
long long limit = (long long) sqrt(C);
while (limit * limit > C) limit--;
while ((limit+1)*(limit+1) <= C) limit++;
Better: use sqrtl and floor.
Simplify:
long long limit = sqrt(C);
while (limit * limit > C) limit--;
while ((limit+1)*(limit+1) <= C) limit++;
But we can also just use a constant as before. Since it's a single test, we can just use constant 100000. But to be elegant, I'll use sqrt.
One caution: if C is large up to 1e9, sqrt in double is precise, but to avoid floating errors, we can use sqrtl or compute integer sqrt via binary search. But it's okay.
I'll compute:
long long limit = sqrt(C + 0.5); // rounding? Actually sqrt returns double. Cast to long long truncates. But due to floating rounding, for large integers, it might be off by 1. Safer to use:
long long limit = (long long) sqrt(C);
while (limit * limit < C) limit++;
while (limit * limit > C) limit--;
Then limit is floor sqrt.
But this may involve loops but only a few iterations. We'll do:
long long limit = sqrt(C);
while ((limit+1)(limit+1) <= C) limit++;
while (limitlimit > C) limit--;
But we can just do:
long long limit = sqrt(C);
if (limit*limit < C) limit++; // now limit may be ceil? Actually if sqrt is 31622.7, trunc gives 31622, but 31622^2=999950884? Less than C, so we increment to 31623, then 31623^2=1000004129? Might be > C for C=1e9? Actually 31623^2 = 999950129? Let's compute: 31623^2 = (31620^2=999, etc). I'm not sure. Better to use integer sqrt function:
auto isqrt = [](long long n) {
long long x = sqrt(n);
while (xx > n) x--;
while ((x+1)(x+1) <= n) x++;
return x;
};
limit = isqrt(C);
But since it's just one call, it's fine.
Alternatively, we can avoid sqrt and set limit = 1e6? But I'll stick with constant for simplicity. The constant 100000 works as explained. I'll use 100000 to avoid sqrt issues.
Given the problem is simple, using constant is acceptable.
But let's double-check worst-case operations: If both weights <= 100000, we iterate up to min(C/Wb, Wr-1) which could be up to 99999. That's 1e5 operations, fine. If one weight > 100000, we iterate up to C/weight which is at most 1e9/100001 ≈ 9999, so at most 1e4. So total < 1e5. So it's very efficient.
Thus, implement with TH = 100000.
But we need to be careful: if Wr or Wb is exactly 100000, then max(Wr,Wb)=100000, which is not > TH (since TH=100000, we need >). So it goes into lemma branch. That's okay. If it goes into lemma branch and Wr=100000, then iteration up to Wr-1=99999, fine. So TH can be 100000 inclusive? We set condition if (max(Wr, Wb) > TH) then heavy, else lemma. So for max=100000, it's not >, so goes to lemma. That's acceptable.
But consider if both weights are exactly 100000, then lemma branch loops up to 99999. Fine.
Now, what if one weight is 100001? Then > TH, so heavy branch. That's also fine.
Thus TH=100000 works.
Now, implement.
Potential issues: When using min(C/Wb, Wr-1), ensure that Wr-1 is computed as long long, and that if Wr is 0? Not possible. Also, if Wr=1, then Wr-1=0, loop only y=0.
Now, we must also consider that for the heavy branch, we choose which variable to iterate based on which weight is > TH. But if both > TH, we will pick the first condition (Wr > TH). That's fine. But suppose Wr > TH, but Wb is also > TH, but Wb is much larger? Doesn't matter; iterating over reds (count = C/Wr) may be larger than iterating over blues (C/Wb)? But both counts are small; we can pick either. For safety, we could pick the one with smaller count to minimize loops, but not necessary. Both counts are at most C/TH ≈ 10000, so fine.
Now, we can also simply always iterate over the item with larger weight? Actually we can compute: if Wr > Wb, then maybe iterate over x because count = C/Wr <= C/Wb. So we can iterate over the heavier one. That would minimize loops. But our branch already picks the one > TH; if both > TH, we pick reds if Wr > TH, but maybe Wb > Wr? But that's okay.
We can also unify: if max(Wr,Wb) > TH, then let's iterate over the one with larger weight? Actually we can set:
if (Wr > Wb) {
// iterate over reds? But if both <= TH, we may need to iterate based on efficiency, not weight. So separate.
So we'll keep as earlier.
Now, final check: The answer could be large (up to H_max * C/min(W) i.e., about 1e9 * 1e9 = 1e18, fits in 64-bit.
Now, let's produce final code.
But wait: There's a nuance: The lemma bound y < Wr is valid for any optimal solution when HrWb >= HbWr? For strict > it's necessary; for equality we can transform to get y < Wr. However, is it possible that the optimal solution requires y to be exactly Wr? For equality, we can transform to get a solution with y < Wr and same joy, so there exists an optimal with y < Wr. So the max over y < Wr will achieve the same joy. So yes.
Now, we must also consider that the iteration over y includes y=0, but we are taking max over y. So if the optimal transformed solution uses y=0, that is included.
Now, one more subtlety: In the case of equality, the transformed solution may have different y but same joy. But could the maximum joy for a given y (with x max) be higher than the transformed solution's joy? Possibly, because the transformed solution may not be using full capacity, but the max for that y might fill more weight and thus yield higher joy. Since joy is proportional to weight, filling more weight increases joy. So the maximum over y (with x max) could be even higher than the joy of the transformed solution. So it's safe.
Thus algorithm stands.
Now, I'll code.
Implementation:
#include
#include
using namespace std;
typedef long long ll;
int main() {
ll C, Hr, Hb, Wr, Wb;
cin >> C >> Hr >> Hb >> Wr >> Wb;
const ll TH = 100000; // threshold
ll ans = 0;
if (max(Wr, Wb) > TH) {
// heavy item branch
if (Wr > TH) {
ll max_x = C / Wr;
for (ll x = 0; x <= max_x; ++x) {
ll y = (C - x * Wr) / Wb;
ans = max(ans, x * Hr + y * Hb);
}
} else { // Wb > TH
ll max_y = C / Wb;
for (ll y = 0; y <= max_y; ++y) {
ll x = (C - y * Wb) / Wr;
ans = max(ans, x * Hr + y * Hb);
}
}
} else {
// both weights <= TH
if (Hr * Wb >= Hb * Wr) {
// red more efficient or equal => bound on y
ll max_y = min(C / Wb, Wr - 1);
for (ll y = 0; y <= max_y; ++y) {
ll x = (C - y * Wb) / Wr;
ans = max(ans, x * Hr + y * Hb);
}
} else {
// blue more efficient => bound on x
ll max_x = min(C / Wr, Wb - 1);
for (ll x = 0; x <= max_x; ++x) {
ll y = (C - x * Wr) / Wb;
ans = max(ans, x * Hr + y * Hb);
}
}
}
cout << ans << endl;
return 0;
}
But we should also consider that in the heavy branch, if Wr > TH but Wb is very small, then the loop over x is small, but we compute y = (C - x*Wr)/Wb. This could be huge (up to 1e9), but that's just a computation, not a loop.
Now, test with sample: Input: 10 3 5 2 3 -> output 16.
Now, test with a case where both weights > TH: For example, C=1000000000, Hr=2, Hb=3, Wr=500000, Wb=600000 (both >100000). Then algorithm goes heavy branch, picks Wr > TH, loops x from 0 to 2000. Computes, should be fine.
Now, test with a case where both weights <= TH but the efficient item has weight = 100000 and the other = 1. Then we loop up to 99999. That's okay.
Now, we might want to also consider the possibility that the optimal solution might involve not taking the maximal x for a given y, if we consider that Hr may be 0? But constraints say at least 1, so positive. So maximizing x for given y is optimal.
Now, one more edge: if Wb = 0? Not possible.
Now, I think the solution is ready.
But let's double-check the logic for the bound when HrWb >= HbWr: we said iterate y up to min(C/Wb, Wr-1). However, what if Wr is huge? But we are in branch both <= TH, so Wr ≤ TH, so okay. But note that if Wr is 0? Not possible.
Now, about the condition if HrWb >= HbWr, we treat as red more efficient or equal. But is it possible that red more efficient but Wr is huge? But then both <= TH condition fails because Wr > TH would go to heavy branch. So fine.
Now, what about the scenario where both weights <= TH but HrWb >= HbWr, and Wr is 0? Not possible.
Now, I'll consider if there is any scenario where the bound might be insufficient due to the fact that we take x = floor((C - y*Wb)/Wr) which might be not optimal if Hr is negative? But it's positive.
Thus finalize.
But wait, could there be a scenario where the optimal solution uses a number of the efficient item that is less than the maximum for that y, because using more would exceed C, but we are already taking maximum. So correct.
Now, ensure we use long long for all intermediate results.
Now, perhaps we could simplify: Actually, the lemma can be applied even when both weights are > TH? For example, if both > TH, then both counts are small, so we could also just iterate over one variable entirely without needing lemma. But our heavy branch already does that.
Now, is it possible that both weights > TH but the heavy branch we choose (say iterate over reds) might have max_x up to 2000, but the optimal might require considering x beyond that? No, max_x is the maximum possible reds, so we cover all.
Thus the code is correct.
I'll add a small optimization: In the heavy branch, if Wr > TH and also Wb > TH, we could iterate over the one with smaller max count to reduce loops, but not needed.
Now, think about a possible corner: if Wr > TH but Wb is also > TH but Wb is much larger than Wr? Doesn't matter.
Now, we should also consider that the answer might be large, but we print as long long.
Now, I'll produce final answer.
But before finalizing, let's test with some random small values by mental simulation and maybe write a brute for small C to verify, but we can't run here. I'll try to reason a tricky case.
Consider C=100, Hr=8, Hb=7, Wr=13, Wb=12. Compute efficiencies: Hr/Wr≈0.615, Hb/Wb≈0.583, red slightly more efficient. HrWb=812=96, HbWr=713=91 => 96>91 so red efficient. Lemma says y < Wr=13. Both weights <= TH? 13 and 12 <= 100000, so lemma branch. We'll iterate y from 0 to min(C/Wb=8, 12)=8. Compute:
y=0: x= floor(100/13)=7 => joy=56.
y=1: x= floor((100-12)/13)= floor(88/13)=6 => joy=48+7=55.
y=2: x= floor((100-24)/13)= floor(76/13)=5 => joy=40+14=54.
y=3: x= floor((100-36)/13)= floor(64/13)=4 => joy=32+21=53.
y=4: x= floor((100-48)/13)= floor(52/13)=4 => wait 52/13=4 exactly => joy=32+28=60? Actually x=4, y=4 gives weight 134+124=52+48=100, joy=84+74=32+28=60. That's higher than 56. So ans=60.
y=5: x= floor((100-60)/13)= floor(40/13)=3 => joy=24+35=59.
y=6: x= floor((100-72)/13)= floor(28/13)=2 => joy=16+42=58.
y=7: x= floor((100-84)/13)= floor(16/13)=1 => joy=8+49=57.
y=8: x= floor((100-96)/13)= floor(4/13)=0 => joy=0+56=56.
So max is 60 at (4,4). Check if any solution better? Could there be x=5,y=2? weight 513+212=65+24=89 <=100, joy=40+14=54. Not better. x=6,y=1 weight=78+12=90 joy=48+7=55. x=7,y=0 weight=91 joy=56. So 60 is max. Good.
Now, what about if we had used heavy branch? Here max(Wr,Wb)=13 <= TH, so we used lemma branch. Good.
Now, consider a case where both weights > TH but we iterate over the heavy item (say Wr=100001, Wb=100002). Then both counts are about 9999 and 9999. Iterating over x up to 9999 is fine.
Now, consider case where both weights are small but the bound is not tight enough? No.
Now, confirm that the bound from lemma is indeed y < Wr (i.e., y <= Wr-1). In our iteration we use y <= min(C/Wb, Wr-1). That's correct.
Now, what about when Wr is 1? Then y <= 0, so only y=0. That's fine.
Now, test a case where HrWb >= HbWr but Wr is huge? Actually both weights <= TH, so Wr ≤ TH. So it's okay.
Now, implement.
One more nuance: In the heavy branch, we are iterating over the heavy item, but what if the heavy item is extremely inefficient and the optimal uses many of the light item? Since we iterate over the heavy item count from 0 to max, we still capture all possibilities because for each possible heavy count we take max light. So if optimal uses 0 heavy, we get it at x=0. So covered.
Thus final code is correct.
Now, we can produce final answer.
But the problem statement includes an image, not needed.
Now, I'll write final solution.
Potential improvements: Could also consider swapping roles if Wr > Wb to reduce loops in heavy branch, but not needed.
Now, I'll produce final code in answer.
One more thing: The input numbers can be up to 1e9, so use long long. In C++ int is usually 32-bit, may overflow when multiplying. So use long long.
Now, final answer. ```cpp
#include
#include
using namespace std;
typedef long long ll;
int main() {
ll C, Hr, Hb, Wr, Wb;
cin >> C >> Hr >> Hb >> Wr >> Wb;
const ll TH = 100000; // threshold – safe upper bound for O(TH) loops
ll ans = 0;
if (max(Wr, Wb) > TH) {
// one weight is large – its count is at most C/weight ≤ C/TH ≤ 1e4
if (Wr > TH) {
ll max_x = C / Wr;
for (ll x = 0; x <= max_x; ++x) {
ll y = (C - x * Wr) / Wb;
ans = max(ans, x * Hr + y * Hb);
}
} else { // Wb > TH
ll max_y = C / Wb;
for (ll y = 0; y <= max_y; ++y) {
ll x = (C - y * Wb) / Wr;
ans = max(ans, x * Hr + y * Hb);
}
}
} else {
// both weights are ≤ TH – use the swapping lemma
if (Hr * Wb >= Hb * Wr) {
// red at least as efficient -> optimal has y < Wr
ll max_y = min(C / Wb, Wr - 1);
for (ll y = 0; y <= max_y; ++y) {
ll x = (C - y * Wb) / Wr;
ans = max(ans, x * Hr + y * Hb);
}
} else {
// blue more efficient -> optimal has x < Wb
ll max_x = min(C / Wr, Wb - 1);
for (ll x = 0; x <= max_x; ++x) {
ll y = (C - x * Wr) / Wb;
ans = max(ans, x * Hr + y * Hb);
}
}
}
cout << ans << endl;
return 0;
}