We are given: n beds in a row, m pillows total (n ≤ m). Each hobbit must have at least 1 pillow. The condition: "any hobbit gets hurt if he has at least two pillows less than some of his neighbors have." So basically, for any adjacent pair, the absolute difference in pillows must be at most 1? The phrasing: "he has at least two pillows less than some of his neighbors have." That means if a hobbit has x and a neighbor has y such that x ≤ y-2, then he gets hurt. So we need to avoid that. So the condition is: For every adjacent pair, |a_i - a_{i+1}| ≤ 1. But careful: "at least two pillows less" means if a_i <= a_j -2 (where j is neighbor), then he is hurt. Does it also apply if he has more? The statement says "any hobbit gets hurt if he has at least two pillows less than some of his neighbors have." So only if a hobbit has at least two less than a neighbor. If a hobbit has more, it doesn't say that the neighbor is hurt? But the neighbor would then have at least two less? Actually, if a_i is larger than a_j by at least 2, then a_j would be at least two less than a_i, so a_j would be hurt. So effectively, the condition is symmetric? Let's read: "any hobbit gets hurt if he has at least two pillows less than some of his neighbors have." So for each hobbit, consider his neighbors; if there exists a neighbor such that the neighbor's pillows minus his pillows >= 2, then he is hurt. So to avoid any hurt, for every adjacent pair, the difference must be at most 1. Because if difference is 2 or more, then the smaller one is hurt. If difference is exactly 1, then the smaller one is exactly 1 less, which is not "at least two less", so he is not hurt. And the larger one is not hurt because he is not less than his neighbor. So condition is: For all i, |a_i - a_{i+1}| <= 1. That's the typical interpretation.
Thus we have an array of n positive integers (>=1) summing to m, with the condition that adjacent differences are at most 1. We want to maximize a_k (Frodo's bed). n,m up to 1e9, so we need O(log m) or O(1) solution.
This is a known problem from Codeforces (I think "Pillows" or something). We need to compute the max possible a_k given total pillows m, number of beds n, and position k.
We need to maximize a_k subject to:
- a_i >= 1 for all i.
- |a_i - a_{i+1}| <= 1.
- sum_i a_i = m.
We can choose any configuration of a_i satisfying these constraints. We want to maximize a_k.
Given m,n,k, what's the maximum possible value for a_k?
We can think of constructing a "mountain" shape with peak at position k. To maximize a_k, we want to allocate as many pillows as possible to position k, while keeping the array decreasing by at most 1 as we move away from k, and all entries at least 1. This is like a pyramid centered at k.
Let x = a_k (the target). Then the minimal pillows needed to support x at position k, under the constraints, is: we must have a_i >= max(1, x - distance) where distance = |i-k|. Because from the peak, the numbers can decrease by at most 1 each step, and they can be larger but to minimize total sum (so we can maximize x given fixed m), we set them as low as possible while satisfying constraints: a_i = max(1, x - d_i) where d_i = |i-k|. Additionally, the decreasing condition only restricts difference, not being too high. But if we set some a_i higher than these minimal values, that would increase total sum, making it harder to achieve given m; so for a given x, we want to check if it's possible to have sum <= m? Actually we need sum exactly m, but we can allocate extra pillows arbitrarily as long as constraints hold. But to maximize x, we want to see the smallest possible total sum given that a_k = x (and we can adjust others upward if needed). If the minimal possible sum for a given x is <= m, then we can increase some other a_i (perhaps the ones near the edges) to use up the remaining pillows without violating constraints (since we can increase any a_i as long as adjacent differences <= 1). But we have to ensure we don't exceed m. But if minimal sum is > m, then x is too high. So the condition for x being feasible is: minimal_sum(x) <= m.
Thus we want to find max x such that minimal_sum(x) <= m.
Now compute minimal_sum(x). Given x, we consider the shape:
For i left of k: left side distances 1,2,..., (k-1). Actually distance from k: for i = k-d (if d steps left), a_i minimal = max(1, x - d). Similarly for right side: distances 1,..., n-k. So minimal sum = sum over all i of max(1, x - |i-k|). Additionally, we have a_k = x.
Now we need to sum these terms.
But note that as x grows, the pyramid expands. Eventually the leftmost and rightmost might hit the floor of 1. So we need to handle the range where x - d >= 1, i.e., d <= x-1. So for left side, number of positions where a_i > 1 is at most x-1 (since distance 0 gives x, distance 1 gives x-1, ..., distance x-1 gives 1). Actually when distance = x-1, then x - (x-1) = 1, which is still >=1. For distance >= x, the minimal becomes 1. So on each side, the pyramid covers up to min(d_max, x-1) positions with descending values from x-1 down to 1, and the rest are 1.
Thus minimal sum S(x) = x + sum_{d=1}^{L_eff} (x - d) + (remaining left positions)1 + similarly for right. But careful: L_eff = min(k-1, x-1). Similarly R_eff = min(n-k, x-1). Then the sum of the descending part: For left side: sum_{d=1}^{L_eff} (x - d) = L_eff * x - sum_{d=1}^{L_eff} d = L_effx - L_eff*(L_eff+1)/2. Similarly for right side.
Then remaining left positions: (k-1 - L_eff) each with 1. So total 1's from left leftover = (k-1 - L_eff). Right leftover: (n-k - R_eff). Plus also the base: the positions that are beyond pyramid on both sides are 1. Also the peak itself is x. So total sum:
S(x) = x + [L_effx - L_eff(L_eff+1)/2] + [R_effx - R_eff(R_eff+1)/2] + (k-1 - L_eff) + (n-k - R_eff).
Simplify: S(x) = x + (L_eff + R_eff)*x - [L_eff(L_eff+1)+R_eff(R_eff+1)]/2 + (n-1) - (L_eff+R_eff) because total number of beds excluding k is n-1 = (k-1)+(n-k). Actually (k-1 - L_eff)+(n-k - R_eff) = n-1 - (L_eff+R_eff). So:
S(x) = x + (L_eff+R_eff)*x - (1/2)[L_eff(L_eff+1)+R_eff(R_eff+1)] + n-1 - (L_eff+R_eff).
Combine the terms: S(x) = x*(1 + L_eff + R_eff) - (L_eff+R_eff) - (1/2)[L_eff(L_eff+1)+R_eff(R_eff+1)] + n-1.
Alternatively, we can compute as:
S(x) = (sum_{i=1}^{n} base_i) where base_i = 1 if far, else x - d.
Maybe there is a more straightforward formula.
But note: we can also compute S(x) = sum_{i=1}^{n} max(1, x - distance_i) where distance_i = |i - k|.
Given that n,m up to 1e9, x can be up to m (since at least n pillows, but x can be large). However we can binary search on x from 1 to m (but m up to 1e9, binary search O(log m) is fine). But we need to compute S(x) efficiently O(1). That seems doable. But note that L_eff = min(k-1, x-1) and R_eff = min(n-k, x-1). So we need to compute these based on x.
But we have to be careful: x can be as small as 1, but since n ≤ m, there is always at least n pillows, so x can be 1 at minimum.
But maybe we can find a direct formula. Binary search is safe.
Edge Cases: k is 1 or n, then one side length is zero.
Now we need to ensure that we can always distribute extra pillows beyond the minimal sum without violating constraints. The question: If minimal sum <= m, is it always possible to achieve exactly sum = m? We need to argue yes: we can increase some a_i without violating constraints. Since the constraints only restrict differences, we can add pillows to any bed as long as we maintain the adjacency condition. But if we increase a bed arbitrarily, it may cause differences >1. However we can add pillows uniformly to all beds? Not exactly. But we can increase the "floor" value. Actually consider that the minimal configuration is a pyramid that might have some flat 1's on the edges. If we have extra pillows, we can increase some of those 1's, but must ensure that the differences with neighbors remain ≤1. Typically we can increase the entire sequence by adding 1 to every bed, which would increase sum by n and still maintain the condition (since differences unchanged). But that would increase all numbers equally, raising the minimum. However we might not want to increase all because we might overshoot? But we can add pillows in a way that preserves the condition, for example, we can always increase the peak further? But that would change x. We want to keep x fixed. So we need to distribute extra pillows without increasing x. So we need to see if there is a way to add pillows to other beds while keeping the peak at x and differences ≤1.
Given a minimal configuration where a_i = max(1, x - d_i). If we add a pillow to some bed, we might break the condition with its neighbors if they are exactly one less. But we can also add to neighbors accordingly. Essentially, we can increase the whole "floor" area. Usually, for such monotonic constraints, the configuration space is convex; we can add pillows to any bed as long as we also adjust to keep differences ≤1. It might be possible to increase any of the 1's at the edges? Let's examine.
Suppose leftmost side has a_1 = 1. Its neighbor a_2 might be either 2 (if within pyramid) or 1 (if also floor). If a_2 = 2, then difference is 1, so we can't increase a_1 to 2 because then difference would be 0 (2-2=0) which is fine? Actually condition: |a_i - a_{i+1}| ≤ 1, so difference 0 is allowed. So we can increase a_1 to 2, then a_2 might need to be at least 1? But a_2 is 2, difference 0, fine. However if a_2 = 1 (both floor), then both are 1, difference 0; increasing a_1 to 2 would make difference 1 (2-1=1) which is allowed. So increasing a_1 alone seems okay. But what about the neighbor on the other side? Only one neighbor for endpoints. So we can increase any bed individually as long as after increase, it remains within 1 of its neighbors. Since the neighbors are not being decreased, the difference could become larger if we increase too much. For example, if a_i is increased to be 2 more than neighbor, that violates. So to safely add pillows, we must ensure that after adding, a_i ≤ neighbor+1 and a_i ≥ neighbor-1. Since we are only increasing a_i, the condition a_i ≥ neighbor-1 is automatically satisfied because original a_i >= neighbor-1? Actually original a_i might be exactly neighbor-1? Let's analyze: In the minimal configuration, we have a_i either part of the descending pyramid or flat ones. The pyramid ensures that as we go away from peak, each step decreases by exactly 1 until we hit 1, then constant 1. So for any two adjacent positions, the difference is either 0 (if both 1) or 1 (if one is higher). In the minimal configuration, differences are exactly 0 or 1. So if we increase a_i by 1, then:
- If originally a_i = a_{i-1} - 1 (i.e., a_i is one less than left neighbor), then after increment, a_i becomes equal to a_{i-1}. That's allowed (diff=0).
- If originally a_i = a_{i+1} - 1, similarly becomes equal to right neighbor.
- If originally a_i = a_{i-1} (both equal), then after increment, a_i becomes a_{i-1}+1, diff=1 allowed if a_{i-1} is not also increased? But that would be allowed as long as a_i <= a_{i-1}+1? Actually a_i = a_{i-1}+1 after increment, diff=1, allowed. However, we must also check the right neighbor: if originally a_i = a_{i+1} (equal), then after increment, a_i = a_{i+1}+1, diff=1, allowed. If originally a_i = a_{i+1}+1? That would mean a_i is one more than right neighbor; after increment, a_i becomes a_{i+1}+2, diff=2, not allowed. But in the minimal configuration, is it possible that a_i is one more than its right neighbor? That would be descending from left to right. For descending, a_i = a_{i+1}+1 is possible. For example, near the peak: a_{k} = x, a_{k+1}=x-1, so a_k is one more than a_{k+1}. If we increase a_{k+1} by 1, then a_{k+1} becomes equal to a_k, diff=0, allowed. But if we increase a_k? That would increase the peak, which we don't want. However we are not increasing the peak; we are increasing other beds. So consider a position that is one more than its right neighbor: That happens when we are moving away from peak to the right: a_i = something, a_{i+1}=a_i-1. So a_i is greater than a_{i+1} by 1. If we increase a_{i+1} (the smaller one) by 1, then they become equal, fine. If we increase a_i (the larger one) by 1, then difference becomes 2, violating. So to avoid violation, we should avoid increasing a bed that is larger than its neighbor by exactly 1. But can we increase such a bed? Possibly we could also increase the neighbor to keep difference ≤1. But that would increase sum further; but we are allowed to allocate extra pillows arbitrarily as long as constraints hold. So we can always add pillows in such a way to not break constraints: for instance, we can add pillows to all beds that are at the minimum (the ones that are 1) without affecting others? But need to check if increasing a floor bed that is next to a descending step could cause violation. Example: left side: positions: ... a_{k-2}=x-2, a_{k-1}=x-1, a_k=x, then to the left further: a_{k+1}? Wait. Actually for left side: i = k-1: distance 1 => a = x-1; i = k-2: distance 2 => a = x-2; ... until distance d where x-d=1 => d = x-1; then further left all 1's. So at the boundary between the descending part and the flat 1's, there is a step: say at position i where a_i = 2 (if x- d =2) and i-1 (further left) has a_{i-1}=1. So a_i = 2, a_{i-1}=1 => difference = 1. If we increase a_{i-1} from 1 to 2, then they become equal, fine. If we increase a_{i} from 2 to 3, then difference with a_{i-1} becomes 2 (if a_{i-1} remains 1) which is not allowed. But we could also increase a_{i-1} to 2 simultaneously, but that would increase two pillows; but is it allowed to just increase a_i? Not alone. But we can choose to increase the flat region uniformly, like increase all flat 1's to 2, then also adjust the boundary? Actually, we could increase a_{i-1} to 2 without increasing a_i; then difference is 0. So we have flexibility.
Thus, given minimal sum S_min(x), we can allocate extra pillows in many ways; the question is: can we always achieve any total sum between S_min(x) and some S_max(x) (while keeping a_k = x)? If yes, then condition S_min(x) <= m is sufficient. But we must also check that we cannot exceed some maximum while keeping a_k fixed? Actually we could increase other beds arbitrarily, but may eventually be forced to increase a_k to keep differences ≤1? For instance, if we increase a_{k+1} enough, it might become equal to x, but we could also increase it beyond x? But then to keep difference ≤1, a_k would need to be at least (a_{k+1} -1) => if a_{k+1} becomes x+1, then a_k must be at least x, which it is, but difference would be 1? Actually if a_{k+1}=x+1, then a_k (x) is 1 less, which is allowed because a_k is not less by 2. However, the condition is that any hobbit gets hurt if he has at least two pillows less than some neighbor. So if a_{k+1}=x+1, then a_k = x, difference =1, so both are fine. But is a_{k+1}=x+1 allowed? The constraint is that the difference must be ≤1. So if a_{k+1}=x+1, then difference with a_k is 1, allowed. But what about a_{k+2}? If we increase a_{k+1} to x+1, then to maintain differences, a_{k+2} must be at least x (since |a_{k+1} - a_{k+2}| ≤ 1). But a_{k+2} originally is max(1, x-2). To keep it ≤1 difference, we can set a_{k+2} to x (if we increase it) or x? Actually if a_{k+1}=x+1, then a_{k+2} can be x or x+2? The condition: |a_{k+1} - a_{k+2}| ≤ 1 => a_{k+2} ∈ [x, x+2]? Wait: if a_{k+1}=x+1, then a_{k+2} must be between (x+1)-1 = x and (x+1)+1 = x+2. So a_{k+2} could be x, x+1, or x+2. But a_{k+2} also has neighbor a_{k+3}. So we could increase the whole right side uniformly? Possibly we can increase some beds beyond the pyramid. However, note that if we increase a_{k+1} above x, we might be able to keep a_k fixed at x, but then a_{k+1} is higher than the peak, effectively making a new peak. But we want to maximize a_k, so we would not want to increase others above x because that might not help us; but the question is about feasibility: given we want a_k = x, can we always use extra pillows by raising other beds without violating constraints? We can always raise the beds that are not on the peak, but there might be a limit because if we raise a neighbor too high, it would force the peak to be at least that high minus 1? Actually the condition only restricts differences. So if we raise a_{k+1} to x+1, it's still within 1 of a_k (x). That's fine. If we raise a_{k+1} to x+2, then difference would be 2, not allowed. So a_{k+1} ≤ x+1. Similarly, if we raise a_{k+2} can be at most a_{k+1}+1. So in principle, we could raise the entire right side to form a plateau or even increase gradually. But could we raise them arbitrarily while keeping a_k = x? Let's think: On the right side, we have a_k = x. a_{k+1} can be at most x+1. If we set a_{k+1}=x+1, then a_{k+2} can be at most a_{k+1}+1 = x+2, but also must be within 1 of a_{k+1}. So a_{k+2} can be as high as x+2. Then a_{k+3} can be x+3, and so on. But note that this would create an increasing sequence to the right, making later beds much higher than the peak. This would increase sum dramatically, but we only have a fixed total m. However, we are checking if we can achieve any sum between S_min(x) and some upper bound while keeping a_k = x. Since we have a fixed total m, we just need to know if there exists some configuration with sum exactly m and a_k = x. If S_min(x) <= m, can we always realize exactly m? We need to argue that we can increase sum continuously from S_min(x) up to some maximum without changing a_k. Typically, these kind of problems rely on the fact that you can always add pillows one by one to some bed while preserving constraints, as long as you don't exceed the bound where you would have to increase a_k. But is there an upper bound for sum given fixed a_k? Yes, there is a maximum sum possible with a_k fixed, because you cannot increase others indefinitely? Let's examine: With a_k fixed at x, what is the maximum possible sum? You could make the sequence strictly increasing to the left and right from k? But there are boundaries at ends. At the left end (bed 1), you can make a_1 arbitrarily high? Let's see constraints: Starting from a_k = x, moving left: a_{k-1} must satisfy |a_{k-1} - a_k| ≤ 1 => a_{k-1} ∈ [x-1, x+1]. If we set a_{k-1} = x+1, then moving further left: a_{k-2} must be within 1 of a_{k-1}, so a_{k-2} ∈ [x, x+2]. We can choose a_{k-2} = x+2, then a_{k-3} = x+3, etc. So we could make the sequence increase as we move away from k, as long as we stay within bounds? But we have finite number of beds; at the leftmost bed, there is no further constraint. So we could set a_1 to be very large if we increase step by step. For example, if k=2, we could have a_2 = x, a_1 = x+1 (or higher?). Let's compute: a_2 = x, a_1 can be at most x+1 (since difference ≤1). So a_1 cannot exceed x+1. So the maximum at the left end is x+1. If we have more beds to the left, could we make them larger than x+1? Starting from a_k, moving leftwards: each step you can increase by at most 1. So after d steps left, the maximum possible value is x + d. But note the constraint also that differences can't be more than 1, but you can increase, so the maximum at position k-d is x + d? Let's verify: We want a_{k-1} max. Given a_k = x, a_{k-1} ≤ a_k + 1 = x+1. So max is x+1. Then for a_{k-2}, given a_{k-1} can be at most x+1, then a_{k-2} ≤ a_{k-1}+1 ≤ x+2. So yes, a_{k-2} ≤ x+2. In general, at distance d to the left, a_{k-d} ≤ x + d. Similarly to the right, a_{k+d} ≤ x + d. However, is there any lower bound that would force it to be at least something? No, we can always set it to be as low as allowed (but we are maximizing sum). So the maximum sum with fixed a_k = x would be obtained by setting each side to the maximum allowed: a_{k-d} = x + d, for d = 1..left_len, but careful: we must also respect that values cannot be negative and must be at least 1, but x+d will be >1. However, there is also the constraint that we cannot have "valleys" – but we are constructing a monotonic increasing as we move away from k, which is allowed as long as each step is ≤1 increase? Actually if we set a_{k-1}=x+1, that's an increase of 1 from a_k, allowed. Then a_{k-2}=x+2 is an increase of 1 from a_{k-1}, allowed. So yes, we can have increasing sequence away from k. But wait, the condition is about any hobbit getting hurt if he has at least two pillows less than a neighbor. This is symmetric, so increasing is fine as long as differences are at most 1. So we can have values higher than the peak on both sides, as long as they increase gradually. But then a_k would not be the maximum; there would be higher values on the sides. But the condition doesn't require a_k to be the maximum; it's just that we want to maximize a_k given the total m. In the feasibility check, we fix a_k = x. But if we allow other beds to be larger than x, then a_k is not the maximum, but that's allowed as long as a_k is exactly x. But would that help us achieve a higher total sum while keeping a_k fixed? Yes, but we only care about whether we can achieve exactly m sum. For given x, the maximum possible sum is something like: we can increase other beds arbitrarily high, but there is an upper bound because each side length is limited. Actually, as argued, at distance d, max is x + d (since we can increase by 1 each step). So the maximum sum for fixed x is when we set the sequence as high as possible on both sides: i.e., on left, set a_{k-d} = x + d for d=1..(k-1); on right, set a_{k+d} = x + d for d=1..(n-k). But is that always consistent? For example, if we set left side increasing as we move away from k, then at the leftmost bed (index 1), we would have a_1 = x + (k-1). That's the maximum possible at that position. Similarly, rightmost a_n = x + (n-k). So the maximum sum would be:
MaxSum(x) = x + sum_{d=1}^{k-1} (x + d) + sum_{d=1}^{n-k} (x + d).
But careful: For d steps left, the position index is k-d. The value = x + d. So yes.
Sum_{d=1}^{L} (x + d) = L*x + L(L+1)/2, where L = k-1. Similarly for right: R = n-k.
So MaxSum(x) = x + Lx + L(L+1)/2 + Rx + R(R+1)/2 = x*(1+L+R) + (L(L+1)+R(R+1))/2.
But note that this MaxSum is actually larger than minimal sum. So for a given x, achievable sums lie between S_min(x) and S_max(x) inclusive? Probably yes, and because we can adjust continuously? We need to see if any integer between them is achievable. Usually with such constraints and integer values, the set of achievable sums might be all integers in that range, because we can increment by 1 by adding to some bed while maintaining constraints. But we must confirm.
Given minimal configuration (descending pyramid) and maximal configuration (ascending ramps), both satisfy constraints. And there may be many intermediate configurations. Since we can increase from the minimal by adding pillows to certain positions gradually, we likely can achieve any intermediate sum. For example, we can start from minimal and add pillows one by one to the leftmost bed until it reaches its maximum, then to the next, etc. This is akin to having a convex polytope of integer points; the sum can vary.
But in such problems, it's standard to binary search on x using the condition that minimal pillows needed for x is ≤ m. I recall Codeforces problem "Pillows" (maybe 239B? Actually it's Codeforces Round #...). The solution is indeed binary search on answer, compute minimal pillows needed. So we can assume feasibility if minimal sum ≤ m.
Let's verify with examples:
Example 1: n=4,m=6,k=2. Our method: binary search for max x. Let's compute S_min(x):
- For x=2: k=2, L_eff = min(k-1=1, x-1=1)=1, R_eff = min(n-k=2,1)=1. So L_eff=1,R_eff=1.
S_min = x + L_effx - L_eff(L_eff+1)/2 + R_effx - R_eff(R_eff+1)/2 + (n-1)-(L_eff+R_eff) = 2 + 12 -1 + 12 -1 + 3 -2 = Let's compute: L_effx=2, minus L_eff(L_eff+1)/2=12/2=1 => contributes 1; similarly for right: 2-1=1; plus x=2 => total so far 2+1+1=4; plus (n-1)-(L_eff+R_eff)=3-2=1 => S_min=5? Actually n-1=3, L_eff+R_eff=2, so leftover=1. So S_min=5? But m=6, so x=2 feasible? S_min=5 <=6. Now x=3: L_eff = min(1,2)=1; R_eff = min(2,2)=2? Actually x-1=2, so R_eff = min(2,2)=2. Then compute:
Left sum: L_effx - L_eff(L_eff+1)/2 = 13 - 1 = 2? Actually L_eff(L_eff+1)/2 =1 -> 3-1=2.
Right sum: R_effx - R_eff(R_eff+1)/2 = 23 - (2*3/2=3) = 6-3=3.
So sum of these two parts = 2+3=5.
Add x=3 => total 8.
Remaining: (k-1 - L_eff) = 1-1=0; (n-k - R_eff)=2-2=0; So S_min = 8 + (n-1 - (L_eff+R_eff))? Actually we already added leftover ones? In the formula we used: we add (k-1 - L_eff)+(n-k - R_eff) as ones. But if L_eff+R_eff covers all others, then leftover=0. But wait, we must also add the ones for positions that are not covered by pyramid? Actually our sum already includes x, plus the left descending part, plus right descending part, plus the ones for leftover. Here leftover=0, so S_min = 3 + 2 + 3 = 8. So S_min=8 > m=6, so x=3 not feasible. Thus max x=2, matches example.
Example 2: n=3,m=10,k=3. So k=3 (rightmost). n=3, k=3 => left side L_len = k-1=2, right side R_len=0.
We need max x.
Check x=4: L_eff = min(2,3)=2 (since x-1=3). R_eff = min(0,3)=0.
Compute:
Left sum: L_effx - L_eff(L_eff+1)/2 = 24 - 23/2 = 8 - 3 = 5.
Right sum: 0.
Add x=4 => total 9.
Remaining ones: (k-1 - L_eff) = 2-2=0; (n-k - R_eff)=0. So S_min=9 <=10.
x=5: L_eff = min(2,4)=2; compute left sum: 25 - 3 = 10-3=7; + x=5 =>12; S_min=12 >10 => not feasible. So max x=4, matches.
Example 3: n=3,m=6,k=1. k=1 leftmost, L_len=0, R_len=2.
x=3: R_eff = min(2,2)=2 (x-1=2). Compute right sum: 23 - 23/2 = 6 -3 =3. + x=3 =>6. leftover: (n-k - R_eff) =2-2=0. So S_min=6 <=6. x=4: R_eff = min(2,3)=2? Actually x-1=3, so R_eff = min(2,3)=2. right sum: 2*4 - 3 =8-3=5; + x=4 =>9; S_min=9 >6. So max x=3, matches.
Thus binary search works.
Now we need to compute S_min(x) efficiently and avoid overflow because values can be up to 1e9 and sums can go up to m (but intermediate calculations might exceed 64-bit? n up to 1e9, x up to maybe 1e9, sums up to around n*x, which could be up to 1e18, so 64-bit signed is safe (max 9e18) if we use 64-bit (long long in C++ up to 9e18). But careful: x can be as high as m up to 1e9, n up to 1e9, product up to 1e18, plus other terms maybe up to ~1e18, but still within 2^63-1 (~9.22e18). So use 64-bit.
But we need to ensure our binary search bounds: low = 1 (since at least 1), high = m (since total m pillows, and Frodo can't have more than m). But we can also set high = m - (n-1) + 1? Actually Frodo can have at most m - (n-1) because others need at least 1 each, so at most m - (n-1). But m up to 1e9, that's fine. However, note that if n is large, maybe x can be > m - (n-1) + 1? Actually maximum x is m - (n-1) if all others get exactly 1. But that's a bound; but also the constraints might force x to be smaller. So we could set high = m - (n-1) + 1? Actually better set high = m (safe). But when computing S_min(x), if x is huge, S_min(x) will be huge and may overflow 64-bit? But we can cap the sum at something > m, say if sum exceeds m we can break early. In binary search, we compute S_min(x) and compare to m. To avoid overflow, we can check during computation: if intermediate sum > m, we can return false early. Since m ≤ 1e9, but S_min(x) could be huge (like if x=1e9, n=1e9, S_min(x) ~ (x^2) something? Let's compute worst-case S_min(x) when x is large. If x is huge, then L_eff = k-1, R_eff = n-k, so S_min(x) = x + ( (k-1)+(n-k) )x - [L(L+1)+R(R+1)]/2 + (n-1)-(L+R). That simplifies to x + (n-1)x - something + (n-1)-(n-1) = nx - something? Actually if L_eff = k-1, R_eff = n-k, then L_eff+R_eff = n-1, so S_min = x + (n-1)x - [sum of L(L+1)/2 + R(R+1)/2] + (n-1)-(n-1) = nx - [L(L+1)+R(R+1)]/2. So S_min is approx nx, which for x up to 1e9 and n up to 1e9 gives 1e18, still safe in 64-bit. But if we also consider that we may cap early when sum > m, we can avoid overflow by using conditions like if x > m? Actually m up to 1e9, so if x > m, S_min(x) > m because at least x itself > m, so we can early return false. But in binary search we will have high=m, so x <= m. So x up to 1e9, n up to 1e9, product up to 1e18. That's within 2^63-1. So using 64-bit signed (long long in C++) is safe.
But in Python, integers are arbitrary precision, so no problem.
Thus we can implement binary search from 1 to m, compute minimal pillows needed for x, and if <= m, then it's feasible, else not.
But is there a direct formula? Maybe we can compute x directly using arithmetic? Possibly, but binary search is simple and fast enough O(log m) with O(1) per check.
Edge Cases: When x=1, S_min(1) = n (since all must be at least 1, and differences? With x=1, the condition that differences <= 1 still holds if all are 1, sum = n. But also possible to have some higher? But minimal sum is n, because each at least 1. So S_min(1) = n <= m always, because n ≤ m. So low = 1 feasible.
Now confirm S_min formula thoroughly.
Define left_len = k-1, right_len = n-k.
Let d_left = min(left_len, x-1). Similarly d_right = min(right_len, x-1).
Then the left side positions that are within the pyramid: for distance d=1..d_left, a_{k-d} = x - d. The rest left positions (if any) get 1.
Similarly for right.
Thus sum = x (peak) + sum_{d=1}^{d_left} (x - d) + sum_{d=1}^{d_right} (x - d) + (left_len - d_left) * 1 + (right_len - d_right) * 1.
Compute sum_{d=1}^{t} (x - d) = t*x - t(t+1)/2.
Thus total = x + [d_leftx - d_left(d_left+1)/2] + [d_rightx - d_right(d_right+1)/2] + (left_len - d_left) + (right_len - d_right).
Simplify: = x*(1 + d_left + d_right) - (d_left(d_left+1)+d_right(d_right+1))/2 + left_len + right_len - (d_left + d_right).
But left_len + right_len = n-1. So total = x*(1 + d_left + d_right) - (d_left(d_left+1)+d_right(d_right+1))/2 + (n-1) - (d_left + d_right).
Alternatively, = x + (d_left + d_right)*(x - 1) - (d_left(d_left+1)+d_right(d_right+1))/2 + (n-1).
Because x*(1 + d_left + d_right) - (d_left + d_right) = x + (d_left + d_right)(x - 1). So total = x + (d_left + d_right)(x - 1) - (d_left(d_left+1)+d_right(d_right+1))/2 + (n-1). Check: Expand: x + (d_left+d_right)(x-1) - ... + (n-1) = x + (d_left+d_right)x - (d_left+d_right) - ... + (n-1) = x(1+d_left+d_right) - (d_left+d_right) - ... + (n-1). Then we have to add leftover ones? Wait earlier we had total = x*(1 + d_left + d_right) - (d_left(d_left+1)+d_right(d_right+1))/2 + (n-1) - (d_left + d_right). That matches because we have -(d_left+d_right) in both expressions. Yes, it's consistent.
Simplify further: total = (n-1) + x + (d_left+d_right)*(x-1) - (d_left(d_left+1)+d_right(d_right+1))/2.
That's fine.
We could also compute by summing arithmetic sequences: The pyramid gives values: on left, if d_left = left_len, then it's full descending from x-1 down to x-left_len, and then maybe 1's if left_len < x-1? Actually careful: If left_len >= x-1, then d_left = x-1, meaning we have descending from x-1 down to 1, covering exactly x-1 left positions, and the remaining left positions (left_len - (x-1)) are forced to be 1 (since they are further away). If left_len < x-1, then d_left = left_len, meaning we have descending from x-1 down to x-left_len (which is >1), and there are no extra 1's on left because we covered all left positions; but then the smallest left value is x-left_len, which may be >1. But note that if left_len < x-1, the condition does not require that we have 1's on the left; we just have decreasing values as far as we can, and because there are no more beds, it's fine. So indeed, the minimal sum uses the smallest possible values: each bed gets max(1, x - distance). So this formula is correct.
Now we need to check for overflow in computation of terms like d_left(d_left+1)/2: d_left can be up to 1e9, product up to 1e18, still fine for 64-bit.
Now we need to be careful about using Python's integer which is unlimited, so fine.
Thus solution: binary search for maximum x in [1, m] such that minPillows(x) <= m.
But wait, is it possible that for some x, minPillows(x) <= m but we cannot achieve exactly m because the achievable sums might have gaps? Let's think about. Starting from the minimal configuration, we can add pillows one by one to the leftmost bed (or any bed) until we reach the maximal configuration. Because we can always increment a bed by 1 as long as after increment it does not violate the constraints. However, if we increment a bed that is part of the pyramid, we might need to increment neighbors to keep differences ≤1? But we can increment the bed and also adjust neighbors accordingly. This might require incrementing multiple beds at once to keep constraints, which could cause the sum to increase by more than 1. But is it possible to increase sum by exactly 1? Consider the minimal configuration: all differences are either 0 or 1. If we try to add one pillow to a bed that is not at the maximum allowed for that position (with respect to neighbors), we need to check if that increment alone keeps differences ≤1. If it does, then sum increases by 1. If not, we may need to increment neighbors too, which would increase sum by more than 1. So there might be gaps: some total sums may not be achievable.
But typical reasoning in such problems: Since we can always add pillows to the beds that are at the far ends (the ones that have value 1 and have neighbor also 1 or 2?), we can add one pillow to such a bed without violating constraints because its neighbor is either 1 or 2. Let's analyze thoroughly.
We need to ensure that for any integer t between S_min and S_max, there exists a configuration with sum = t and a_k = x. I suspect it's true because the set of configurations forms a kind of integer lattice that is connected via elementary moves of adding 1 to a bed that is not "blocked". But to be rigorous, we could rely on known solutions for this problem (it's a Codeforces problem, and the solution is binary search on answer using minimal sum condition). So it's accepted.
Nevertheless, let's reason: The minimal configuration is as described. The maximal configuration (with a_k fixed) is the one where we set values as high as possible: for left side, a_{k-d} = x + d (if we increase away from k). But note that this maximal configuration might violate the condition that a_k is not the maximum? Actually it's okay. But does this configuration satisfy the condition? Yes, because each step increases by exactly 1, so differences are exactly 1, allowed. So both extremes are valid.
Now, can we move from minimal to maximal by a sequence of increments, each step increasing the sum by exactly 1? Consider the set of possible values for each position: For each position i, its value must be within an interval determined by the peak and the edges? Actually we can think of independent variables? Let's attempt to prove by construction: Starting from minimal, we can always add a pillow to the leftmost bed (position 1) until it reaches its maximum. At each increment of position 1 by 1, we must check that it does not create a difference >1 with position 2. Initially, position 1 is either 1 or maybe larger? In minimal config, leftmost is either 1 (if left_len >= x-1) or some value >1 (if left_len < x-1). Actually if left_len < x-1, then the leftmost is x - left_len, which is >1. Its neighbor to the right is x - (left_len-1) (if left_len>0) which is exactly 1 higher. So difference is 1. If we increase the leftmost by 1, it becomes either 2 or x-left_len+1. Its neighbor is x-(left_len-1) = x-left_len+1? Actually neighbor: for left_len = L, positions: index k-L (leftmost) has value x - L; index k-L+1 has value x - (L-1) = x - L + 1. So the neighbor is exactly 1 higher than leftmost originally. If we increase leftmost by 1, then leftmost becomes equal to neighbor, difference 0, allowed. So it's safe. So we can increase leftmost up to the value of its neighbor. But if we want to increase leftmost further, we would need to also increase the neighbor to maintain difference ≤1? Actually if leftmost becomes equal to neighbor, then to increase leftmost again, we would need to increase neighbor as well, otherwise leftmost would be 1 more than neighbor? Wait: After leftmost equals neighbor, if we increase leftmost by 1, leftmost becomes neighbor+1, difference 1, which is allowed. So that's also allowed. But careful: The condition is that any hobbit gets hurt if he has at least two pillows less than some neighbor. So if leftmost is neighbor+1, then neighbor has exactly 1 less, which is okay. So leftmost can be larger than neighbor. Actually originally neighbor is larger, but after increments leftmost can become larger, as long as difference ≤1. So it's fine. However, there is a maximum that leftmost can attain, which is limited by the fact that we have to maintain differences all the way to the peak. If leftmost becomes too large, then the difference between leftmost and its neighbor could become >1 if we don't adjust neighbor. But we can also increase neighbor. So to increase leftmost beyond a certain point, we might need to increase neighbor as well, which would increase sum by more than 1. But we can still increase sum by 1 by choosing to increase a bed that is currently at a "local minimum" where both neighbors are either equal or higher? Actually we can always increase a bed that is not at its maximum possible value under the current configuration, while keeping others fixed, as long as after increment it doesn't exceed neighbor+1. So if a bed is less than its right neighbor +1 and less than its left neighbor +1, we can increment it by 1. In the minimal configuration, many beds are at the lower bound; but if we increment a bed in the middle, it might become equal to its higher neighbor? That's allowed. Or it might become 1 more than its lower neighbor? That's also allowed as long as the lower neighbor is not more than 1 less? Actually if we increase a bed that is currently equal to its right neighbor (which is lower or equal), then after increment it becomes right neighbor+1, diff=1, allowed. So it seems many increments are possible individually.
But is there any situation where no single bed can be incremented without breaking constraints? Possibly if all beds are at their maximum allowed values relative to their neighbors, i.e., each bed is exactly 1 more than at least one neighbor? Actually maximum configuration is where each bed is as high as possible given the fixed a_k. In that configuration, on the left side, we have a_{k-d} = x + d. For d from 0 to L. At the leftmost, there is no left neighbor, but its right neighbor is x+(L-1). The leftmost is x+L. Difference = 1, so it's at its maximum? Could we increase leftmost further? If we increase leftmost to x+L+1, difference with right neighbor becomes 2, not allowed unless we also increase the right neighbor. But if we increase right neighbor too, we propagate. So that would require multiple increments. So in the maximal configuration, no single bed can be incremented by 1 without violating constraints unless we increment a whole suffix. So the maximal configuration is indeed a local maximum where no single increment is allowed.
Now, are there integer sums between S_min and S_max that are not achievable? This is reminiscent of the fact that the set of possible sums is an interval of integers. Because we can consider the following: Let f be a function from configurations to sum. The configuration space is the set of integer vectors satisfying constraints. This set is a distributive lattice under componentwise min and max? Actually the constraints are linear inequalities: a_i ≥ 1, |a_i - a_{i+1}| ≤ 1. This describes a polytope that is integral? Not necessarily, but we only need integer solutions. The set of integer solutions is all integer points inside that polytope. The sum is a linear function. The minimum and maximum are attained at some vertices. The integer points might not be convex, but due to the structure (it's a network flow-like constraints), the set might be totally unimodular? Possibly it's a kind of "M-convex" set. But simpler: We can argue that we can always adjust from min to max by a sequence of moves that each increase sum by 1, by always incrementing the leftmost bed until it reaches its max, then the next, etc. Let's attempt to construct a process:
Start from minimal config. Let’s denote arrays a. We'll aim to reach a target configuration that is some intermediate sum. Actually, we can treat the process of adding pillows as filling from the edges inward. But maybe we can simply note that we can increase any "valley" or "flat" part gradually. Since the constraints only bound differences, and we have no upper bound other than those imposed by the fixed a_k and the ends, we can think of each configuration as determined by the values at the two ends? Not exactly.
Nevertheless, the standard solution for this problem uses the binary search on answer with minimal pillows condition, and it's accepted. So it's safe.
One more nuance: In the minimal sum calculation, we used the condition that we can set a_i = max(1, x - distance). That indeed gives the smallest possible sum while keeping a_k = x and satisfying constraints. But is it always valid? Yes, because we need a_i >= 1 and |a_i - a_{i+1}| ≤ 1. The construction with a_i = max(1, x - |i-k|) satisfies: For adjacent i,i+1, consider their distances to k: if both are within the pyramid, their values differ by 1. If one is within and the other is outside (distance > x-1), then the inside value is 1 (since if distance = x-1, value =1; actually if distance = x-1, value=1, and distance = x gives 1 as well? Let's see: max(1, x - (x-1)) = 1, and max(1, x - x) = 1. So at the boundary where distance = x-1 and x, both are 1, so difference 0. If distance = x-1 (value=1) and distance = x (value=1), both 1. So okay. If the pyramid doesn't extend to the edge because left_len < x-1, then all left positions are covered, and the leftmost value is x-left_len, which is >1. Its left neighbor doesn't exist. So the constraints only between existing beds. For leftmost and its right neighbor: leftmost value = x-left_len, neighbor = x-(left_len-1) = x-left_len+1. Difference=1, okay. So the construction is valid. And it's minimal because any increase would raise sum.
Thus condition is correct.
Now implement.
We need to compute d_left = min(k-1, x-1), d_right = min(n-k, x-1). Then S = x + d_leftx - d_left(d_left+1)//2 + d_rightx - d_right(d_right+1)//2 + ( (k-1) - d_left ) + ( (n-k) - d_right ).
But careful: (k-1) and (n-k) might be large. Use Python ints.
Alternatively, we can compute as:
S = x
S += d_left * x - d_left*(d_left+1)//2
S += d_right * x - d_right*(d_right+1)//2
S += (k-1 - d_left) + (n-k - d_right)
Return S.
We should also consider if x=1, then d_left = min(k-1,0)=0, d_right = min(n-k,0)=0, S = 1 + 0 + 0 + (k-1)+(n-k) = 1 + (n-1) = n. Correct.
Now binary search boundaries: low = 1, high = m (since m≥n). While low < high: we need to find max feasible x. Usually we set mid = (low+high+1)//2 to avoid infinite loop. If check(mid) (i.e., S_min(mid) <= m), then low = mid, else high = mid-1. Finally output low.
Check for large values: x can be up to m, but S_min(x) can exceed m for x close to m. So binary search works.
Now test with given examples.
Example 1: n=4,m=6,k=2 -> low=1,high=6.
mid=3 -> S_min(3)=8>6 -> high=2.
mid? Actually loop: low=1,high=6, mid=(1+6+1)//2=4? Wait typical: while low<high: mid = (low+high+1)//2; if feasible(mid): low=mid; else: high=mid-1. So first mid = (1+6+1)//2=4. Check x=4: compute d_left = min(1,3)=1; d_right = min(2,3)=2; S_min= x(1+1+2)=44? Let's compute: 4 + (14 -1) + (2*4 -3) + (1-1)+(2-2) = 4 + (4-1=3) + (8-3=5) +0+0 =12? Actually 4+3+5=12. So 12>6, not feasible, so high=3.
Now low=1,high=3, mid=(1+3+1)//2=2.5 floor=2? Actually (1+3+1)//2=5//2=2. Check x=2: S_min=5 <=6 -> low=2. Now low=2,high=3? Actually after setting low=2, check loop condition low<high? 2<3 true, so continue. mid=(2+3+1)//2=6//2=3. Check x=3: S_min=8>6 -> high=2. Now low=2,high=2, loop ends. Output 2. Good.
Example 2: n=3,m=10,k=3. low=1,high=10. mid=(1+10+1)//2=6. x=6: d_left=min(2,5)=2, d_right=0; S_min = 6 + (26 - 23/2=12-3=9) + 0 + (0)+(0) = 6+9=15>10 => high=5. mid=(1+5+1)//2=3? Actually low=1,high=5, mid= (1+5+1)//2=7//2=3. x=3: d_left=min(2,2)=2, S_min=3 + (23-3=6-3=3) =6? Wait compute: 3 + (23 - 3) = 3+ (6-3)=6; plus leftover? d_left=2, left_len=2, so leftover=0; S_min=6 <=10 -> low=3. Now low=3,high=5, mid=(3+5+1)//2=9//2=4. x=4: we computed S_min=9 <=10 -> low=4. low=4,high=5, mid=(4+5+1)//2=10//2=5. x=5: S_min=12>10 -> high=4. loop ends, output 4. Good.
Example 3: n=3,m=6,k=1: low=1,high=6. mid=4? Actually (1+6+1)//2=4. x=4: d_right=min(2,3)=2; S_min = 4 + (24 - 3 =8-3=5) + (0) + (leftover 0) =9? 4+5=9 >6 -> high=3. low=1,high=3, mid= (1+3+1)//2=2? 5//2=2. x=2: d_right=min(2,1)=1; S_min = 2 + (12 -1 =2-1=1) + ( (2-1)=1 )? Wait compute: d_right=1, right_len=2, so leftover = right_len - d_right = 2-1=1. So S_min = 2 + (12 - 1) + (0) + (0? Actually we have to add leftover: (n-k - d_right) = 2-1=1, plus (k-1 - d_left)=0. So S_min = 2 + (2-1)=1? Actually careful: S = x + d_leftx - L(L+1)/2 + d_rightx - R(R+1)/2 + (k-1-d_left)+(n-k-d_right). Here k=1 => left_len=0 => d_left=0. So S = 2 + 0 + (12 - 12/2? Actually R=1 => d_rightx = 2, R(R+1)/2=1 => so term =1) + (0) + (2-1)=1 => total = 2+1+1=4. So S_min=4 <=6 -> low=2. low=2,high=3, mid=(2+3+1)//2=6//2=3. x=3: d_right=min(2,2)=2; S_min = 3 + (2*3 - 3 =6-3=3) + 0 + (2-2)=0 => total 6 <=6 -> low=3. low=3,high=3, loop ends -> output 3. Good.
So binary search works.
Now, we need to implement solution in Python.
But note constraints up to 1e9, binary search about 30-31 iterations, fine.
One more nuance: Could it be that maximal x is greater than m? Obviously not, because x <= m. But maybe we can set x = m - (n-1) + something? But we already have high=m, which is safe. However, S_min(m) is huge, but check will fail early.
But we can also set a tighter high bound to avoid overflow (though not needed). But we could set high = m - (n-1) + 1? Actually x can be at most m - (n-1) + 1? Consider all others have 1, then Frodo can have m - (n-1). That's one possibility. But if others need more due to constraints, then Frodo must be less. So maximum x ≤ m - (n-1) + (some?) Actually minimum sum for others given Frodo has x is something; but if we want to maximize x, we set others to minimal. So the maximum x is when we allocate minimal to others, which is exactly S_min(x) must be ≤ m. So we are finding the largest x such that minimal total including x ≤ m. That x could be greater than m - (n-1) if others can be less than 1? No, others minimum is 1. So the total minimal for given x is at least 1*(n-1) + x = n-1+x. So condition n-1+x ≤ m => x ≤ m - (n-1). So indeed x cannot exceed m - (n-1). So we can set high = m - (n-1) + 1? Actually x max is m - (n-1). Because if x = m - (n-1) + 1, then even if all others are 1, sum would be (m - n + 1 + 1) + (n-1)*1 = m+1 > m. So indeed x ≤ m - (n-1). Since m≥n, m - (n-1) >=1. So we can set high = m - (n-1). This might be smaller and safe. But careful: if the constraints force some neighbors to have more than 1 even for minimal sum, then maybe x cannot be that high anyway. But using high = m is fine.
However, if we set high = m, then for large m and n small, x could be up to 1e9, but that's fine. But we might get overflow in languages with fixed-width ints if we compute S_min(m) which might be huge (like n up to 1e9, x up to 1e9, product 1e18). But as said, within 2^63-1. So it's safe. In Python it's fine.
But to be extra safe, we can implement the check with early termination: if we compute d_left*x or something, but since Python big ints, no worry.
Thus final solution:
def min_pillows(x):
left_len = k-1
right_len = n-k
dL = min(left_len, x-1)
dR = min(right_len, x-1)
total = x
total += dLx - dL(dL+1)//2
total += dRx - dR(dR+1)//2
total += (left_len - dL) + (right_len - dR)
return total
But careful: if x=1, then x-1=0, so dL=0, dR=0, total = 1 + 0 + 0 + (left_len) + (right_len) = 1 + n-1 = n. Works.
Now binary search.
Edge Cases: n=1. Then there is only one bed (k=1). The constraints: Only one hobbit, he gets all pillows, and no neighbor condition (since no neighbors). So maximum pillows Frodo can have is m. Let's test our formula: n=1, k=1, left_len=0, right_len=0. min_pillows(x) = x + 0 + 0 + 0 = x. So condition x ≤ m => max x=m. Binary search from 1 to m will find m. Good.
But if n=1, then m≥n => m≥1. Works.
Another edge: x could be large such that dL = left_len, dR = right_len, then min sum = x + left_lenx - left_len(left_len+1)//2 + right_lenx - right_len(right_len+1)//2 + (left_len - left_len) + (right_len - right_len) = x*(1+ left_len+right_len) - [left_len(left_len+1)+right_len(right_len+1)]//2 = n*x - [left_len(left_len+1)+right_len(right_len+1)]//2. This could be large.
Now we should also ensure that for large x, dL and dR are limited by left_len and right_len, not by x-1. So when x > left_len+1? Actually if x-1 >= left_len, then dL = left_len, meaning pyramid extends beyond left side? Actually if x-1 >= left_len, then the left side is fully covered by descending values from x-1 down to x-left_len, which might still be >1 if left_len < x-1. In that case, there are no leftover ones; all left positions get values >1. That's fine.
Now, is there any scenario where the minimal sum we computed is not actually achievable because of the condition at the boundaries? Let's double-check boundary case: Suppose left_len = 0 (k=1). Then there is no left side. The minimal configuration is a_k = x, and right side: for d=1..min(right_len, x-1) set a_{k+d}=x-d, and the rest (if any) set to 1. That's fine.
Now, what about the scenario where x is so small that x-1 is less than both left_len and right_len. Then both dL and dR are x-1. Then left side will have exactly x-1 beds with descending values, and the remaining left positions (left_len - (x-1)) are 1. That's valid.
Thus S_min(x) is correct.
Now, but is it always possible to achieve any total sum between S_min and S_max? Since we only need to check existence for a specific x, not for all sums. But our binary search only checks the condition S_min(x) <= m. If there is a gap and for some x, S_min(x) <= m but it's impossible to reach exactly m because all configurations with a_k=x have sum either ≤ some T < m or ≥ some T' > m, with a gap containing m, then our condition would incorrectly deem x feasible. So we need to ensure that if S_min(x) <= m, then there exists a configuration with sum exactly m and a_k = x. Is that always true? Let's think.
We can construct a configuration with sum exactly m by starting from the minimal configuration and adding the extra pillows (delta = m - S_min(x)) one by one in a controlled manner. As argued, we can always add pillows to some bed without breaking constraints until we reach a desired sum. But we must show we can add exactly delta pillows without overshooting or causing gaps.
Consider the following: The set of possible sums for a fixed x is all integers from S_min(x) to S_max(x). This is plausible because the configuration space is essentially the set of integer sequences (a_1,...,a_n) satisfying a_k = x, a_i >= 1, and |a_i - a_{i+1}| ≤ 1. This is a kind of "integer interval" in the sense of majorization? Alternatively, we can view it as: Starting from the minimal configuration, we can increment any "free" variable at the ends. Actually, we can model as each configuration corresponds to a "mountain" shape? Not necessarily, because we can have two peaks? But with a fixed a_k = x, the shape can vary. However, due to the constraints, the values are determined by the "slopes" from the peak. If we want to increase sum, we can increase some values on the sides. But can we increase sum by 1? Let's attempt to prove by constructing an explicit procedure: We'll add pillows one by one to the leftmost bed (position 1) as much as possible, but each addition might require eventually increasing its neighbor to maintain the condition if we exceed a certain threshold? But we can add to leftmost as long as after addition it is ≤ its neighbor+1. In minimal configuration, leftmost is either 1 or some value v (which is ≤ neighbor+1). Initially, it is exactly neighbor-1? Actually if leftmost is within the pyramid (i.e., left_len < x-1), then leftmost = x-left_len, neighbor = x-left_len+1, so leftmost = neighbor-1. So we can add 1 to leftmost: becomes equal to neighbor, difference 0, allowed. Add another 1: leftmost becomes neighbor+1, difference 1, allowed (since neighbor is not less by 2). So we can keep increasing leftmost until it reaches its maximum possible value? But is there an upper bound? The maximum possible for leftmost given a_k=x is x+ (k-1) (if we increase away from k). That is because to get leftmost high, we need to increase each step by 1 moving from k to leftmost. In the minimal configuration, leftmost is x - left_len if left_len < x-1, else 1. So leftmost can be increased up to x+left_len? Actually maximum is x+left_len, because we can increase by 1 each step moving left from k. So the difference between max and min for leftmost is at most (x+left_len) - (max(1, x-left_len)). That's potentially large. But can we increase leftmost one by one without touching other beds? Let's test: Suppose we have leftmost = L, its right neighbor = N. The constraints require |L - N| ≤ 1. If we increase L by 1, we need to ensure that new L' = L+1 satisfies |L' - N| ≤ 1. That is, L+1 ≤ N+1 always true; but we need L+1 ≥ N-1? Actually condition is both directions: L' - N ≤ 1 and N - L' ≤ 1. So we need N - (L+1) ≤ 1 => N ≤ L+2. Since originally |L - N| ≤ 1, we have N ∈ [L-1, L+1]. So after increment, L+1 is such that: If N = L+1 originally, then N - (L+1) = 0 ≤ 1; L+1 - N = 0 ≤ 1, ok. If N = L originally, then N - (L+1) = -1 (absolute 1) ≤1; L+1 - N =1 ≤1, ok. If N = L-1 originally, then N - (L+1) = -2 (abs 2) >1, not ok. So the problematic case is when leftmost is greater than its neighbor? Actually in the minimal configuration, leftmost is always ≤ neighbor because it's descending from peak? Let's check: For left side, as we move left away from k, the values decrease (or stay constant) in the minimal configuration. So leftmost ≤ neighbor? Actually for left side: a_{k-1} = x-1, a_{k-2} = x-2, ... So as index decreases (moving left), values decrease. So leftmost (farthest left) is the smallest. So leftmost ≤ neighbor? Yes, neighbor (one step right) is larger. So in minimal config, N = L+1 (since descending by 1 each step) if within pyramid; or if leftmost is 1 and neighbor is also 1 (if both are 1) then N = L; or if leftmost is 1 and neighbor is 2 (at boundary of pyramid) then N = L+1. So N is either L or L+1. So the case N = L-1 does not occur in minimal config. So we can always increase leftmost by 1 and still have |L+1 - N| ≤ 1, because if N = L, then diff=1; if N = L+1, then diff=0. So safe.
But after several increments, leftmost may become larger than neighbor. For example, start with L=1, N=2 (boundary case). After increment, L=2, N=2, diff=0. Increment again: L=3, N=2, diff=1 (allowed). So still allowed because difference is 1. After that, L=4, N=2 would give diff=2 not allowed. But before we get to L=4, we would have to also increase N to keep diff ≤1? But can we increase L to 4 without touching N? Let's see: L=3, N=2 diff=1. If we increment L to 4, then diff becomes 2, not allowed. So we cannot increment L to 4 unless we also increment N. So the move from (L=3,N=2) to (L=4,N=2) is invalid. But we could instead increment N to 3, then L could become 4 later. So to increase L further beyond N+1, we need to increase N as well. This suggests that we cannot always increase sum by exactly 1 using only a single bed; sometimes we need to increase two beds simultaneously, which would increase sum by at least 2. Could that cause gaps? For example, suppose we have configuration where leftmost=3, neighbor=2, and all other beds are at their maximum possible values? Actually we could also increment N instead of L, which increases sum by 1, but that doesn't directly increase L. But we want to achieve any total sum, not necessarily by a fixed order. The question: Starting from minimal config, can we reach any integer total sum up to max? I think yes because we can "smoothly" adjust. For instance, we can first increase leftmost as much as possible without needing to increase neighbor, until L = N+1? Actually the maximum L can be without increasing N is N+1? Let's derive: If L and N satisfy |L-N|≤1, then L can be at most N+1. If we want L to be N+2, we need to increase N first so that N becomes at least L-1. So to increase L by 2, we might need to increase N by 1 as well, total increase 3. But maybe we can increment N first, then L. The sequence: current (L,N) = (3,2). Increase N to 3 (sum+1). Now (3,3). Then increase L to 4 (sum+1) -> (4,3) diff=1, sum+2 from original. So to go from (3,2) to (4,3) we increased sum by 2, which is okay; we didn't need to increase by 3. But what about going from (3,2) to (4,2) is impossible. But the total sum 1 higher than (3,2) might be achieved by increasing some other bed, not necessarily L. For example, from (3,2) we could increase some other bed like the second neighbor, etc. So maybe every integer sum is reachable. But is there a scenario where the total sum can only be even? Let's attempt a small example to see.
Consider n=2, k=1 (or k=2). Actually simpler: n=2, k=1. Then we have a_1 = x (Frodo), a_2 must satisfy |a_1 - a_2| ≤ 1, a_2 ≥ 1. So a_2 ∈ [max(1, x-1), x+1]. The minimal sum for given x is: a_2 = max(1, x-1). So S_min = x + max(1, x-1). The maximal sum is x + (x+1) = 2x+1. But note that the possible values of a_2 are integers from max(1, x-1) to x+1 inclusive. So possible total sums are x + t, where t runs over that interval. So sums are consecutive integers. So for n=2, no gaps.
For n=3, with k=2 (middle). Let's analyze: a_1, a_2=x, a_3. Constraints: |a_1 - x| ≤ 1, |x - a_3| ≤ 1, and also |a_1 - a_2|? Already covered. Actually only adjacent constraints: a_1 and a_2, a_2 and a_3. No direct constraint between a_1 and a_3. So a_1 can vary independently of a_3 within [max(1, x-1), x+1]. Similarly a_3 within [max(1, x-1), x+1]. So the sum is x + a_1 + a_3, where each a_i can vary in an interval of length at most 2? Actually if x≥2, then a_1 ∈ [x-1, x+1] (since ≥1 automatically if x≥2). So three possible values: x-1, x, x+1. Similarly a_3. So total sum can be x + (x-1)+(x-1) = 3x-2, up to x+(x+1)+(x+1)=3x+2. Are all integers between achievable? Let's test x=2: intervals: a1∈[1,3], a3∈[1,3]. So sums from 2+1+1=4 to 2+3+3=8. All integers 4..8 are achievable? Let's list: 4 (1,1), 5 (2,1) or (1,2), 6 (2,2) or (1,3) etc, 7 (3,2) or (2,3), 8 (3,3). Yes all. For x=1: a1∈[1,2]? Actually a1 must be ≥1 and |a1-1|≤1 => a1∈[0,2] but ≥1 => [1,2]. Similarly a3∈[1,2]. Sums: 1+1+1=3, 1+1+2=4, 1+2+1=4, 1+2+2=5. So achievable sums: 3,4,5. Missing? 3,4,5 are consecutive. So fine.
For n larger, likely the set of sums is an interval. Because the constraints are essentially that each a_i is within a range that depends linearly on its distance from k, and the ranges for different i are independent except through the adjacency constraints that couple them, but the coupling may restrict the joint distribution. However, due to the structure of a line graph with constraints |a_i - a_{i+1}| ≤ 1, fixing a_k = x yields that for any i, a_i can vary within [L_i, U_i] where L_i = max(1, x - |i-k|) (the minimal) and U_i = x + |i-k| (the maximal). But not all combinations of values within these ranges are allowed because of the chain constraints. However, I suspect the set of achievable sums is indeed all integers between S_min and S_max. This is a property of "M-convex" sets on a path? Actually it's known that for such difference constraints, the set of feasible vectors forms a "distributive lattice" under componentwise min and max, and the sum is a separable convex function? Not sure. But we can argue by induction: For a given k, we can view the left side and right side as independent "mountain" shapes. Actually, the constraints on left side are: a_k = x, and for i from k-1 down to 1, we have a_i ≥ 1, and |a_i - a_{i+1}| ≤ 1. This is equivalent to a_i ∈ [max(1, a_{i+1} - 1), a_{i+1} + 1]. So starting from a_k, we can choose a_{k-1} in that range, then a_{k-2} based on a_{k-1}, etc. So the left side is a kind of path where each step can go up or down by at most 1. The right side similar. So the set of possible left side configurations, given a_k = x, is all sequences satisfying these constraints. The minimal left sum (given a_k) is achieved by always taking the minimal allowed value at each step (i.e., a_{i} = max(1, a_{i+1} - 1)), which gives the descending pyramid. The maximal left sum is achieved by always taking the maximal allowed (a_i = a_{i+1} + 1). Now, can we achieve any sum between? I think yes, because we can gradually "raise" the values from the minimal to maximal by a process of increasing one element at a time, and at each step we can increase sum by exactly 1. This is akin to having a "mountain" that can be inflated. In such a chain, the set of achievable sums might be contiguous. Let's try to prove for the left side alone (fixing a_k). Consider we have a chain of length L = k-1, with endpoint a_{k-L} (leftmost) free except constraints. We want to see if for any integer s between S_min_left and S_max_left, there exists a left configuration with sum s (plus a_k). This is similar to the number of ways to walk from a_k to some value at step L, with step differences ±1 or 0? Actually the constraints allow a_i to be either a_{i+1} - 1, a_{i+1}, or a_{i+1} + 1, but also must stay ≥ 1. Starting from a_{k}=x, we choose a_{k-1}, then a_{k-2}, etc. The sum of the left side is the sum of these L values. The minimal sum is when we always choose the smallest allowed: a_{i} = max(1, a_{i+1} - 1). The maximal sum is when we always choose a_i = a_{i+1} + 1. The question: can we achieve any intermediate sum? This is like we have a sequence where each variable is bounded between two monotonic functions. I think yes, because we can start from minimal and then increase the leftmost by 1, then propagate as needed. Let's test a small case L=2, x=3. Minimal left: a_{k}=3, a_{k-1}=2, a_{k-2}=1 => sum left = 3? Actually left sum includes a_{k-1}+a_{k-2}? Wait left side excludes a_k. So left sum = a_{k-1}+a_{k-2} = 2+1=3. Maximal left: a_{k-1}=4, a_{k-2}=5? But careful: a_{k-1} max is x+1=4, then a_{k-2} max is a_{k-1}+1 =5. So left sum max = 4+5=9. Now, are all integers 3..9 achievable? Let's enumerate possibilities: a_{k-1} can be 2,3,4 (since |a_{k-1} - 3| ≤ 1 => 2,3,4). For each, a_{k-2} must satisfy |a_{k-2} - a_{k-1}| ≤ 1 and ≥1. So:
- If a_{k-1}=2: then a_{k-2} ∈ [1,3] => left sums: 2+1=3, 2+2=4, 2+3=5.
- If a_{k-1}=3: then a_{k-2} ∈ [2,4] => sums: 3+2=5, 3+3=6, 3+4=7.
- If a_{k-1}=4: then a_{k-2} ∈ [3,5] => sums: 4+3=7, 4+4=8, 4+5=9.
Thus achievable sums: 3,4,5,6,7,8,9. All integers. Good.
For L=3, x=3. Minimal: a_{k-1}=2, a_{k-2}=1, a_{k-3}=1? Wait careful: Starting from a_k=3, minimal: a_{k-1}=max(1,3-1)=2; a_{k-2}=max(1,2-1)=1; a_{k-3}=max(1,1-1)=1 (since 0->1). So left sum = 2+1+1=4. Maximal: a_{k-1}=4, a_{k-2}=5, a_{k-3}=6 => sum=4+5+6=15. Can we get sum=5? Possibly. Let's check some combos: a_{k-1}=2, then a_{k-2} can be 1,2,3; for each a_{k-2}, a_{k-3} has range. Might cover all. I'd guess yes.
Thus it seems plausible that the sum can take all integer values between min and max.
Moreover, the right side is independent (except they share a_k). So the total sum is left_sum + x + right_sum. Since left_sum and right_sum can each independently achieve all integers in their ranges (and they are independent because the constraints on left and right don't interact except through a_k fixed), the total sum can achieve all integers from S_min to S_max. Actually the independence is: left side configuration only depends on a_k, right side only depends on a_k, and they don't affect each other. So if left_sum can achieve any integer between L_min and L_max, and right_sum any integer between R_min and R_max, then the total sum can achieve any integer between L_min+R_min+x and L_max+R_max+x. However, is the set of sums the full Cartesian product? Not necessarily; but if each side can achieve all integers individually, then for any target total S, we can choose left_sum = some integer l, and right_sum = S - x - l. We need to ensure l is achievable on left and S-x-l is achievable on right. Since the left range is contiguous and the right range is contiguous, the set of sums is the Minkowski sum of two intervals, which is also an interval (the sum of two integer intervals is an interval of integers, provided there is no gap). Specifically, if left_sum can be any integer in [Lmin, Lmax] and right_sum any integer in [Rmin, Rmax], then total sum can be any integer from Lmin+Rmin+x to Lmax+Rmax+x. Because for any T in that range, we can pick l = max(Lmin, T - x - Rmax) and then adjust? Actually to be precise, the set {l + r : l ∈ [Lmin,Lmax], r ∈ [Rmin,Rmax]} = [Lmin+Rmin, Lmax+Rmax] (since intervals are integer intervals). This holds because intervals are contiguous. So yes, total sum can achieve all integers between the min and max.
Thus, as long as each side individually can achieve all integer sums in its range, the total is continuous. We argued for a single side via a walk; it seems plausible. Alternatively, we can note that the set of possible sequences on a path with fixed endpoint is a "polymatroid"? Actually it's a distributive lattice, and the sum is a linear function; the set of achievable sums is an interval because the lattice is "consecutive". I'm convinced.
Therefore, condition S_min(x) ≤ m is sufficient.
Thus binary search solution is correct.
Now we implement.
But we need to be careful about Python recursion? Not needed.
Time complexity: O(log m) per test.
Now let's handle input: one line with three integers. Output single integer.
We'll code as:
def can(x):
left_len = k - 1
right_len = n - k
dL = min(left_len, x - 1)
dR = min(right_len, x - 1)
total = x
total += dL * x - dL * (dL + 1) // 2
total += dR * x - dR * (dR + 1) // 2
total += (left_len - dL) + (right_len - dR)
return total <= m
But careful: x - 1 can be negative if x=0, but x>=1, so fine.
Now binary search:
low, high = 1, m
while low < high:
mid = (low + high + 1) // 2
if can(mid):
low = mid
else:
high = mid - 1
print(low)
Check with examples: works.
Now test additional cases:
Case n=1,m=5,k=1: can(1)=1<=5, can(5)=5<=5? Actually x=5: total=x=5 <=5, so feasible; low becomes 5; output 5.
Case n=5,m=5,k=3: each must have at least 1, total 5, so all 1. Condition differences? With all 1, differences 0, ok. Frodo gets 1. So max x=1. Our binary search: low=1,high=5. mid=3: compute S_min(3): left_len=2,right_len=2, dL=min(2,2)=2,dR=2; total=3 + 23-3 + 23-3 =3+3+3=9? plus leftover 0 ->9 >5 => not feasible, high=2. mid=(1+2+1)//2=2; x=2: dL=min(2,1)=1,dR=1; total=2 + (12-1)=1? Actually compute: total =2 + (12 -1) + (1*2 -1) + (2-1)+(2-1) =2 + (2-1=1) + (2-1=1) +1+1 =2+1+1+1+1=6 >5? Wait 2+1+1=4, plus 1+1=2 =>6. So 6>5 => not feasible, high=1. Output 1. correct.
Case n=5,m=10,k=3. Let's manually think: Could Frodo get 3? Minimal sum for x=3: left_len=2,right_len=2, x-1=2 => dL=2,dR=2; total=3 + 23-3=3+3=6? Actually 23-3=3, so left sum=3, right sum=3, plus x=3 =>9, leftover 0 =>9 <=10. x=4: dL=min(2,3)=2,dR=2; total=4 + (24-3=5) + (24-3=5) =4+5+5=14 >10. So max x=3? But maybe x=4 could be possible if we reduce others? But minimal sum for x=4 is 14, which is >10, so not possible. So answer 3. Check if we can achieve sum 10 with x=3: minimal 9, need 1 extra. Can we add 1 pillow to some bed without violating constraints? For instance, increase a_1 from 1 to 2? But in minimal config for x=3: values: left: a_2? Actually beds: index 1,2,3,4,5; k=3. Pyramid: a_3=3; a_2=2; a_4=2; a_1=1; a_5=1. Sum=3+2+2+1+1=9. Adding 1 to a_1 makes it 2, difference with a_2 becomes 0, ok. Sum=10. So feasible. So answer 3.
Thus correct.
Now we need to consider potential overflow in languages like C++ but in Python it's fine.
One more nuance: For very large n and m, the binary search might run up to 60 iterations if we set high=m which could be up to 1e9, log2(1e9) ~30, fine.
But note: m could be as high as 1e9, n up to 1e9, but x may be up to about 1e9, dL and dR up to 1e9, multiplication may produce up to 1e18, still fine.
Implementation: We'll parse input using sys.stdin.read().
We'll define a function minimal_pillows(x) that returns the minimal total pillows required.
One more edge: When x = 1, dL = min(left_len, 0) = 0, dR = 0. The formula total = 1 + 0 - 0 + 0 - 0 + left_len + right_len = n, as expected.
All good.
Now, is there any scenario where x-1 can be negative? No because x>=1.
Now final solution is straightforward.
But wait, there is a nuance: The problem statement says: "any hobbit gets hurt if he has at least two pillows less than some of his neighbors have." This could be interpreted as: if a hobbit has x and a neighbor has y, and x ≤ y-2, then he is hurt. It does not say that the neighbor is hurt if the neighbor has at least two less. So it's only one-directional? Actually it says "any hobbit gets hurt if he has at least two pillows less than some of his neighbors have." So for each hobbit, we look at his own pillow count relative to each neighbor. If his count is at least two less than a neighbor's, he's hurt. So if a_i is much larger than a_{i+1}, then a_{i+1} might be hurt if a_{i+1} ≤ a_i - 2. But a_i is not hurt because it is not less. So the condition is not symmetric; it's directed. However, does this change the constraints? Let's re-express: For every i, for every neighbor j (i-1 or i+1), we must not have a_i ≤ a_j - 2. Equivalently, a_i ≥ a_j - 1? No, we need to ensure that a_i is not at least two less than neighbor j, i.e., a_i > a_j - 2, i.e., a_i ≥ a_j - 1. Because if a_i = a_j - 2, then a_i = a_j - 2, so a_i ≤ a_j -2, so hurt. So we need a_i ≥ a_j - 1. This is equivalent to a_i - a_j ≥ -1, i.e., a_j - a_i ≤ 1. But it does not restrict a_i - a_j being large. For instance, if a_i = 10 and a_{i+1}=1, then a_{i+1} = 1 ≤ 10-2=8, so a_{i+1} is hurt. So that's not allowed. So to avoid any hurt, we must have for all adjacent pairs, the smaller must be at most 1 less than the larger. That is exactly the condition that the absolute difference ≤ 1? Let's check: If a_i = 5, a_{i+1}=7, then difference =2. Then a_i =5 ≤ 7-2=5, so a_i is hurt because 5 ≤ 5? The condition is "at least two pillows less", i.e., a_i ≤ a_j - 2. Here a_i=5, a_j=7, 5 ≤ 5? Yes, 5 ≤ 5 is true, so a_i is hurt. So if difference is exactly 2, the smaller is hurt. So difference of 2 is not allowed. If a_i = 5, a_{i+1}=6, difference=1, then 5 ≤ 5? Actually 5 ≤ 6-2=4? 5 ≤ 4 is false, so not hurt. Also a_{i+1} checks: 6 ≤ 5-2=3? false. So allowed. If a_i=6, a_{i+1}=5, similar: 5 ≤ 6-2=4? 5≤4 false; 6≤5-2=3 false. So allowed. If a_i=7, a_{i+1}=5, difference=2: the smaller is 5, check 5 ≤ 7-2=5 -> true, so 5 is hurt. So difference of 2 is not allowed regardless of direction. If difference >2, obviously not allowed. So the condition is indeed |a_i - a_{i+1}| ≤ 1. Because if absolute difference is 2 or more, the smaller one is hurt. So it's symmetric effectively. Thus our interpretation is correct.
Now, is there any nuance about "some of his neighbors" meaning if there exists a neighbor such that the condition holds, he's hurt. So it's enough that one neighbor has at least two more. So again it's symmetric.
Thus our model is correct.
Now we can produce final answer.
But I recall a known Codeforces problem: "Pillows" from Codeforces Round #... maybe it's problem 466A? Actually I'm not sure. But the solution is binary search as described.
Now let's write the solution.
We'll create a function:
def min_pillows(x):
left = k - 1
right = n - k
# effective spread
t = x - 1
dl = min(left, t)
dr = min(right, t)
total = x
total += dl * x - dl * (dl + 1) // 2
total += dr * x - dr * (dr + 1) // 2
total += (left - dl) + (right - dr)
return total
Then binary search.
Now, we need to consider that n and m can be up to 10^9, but k is within n.
Now final code in Python:
import sys
def main():
data = sys.stdin.read().strip().split()
if not data:
return
n, m, k = map(int, data)
# binary search
lo, hi = 1, m
while lo < hi:
mid = (lo + hi + 1) // 2
# compute minimal total needed for Frodo = mid
left_len = k - 1
right_len = n - k
t = mid - 1
dl = left_len if left_len < t else t
dr = right_len if right_len < t else t
# compute sum
total = mid
total += dl * mid - dl * (dl + 1) // 2
total += dr * mid - dr * (dr + 1) // 2
total += (left_len - dl) + (right_len - dr)
if total <= m:
lo = mid
else:
hi = mid - 1
print(lo)
if name == "main":
main()
Test with examples.
Now ensure variable names: In the binary search we used mid for x.
Potential off-by-one: In computing dl = min(left_len, t), but t = x-1. If x=1, t=0, dl=0, dr=0. Good.
Now note that when x-1 is very large, dl = left_len, dr = right_len. Then total = x + left_lenx - left_len(left_len+1)//2 + right_lenx - right_len(right_len+1)//2 + 0 = x + (left_len+right_len)x - (L(L+1)+R(R+1))/2 = nx - (L(L+1)+R(R+1))/2.
That can be compared to m.
Now we need to consider if m can be less than n? But given n ≤ m, so m≥n. So low=1 is always feasible.
Edge case: n=1, left_len=0, right_len=0, then dl=dr=0, total = mid, condition total <= m always true for mid up to m. Binary search yields m.
Now we can finalize.
But wait: The problem statement says: "n hobbits are planning to spend the night at Frodo's house. Frodo has n beds standing in a row and m pillows (n ≤ m). Each hobbit needs a bed and at least one pillow to sleep, however, everyone wants as many pillows as possible. Of course, it's not always possible to share pillows equally, but any hobbit gets hurt if he has at least two pillows less than some of his neighbors have."
Our goal: "Frodo will sleep on the k-th bed in the row. What is the maximum number of pillows he can have so that every hobbit has at least one pillow, every pillow is given to some hobbit and no one is hurt?" So we must allocate all pillows? It says "every pillow is given to some hobbit". So we must use all m pillows? Or just that we can't leave pillows unused? It says "every pillow is given to some hobbit". So we must distribute all pillows. So total sum must be exactly m. That's what we used.
Thus solution correct.
Now, is there any more optimal solution without binary search? Possibly we can solve a quadratic inequality. Because S_min(x) is piecewise linear-quadratic. But binary search is fine.
Now, ensure we are reading input properly: The input line contains three integers separated by spaces.
Now final answer.
But I should test more cases:
Case: n=100, m=100, k=50. Then minimal sum for x=1 is 100, so x=1 feasible. Can we have x=2? Compute: left_len=49,right_len=50, x-1=1, so dl=min(49,1)=1, dr=min(50,1)=1. total = 2 + (12 -1) + (12 -1) + (49-1)+(50-1) = 2+1+1+48+49=101 >100. So x=2 not feasible. So answer 1.
Case: n=100, m=1000, k=1. Then left_len=0, right_len=99. We want max x. Compute approximate: For x large, minimal sum = x + sum_{d=1}^{min(99,x-1)} (x-d) + (99 - dR)1. Actually right only. So total = x + (if x-1 >= 99) then dR=99, sum = 99x - 99100/2 = 99x - 4950; plus x = 100x -4950. This must be ≤ 1000 => 100x ≤ 5950 => x ≤ 59.5 => x=59 gives total 10059 -4950 = 5900-4950=950 ≤1000; x=60 gives 6000-4950=1050>1000. So max x=59? But also consider when x-1 < 99, i.e., x ≤ 99. For x=60, x-1=59 <99, so dR=59. Then total = x + dRx - dR(dR+1)/2 + (99-dR) = x + 59x - 5960/2 + (99-59) = 60x? Actually x=60, dR=59, total = 60 + 5960 - 5960/2? Wait compute properly: dR=59, so sum_{d=1}^{59} (x-d) = 59x - 5960/2 = 5960 - 1770 = 3540 -? Actually 5960=3540, 5960/2=1770, so that part = 3540 - 1770 = 1770. Then total = x + 1770 + (99-59)=40 => 60+1770+40=1870. That's much larger than 1000. But that contradicts the full coverage formula? Let's recalc: For x=60, x-1=59, dR=min(99,59)=59. So the right side: positions 2..100. The minimal values: for distance 1..59: 60-1=59, down to 60-59=1. So there are 59 positions with values from 59 down to 1. The remaining right positions: 99-59=40 positions get value 1. So total on right = sum_{d=1}^{59} (60-d) + 401 = (5960 - sum_{d=1}^{59} d) + 40 = (3540 - 5960/2) + 40 = (3540 - 1770) + 40 = 1770 + 40 = 1810. Then plus x=60 gives total = 1870. Indeed 1870 > 1000. So x=60 is not feasible. So indeed max x is less than 60. But earlier using full coverage formula for x=60 gave 100*60 -4950 = 6000-4950=1050, which is not matching 1870 because full coverage formula assumed dR=99 (i.e., x-1 >=99), but x=60 is not in that regime. So my earlier estimate for x=60 using full coverage was wrong because it applied only when x-1 >=99. So we need to binary search.
Let's compute actual max: For x=5: dR=min(99,4)=4; total = 5 + (45 - 45/2?) Actually 45 - 45/2? No: dR(dR+1)/2 = 45/2=10; so right sum = 45 -10 = 20-10=10; plus (99-4)=95; total right = 10+95=105; plus x=5 =>110. So total = 110 <=1000. So x can be higher. We can binary search, but it's okay.
Our algorithm will handle.
Now, just to be thorough, we should test with large values to ensure no overflow in Python: not an issue.
Now, maybe we can derive direct formula: x = ? But binary search is simpler.
Now, I'll consider potential pitfalls: When computing total, we should be careful that integer division is done correctly. Use // for integer division.
Now, we should also consider that the result must be integer.
Now, let's also test a scenario where k is at one end and x is large such that dL or dR = 0, and the other side is fully covered.
Example: n=10^9, m=10^18? But m up to 10^9, but actually m ≤ 10^9? Input says n ≤ m ≤ 10^9. So m max 10^9. So n max 10^9, m max 10^9. So x max around m - (n-1) which could be up to 10^9 but maybe less. So product n*x could be up to 10^9 * 10^9 = 10^18, still fine.
Now, implementing in Python, the binary search is fine.
Now, there is a known solution that uses formula to compute x directly: x = something like 1 + floor((m - n + something)/something). But binary search is safer.
Nevertheless, I can derive a direct formula for completeness but not needed.
But maybe we can improve: Since m,n up to 1e9, binary search 30-31 iterations is trivial.
Now, final solution: as described.
Now, code must be efficient.
Now, I will produce final answer.
But before finalizing, I want to ensure that our function for total does not double count anything. Let's double-check with small examples manually using code.
We can test with n=4,m=6,k=2 x=2: left_len=1,right_len=2, t=1, dl=1,dr=1. total = 2 + (12 -12/2?) Actually dl*(dl+1)/2 = 1*2/2=1, so term = 2-1=1. Similarly dr term =1. So total = 2+1+1 =4. Then add (left_len - dl)=0, (right_len - dr)=1 => total=5. Good.
Now for x=3: dl=1, dr=2? Actually t=2, left_len=1 -> dl=1, right_len=2 -> dr=2. total = 3 + (13 -1) = 3+2=5? Wait compute: dl term = 13 - 12/2 = 3-1=2; dr term = 23 - 2*3/2 =6-3=3; sum = 3+2+3=8; plus (left_len-dl)=0, (right_len-dr)=0 => total=8. Good.
Now for x=4: dl=1, dr=2 (since t=3, left_len=1 -> dl=1, right_len=2 -> dr=2). total = 4 + (1*4 -1) = 4+3=7? Actually dl term = 4-1=3; dr term = 8-3=5; sum=4+3+5=12; leftover 0 =>12. So all good.
Now for n=3,m=10,k=3 x=4: left_len=2,right_len=0,t=3, dl=min(2,3)=2, dr=0. total = 4 + (24 - 23/2)=4 + (8-3)=4+5=9; plus (left_len-dl)=0, (right_len-dr)=0 =>9. Good.
Now for n=3,m=6,k=1 x=3: left_len=0,right_len=2,t=2, dl=0, dr=2. total = 3 + (23 - 23/2)=3+(6-3)=3+3=6; plus leftover 0 =>6.
Now all correct.
Now, one more test: n=5,m=10,k=3 x=3: left_len=2,right_len=2,t=2, dl=2,dr=2. total = 3 + (23 - 3) + (23 -3) = 3+3+3=9; leftover 0 =>9. x=4: t=3, dl=2,dr=2; total = 4 + (24-3=5)+(24-3=5)=4+5+5=14; >10. So max=3. Good.
Now, is it possible that x can be 3 and we can achieve exactly sum 10? Yes, we gave example. So answer 3.
Now, check scenario where minimal sum equals m, answer is that x. If minimal sum less than m, answer might be higher than the x that gives minimal sum less than m? Actually we are searching for max x with minimal sum <= m. Since minimal sum is increasing in x (strictly increasing as x increases), the set of feasible x is an interval from 1 up to some maximum. So binary search works.
Now, ensure monotonicity: As x increases, the minimal sum S_min(x) increases. This is intuitive because if we increase the peak, we must increase at least the neighbors (they can't be lower than before due to constraints). More formally, from formula: S_min(x+1) > S_min(x). We can check: S_min(x) is piecewise quadratic but increasing. So binary search is valid.
Now, one more edge: When x is very large such that both sides are fully covered (i.e., x-1 >= left_len and x-1 >= right_len), then S_min(x) = nx - (left_len(left_len+1) + right_len*(right_len+1))/2. This is linear in x with slope n, so increasing.
Thus binary search works.
Now, code with while loop.
Now, potential improvement: Since m can be large but x max is around m - (n-1), we could set high = m - (n-1) + 1? But let's not.
Now, we need to produce answer as integer.
Now final solution ready.
But wait, there is a nuance: The problem might be from Codeforces and they expected answer to be computed with O(1) using formulas. However, binary search is acceptable given constraints 1e9 and log2(1e9)=30.
But we must consider time limit: typical Codeforces time limit 1s, Python with 30 iterations and simple arithmetic is fine.
Now, produce final answer.
But I'd like to test with extreme values:
n=10^9, m=10^9, k=1. Then we expect answer=1 because total m=n, so all must be 1. Our binary search: low=1, high=1e9. mid=500,000,000. Compute S_min(mid) will be huge because n*x is huge, > m, so will quickly narrow down. At each step, we compute dl, dr, etc. The arithmetic involves multiplication of numbers up to 1e9, which Python can handle quickly. The loop about 30 times, fine.
But one potential performance issue: In Python, multiplication of large ints (up to 1e18) is fine; it's not a big overhead.
Now, also note that we must use sys.stdin.read() for fast input.
Now, final code.
But before final, let's consider if there is any scenario where binary search might get stuck due to integer division? No.
Now, we should also consider that k can be 1 or n, which makes one side zero. Our code handles that because left_len = k-1 or right_len = n-k could be zero.
Now, final answer.
However, there is a known trick: compute x as 1 + (m - n) // something? But we stick with binary search.
Now, final answer:
We'll produce the code with appropriate comments.
Now, answer in the required format.
But the problem states: "Print single integer — the maximum number of pillows Frodo can have so that no one is hurt."
We'll output low.
Now, finalize.
I'll now produce the final output. ```python
import sys
def main() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
n, m, k = map(int, data)
# lengths of the left and right sides
left_len = k - 1
right_len = n - k
# binary search on the answer
lo, hi = 1, m
while lo < hi:
x = (lo + hi + 1) // 2
# minimal number of pillows needed if Frodo gets x
t = x - 1 # how far the pyramid can descend
dl = min(left_len, t) # left side covered by the pyramid
dr = min(right_len, t) # right side covered by the pyramid
total = x # Frodo himself
total += dl * x - dl * (dl + 1) // 2 # left descending part
total += dr * x - dr * (dr + 1) // 2 # right descending part
total += (left_len - dl) + (right_len - dr) # remaining beds get 1
if total <= m:
lo = x
else:
hi = x - 1
print(lo)
if name == "main":
main()