We need to solve problem: given initial array A of N integers (0 <= A[i] <= N? Actually constraints: 0 <= A[i] <= N? But problem statement says 0 <= A[i] <= N? It says: "0 <= A[i] <= N" maybe? Actually given: "0 <= A[i] <= N" in description? Let's see: "Next line contains an array A of N integers separated by spaces, the initial number of idlis served ( 0 <= A[i] <= N )". So each A[i] is between 0 and N inclusive. But N up to 3000. T around 20.
We have operation: while not all equal, pick max and min (any if multiple) compute R = ceil((P - Q)/2) where P is max, Q is min. Transfer R from max to min. Need number of steps until all equal, or -1 if impossible.
Observation: The operation modifies the multiset. It may be possible to simulate, but N up to 3000 and values small, but steps could be large? Since sum S of all elements is invariant? Actually sum is constant because we transfer from one to another. So if we want all equal, each must equal S/N. So S must be divisible by N. If not, impossible: output -1.
But also operation may not converge even if S divisible by N? Example given: N=2, A=[1,2], sum=3, not divisible by 2? Actually 3/2=1.5 not integer, so -1. But they gave -1. However, consider N=2, A=[0,2] sum=2, target=1. Let's simulate: P=2,Q=0,R=ceil((2-0)/2)=1. Transfer: => [1,1] done in 1 step. So it works. So condition sum divisible by N is necessary. But is it sufficient? Possibly yes, because the operation always reduces some measure? We need to check if there are cases where sum divisible but infinite loop? Possibly the given example shows -1 for N=2, [1,2] sum=3 not divisible so -1. So maybe -1 only when sum not divisible? But we need to confirm if any other condition leads to impossibility. Since we are only allowed to transfer from max to min, and always integer values, and the operation might oscillate? For N=2, sum divisible: say [0,2] works, [1,1] obviously works. [2,0] same. [0,4]? sum=4, target=2: P=4,Q=0,R=2 => [2,2] done. So works. So maybe sum divisible is sufficient? But what about N=3? Example: A=[0,0,3] sum=3 target=1. Operation: P=3,Q=0,R=ceil((3-0)/2)=2 => transfer 2 from 3 to a 0 => becomes [2,0,1]? Actually we need to pick a max and min; there are two zeros, we pick any min. Suppose we pick first zero. Then after transfer: max becomes 1? Actually A: [0,0,3]. Pick max=3, min=0 (first). R=2. Transfer: max becomes 3-2=1, min becomes 0+2=2 => array [2,0,1]. Next step: max=2 (from first), min=0 (second). R=ceil((2-0)/2)=1 => transfer: first becomes 1, second becomes 1 => array [1,1,1]. So 2 steps. So works.
Another: [0,1,2] sum=3 target=1: max=2, min=0, R=ceil(2/2)=1 => [1,1,1] done. So works.
What about [0,0,0,5]? sum=5, target=1.25 not integer => impossible. So sum divisible needed.
But also note constraints: A[i] <= N. That might be there for some reason.
We need to compute number of steps. Could be huge if we simulate? Since N up to 3000, values up to N, sum up to N^2 ~ 9e6. Steps might be O(sum) maybe? But worst-case maybe large? For instance, N=3000, all zeros except one value = sum = N * target. Suppose target = 0? But A[i]>=0, sum divisible: if sum=0 then all zeros, done. If sum>0, target >=1? But A[i] <= N, sum <= N^2 ~9e6. Steps might be up to sum? Let's consider: [0,...,0, S] where S = Ntarget. For N=3000, target maybe 3000? Since A[i] <= N, so max possible is N, so sum <= N^2 =9e6, target <= N. So S <= N^2. Steps? Simulating the process: each step transfers ceil((max-min)/2). In worst-case, the process may take many steps, but maybe not too many because each step reduces a measure? Could be O(Ntarget) which is up to 9e6, which might be acceptable? But T up to 20, so 20*9e6 = 180 million operations; but each simulation step also needs to find max and min and update. That might be heavy if we use naive O(N) per step. However, we might be able to compute directly the number of steps without simulation.
Let's analyze operation. It's reminiscent of making all equal by moving mass from high to low, with a particular transfer amount. Equivalent to a process on a multiset. Could it be that number of steps equals something like total "excess" above target divided by something? Or maybe we can model the process more abstractly.
Define total sum = S, target = T = S/N (integer). At each step, we take the current maximum value and the current minimum value, and transfer R = ceil((P - Q)/2). Note that after transfer, the new values are P' = P - R, Q' = Q + R. Also note that if P - Q is odd, R = (P - Q + 1)/2, then P' - Q' = (P - R) - (Q + R) = (P - Q) - 2R = (P - Q) - 2*((P - Q+1)/2) = (P - Q) - (P - Q+1) = -1? Actually if P - Q odd, say d = 2k+1, then R = ceil(d/2) = k+1. Then P' = P - (k+1) = (Q+2k+1) - (k+1) = Q + k; Q' = Q + (k+1) = Q + k + 1. So after transfer, the order might change: P' = Q + k, Q' = Q + k+1. So now the former min becomes larger than the former max? Actually Q' > P'. So they swap relative ordering: the new value of the original min becomes larger than the new value of original max. So the max and min may not remain the same individuals. This is interesting.
If P - Q is even, d=2k, R = k, then P' = P - k = Q + 2k - k = Q + k; Q' = Q + k. So both become equal to Q + k = (P+Q)/2. So they become equal (midpoint). Then after that, they are no longer min or max unless there are other equal extremes.
Thus operation reduces the spread between max and min, but may cause the max and min to swap. This process continues.
We need number of steps until all equal.
We can think of the process as: at each step, pick current max and min, replace them with values that are as close as possible to each other: if difference even, they become equal; if odd, they become two consecutive integers (differ by 1). This is similar to repeatedly applying a balancing operation to the two extremes.
This process is deterministic up to choice of which max/min when ties. However, number of steps might be independent of tie-breaking? Possibly yes, if we always pick any max and min, the number of steps might be same? Need to test with small examples. For N=3, start [0,3,3]? Sum=6 target=2. Let's simulate two tie-breaking possibilities:
Case: max=3 (choose first), min=0. d=3 odd -> R=2 => new values: 3->1, 0->2 => [1,3,2]? Actually after: array [1,3,2] (since we had [0,3,3], pick min=0, max=3 (first). After: [2,3,1]? Wait: originally indices: A0=0, A1=3, A2=3. Pick max = index1 (value3), min = index0 (0). R=2: A1 becomes 1, A0 becomes 2 => array [2,1,3]? Let's compute: A0:0+2=2, A1:3-2=1, A2:3 unchanged => [2,1,3]. Then step2: max=3 (index2), min=1 (index1). d=2 even -> R=1 => A2 becomes 2, A1 becomes 2 => [2,2,2] done. Total 2 steps.
Alternative tie-breaking: initially pick max = index2 (value3), min=0. Then after: A2 becomes 1, A0 becomes 2 => [2,3,1]? Actually [2,3,1] then step2: max=3, min=1 => similar leads to [2,2,2] in 2 steps. So same steps.
What about [1,1,3,3]? N=4 sum=8 target=2. Let's simulate: max=3 (choose any), min=1 (choose any). d=2 even -> R=1 => both become 2. So after one operation, we have two 2's, and two others: one 1 and one 3? Actually careful: suppose we have values: index0=1, index1=1, index2=3, index3=3. Pick max index2=3, min index0=1. Transfer R=1: index2 becomes 2, index0 becomes 2 => array: [2,1,2,3]. Now max=3 (index3), min=1 (index1). d=2 even -> R=1 => index3 becomes 2, index1 becomes 2 => array all 2's. So 2 steps. If we had picked different max/min: say first pick max index2=3, min index1=1 => same. So seems steps deterministic.
Consider scenario with many identical values. Maybe number of steps is determined solely by the multiset, independent of tie-breaking. I suspect so because the operation essentially reduces a certain measure. However, we need to compute steps efficiently.
We could simulate using a priority queue (max-heap and min-heap) to get O(S log N) steps? But S could be up to 9e6, which times log N (log 3000 ~12) => 108 million operations, maybe okay for T=20? 20*108M = 2.16B, too high. So we need a more direct method.
We need to find number of steps required to make all equal using this specific operation.
Let's think about the process in terms of the multiset of values. The operation is reminiscent of "balancing" where we always reduce the gap between extreme values.
One approach: Could we compute the final configuration? We know target T = sum/N. The process must converge to all T. So we need to know how many steps it takes.
Alternatively, consider modeling the process as a series of operations on sorted list. Since operation always involves current max and min, it's natural to maintain sorted order. After each operation, the two elements become either equal (if difference even) or differ by 1 (if odd). Then we need to re-insert them into sorted order.
If we simulate with a balanced BST, each step O(log N). Number of steps maybe up to something like O(N * T) or O(N^2)? But perhaps the number of steps is bounded by something like O(N * log(max))? Not sure.
Let's try to derive formula.
Define the multiset of values. The operation on max and min can be seen as: take the two extreme values a (max) and b (min), replace them with floor((a+b)/2) and ceil((a+b)/2). Because after transfer, the two values become (P - R) and (Q + R). Compute: if d = a - b, then R = ceil(d/2). So new values: a' = a - ceil(d/2), b' = b + ceil(d/2). Then note that a' = floor((a+b)/2)? Let's check: a+b is constant? Actually a+b = (a'+R)+(b'-R) = a'+b', so sum of the two remains same. After operation, the two numbers are: if d even: a' = b' = (a+b)/2, which is integer. If d odd: a' = (a+b-1)/2, b' = (a+b+1)/2. So indeed we are replacing the two extremes with the two numbers that are the floor and ceil of their average. So the operation is: take the current maximum and minimum, remove them, and insert two numbers: floor(avg) and ceil(avg), where avg = (a+b)/2.
That's a nice interpretation. So the multiset evolves by repeatedly taking the two extremes and replacing them with the two values that split their sum equally (or as equal as possible). This operation preserves the total sum, and also preserves the sum of squares? Not exactly.
Now, if we continue this process, eventually all numbers become equal to T, if sum divisible.
Observation: This operation is known as "balancing" and might converge to all equal in a finite number of steps. The number of steps might be equal to something like total "distance" from T? Or maybe we can think of it as: each step reduces the variance. Possibly the process is equivalent to performing a bubble sort like operation? Or we can think of it as the following: Consider sorted list. Operation takes first and last, replaces them with floor(avg) and ceil(avg), then reinserts them, which may not be extremes next step.
We could try to simulate using two deques or something, but need to understand step count.
Let's try to compute step count for given configuration.
We need to find minimal number of operations? Or is the process forced? It is deterministic except for ties, but maybe the number of steps is independent. Could it be that we can compute steps by analyzing how many times we need to "reduce" the range? Possibly we can think of the process as analogous to repeatedly applying "mean reduction" to extremes until all equal. It might be related to the concept of "sorting by splitting" or "redistribution".
Idea: Since the operation essentially reduces the difference between max and min, eventually the max-min becomes 0. Let's denote M = max, m = min. After one operation on these two, the new max could be either the previous second max, or one of the new numbers. The new min similarly. The spread might reduce.
We might try to compute steps by modeling the process as a series of operations on a sorted list. Because the operation always involves extremes, we can maintain a sorted list. After each operation, we remove the smallest and largest, and insert two numbers that are roughly the average. Then we re-sort? Actually we can insert them in correct positions. But we need step count.
Given N up to 3000, maybe number of steps is not huge. Let's test worst-case scenario. Consider N=3000, all zeros except one value = N (3000). Target = 1. Initially: 2999 zeros, one 3000. Operation: max=3000, min=0. avg=1500. So we remove 3000 and 0, insert 1500 and 1500? Actually (3000+0)/2 =1500 exactly, so both become 1500. So after first step, we have: 2998 zeros? Wait careful: We removed one max and one min, so we removed one zero and the 3000. After insertion, we add two 1500s. So we have: zeros count: originally 2999 zeros, we removed one zero -> 2998 zeros. Ones? Actually target 1, but we have zeros and 1500s. Then we have two 1500s. So now multiset: 2998 zeros, two 1500s. Now max=1500, min=0. Next step: pick max=1500, min=0, avg=750, so we remove one 1500 and one zero, insert 750 and 750. So zeros become 2997, 1500s become one (since we removed one 1500, originally two, left one), and we add two 750s. So after each such step, we reduce the number of zeros by 1, and introduce two numbers of half the current max (if max and min are extreme). The process continues until eventually we have many numbers and we might get more than two distinct values.
How many steps until all become 1? Let's simulate conceptually: we start with one big number S = N, and many zeros. At each step, we pair a zero with the current largest number, split it in half (if sum is even) and produce two numbers of half the value. This is akin to "binary splitting" of the large number. It seems the number of steps might be roughly number of times we need to break down the large number until all numbers become 1. But we also have many zeros, each step consumes one zero. Since we have N-1 zeros, after N-1 steps we would have used all zeros? But not exactly, because after some steps, the large number gets broken into smaller numbers, and eventually there will be many numbers >1, and zeros still exist until they are all used. Actually after we use all zeros, we will have N numbers all positive (some may be >1). Then we continue pairing the max and min, which may both be >0. That process may take more steps.
Let's try to compute total steps for extreme case: N=3000, all zeros except one 3000. Target = 1. Steps? Let's attempt to compute by reasoning.
We can think of the process as: we have multiset of numbers; we repeatedly take the max and min, replace them with floor and ceil of average. This is reminiscent of a known process that eventually makes all numbers equal to the average, and the number of steps equals the sum over all elements of something like the number of bits in the binary representation of the deviation from average? Or maybe it's related to the total "excess" above average measured in some unit.
Another angle: The operation can be reinterpreted as moving "mass" from high to low. Since each step transfers R = ceil((max-min)/2) from max to min. The total "transfer amount" might be related to steps.
Define total "work" or total "distance" from equilibrium? Consider sum of absolute deviations from T? Or something like that.
Let's denote the array values. The goal is all equal to T. At each step, we select max and min. Note that moving R from max to min reduces the gap between them by at least ceil(d/2)*2? Actually gap reduces from d to either 0 (if even) or 1 (if odd). So the gap reduces significantly.
Maybe we can compute steps by considering the sorted list and thinking of the process as bubble sort of some kind.
I recall a known problem: "Idli distribution" maybe appears in CodeChef? Actually the problem statement mentions Dexter and idlis, might be from some contest. Possibly there is known solution: answer is -1 if sum not divisible by N; else answer is sum_{i} |A[i] - T| / 2? But example: case 1: A=[1,2,2,3], T=2, sum|diff| = |1-2|+|2-2|+|2-2|+|3-2| = 1+0+0+1=2. /2 =1, matches output 1. Case 3: A=[1,2,3,4,5,6,7], sum=28, T=4, sum|diff| = |1-4|+|2-4|+|3-4|+|4-4|+|5-4|+|6-4|+|7-4| = 3+2+1+0+1+2+3=12. /2=6, but output is 3. So not that.
Maybe answer is number of positive differences? No.
Maybe the steps count is equal to the sum of positive differences? In case3 sum positive diffs = (5-4)+(6-4)+(7-4)=1+2+3=6, half is 3? Actually half of sum of positive diffs = half of total absolute diff/2? Because total absolute diff sum =12, half is 6, not 3. But sum of positive diffs =6, half of that is 3. That matches output 3! In case1: positive diffs = (3-2)=1 (since only 3 >2, and maybe 2 not positive, 1 negative) so half of 1? Actually half of 1 is 0.5, not integer. But output 1. So not that.
Let's compute: case1: total positive deviations above T: (3-2)=1, total negative deviations below T: (2-1)=1? Actually absolute values. Sum positive =1, sum negative =1 (in magnitude). Half of sum positive =0.5. Not integer.
Maybe steps count is max of sum positive and something? No.
Maybe we need to consider something like the number of "inversions" or something.
Let's attempt to simulate small N and see pattern.
We need a method to compute steps quickly. Perhaps we can derive that the process always terminates and number of steps is equal to sum over all elements of (something like distance in binary). Alternatively, maybe we can compute the number of steps by analyzing the process as repeatedly balancing extremes, which is similar to performing a "sort" using a specific operation.
Since N is only 3000, we could simulate each test case using a priority queue but we need to ensure number of steps is manageable. What is the maximum possible number of steps? Let's try to bound.
Observation: Each operation reduces the sum of squares? Let's test. Sum of squares before: a^2 + b^2. After: (floor(avg))^2 + (ceil(avg))^2. For any a,b, we have (floor(avg))^2 + (ceil(avg))^2 <= a^2 + b^2? Actually is it always less? Let's check: For a >= b. Let s = a+b. Then we compare a^2 + b^2 vs floor(s/2)^2 + ceil(s/2)^2. Since floor and ceil are integers differing by at most 1. It's known that for fixed sum s, the sum of squares is minimized when the numbers are as equal as possible (by convexity). So indeed the new sum of squares is less than or equal to old, strictly if a != b (unless difference <=1?). If a and b differ by at most 1, then floor and ceil are just a and b (or swapped) so sum squares same. But note if difference <=1, then operation would produce? If a - b =0, they are equal already; if =1, then R = ceil(1/2)=1, so a' = a-1 = b, b' = b+1 = a, so they swap. That doesn't change the multiset, but it could cause infinite loop if we keep swapping the same two? But if we have only two numbers differing by 1, sum not divisible? Let's examine N=2, [1,2] difference=1, sum=3, target=1.5 not integer, so infinite loop. So when sum divisible, can we have a situation where max-min =1? For N>=2, sum divisible, could max-min =1? Possibly yes, e.g., N=4, [1,1,2,2] sum=6 target=1.5 not integer, so not divisible. For sum divisible, target is integer, and if all numbers are integers, the average T is integer. If max-min=1, then all numbers are either T or T+1? Actually if max = T+1, min = T, and sum of all is NT + (number of T+1) = NT + k, so average = T + k/N. For average to be integer, k must be multiple of N. But k is between 0 and N. So k = 0 or N. If k=N, then all are T+1, max-min=0. If k=0, all T. So max-min cannot be 1 if sum divisible and N>1? Let's check N=3, T integer. Could we have values {T, T, T+1}? Sum = 3T+1, average = T + 1/3, not integer. So no. Could have {T-1, T, T}? Sum = 3T -1, not integer. So indeed if sum divisible by N, and N>1, the maximum and minimum cannot differ by 1? Actually what about N=2, T integer? Then values could be (T, T) diff 0, or (T-1, T+1) diff 2, or (T-2, T+2) etc. For T integer, (T, T+1) sum=2T+1, odd, not divisible by 2. So diff 1 impossible. For N>1, it seems that if sum divisible, the parity of all numbers relative to T maybe forces that differences are even? Not necessarily; but we can have values like T-2, T, T+2, etc. But diff of 1 might be possible? Let's test N=4: target T=2. Can we have values {1,2,2,3}? Sum=8, average=2, so diff=2? Actually max=3, min=1 diff=2. {1,1,2,4} sum=8, diff=3. {0,2,2,4} diff=4. {1,1,1,5} diff=4. So diff=1 not possible? Could we have {1,2,3,2}? diff=2. Let's try to find a configuration with integer average T, N>1, and max-min=1. Suppose min = m, max = m+1. All numbers are either m or m+1. Let count of m+1 be k, count of m be N-k. Sum = (N-k)m + k(m+1) = N*m + k. Average = m + k/N. For this to be integer, k must be multiple of N. Since 0<=k<=N, either k=0 (all m) or k=N (all m+1). Both yield diff=0. So indeed max-min cannot be 1 if average integer and N>1. So when sum divisible, the only case where max-min=1 is impossible (except maybe N=1 trivial). So the operation will strictly reduce sum of squares until convergence. Thus number of steps is finite.
Now, how many steps can there be? The sum of squares is a non-negative integer and each step reduces it by at least 1? Possibly more. Since values are bounded (0 to N? Actually <= N, but after operations values could exceed N? Wait A[i] initially <= N, but after transfers, values could become larger than N? Example: N=3, A=[0,0,3] after first step we got [2,0,1] => 2 > N? N=3, 2<=3, okay. Another: N=2, [0,2] -> [1,1] okay. Could values exceed N? Suppose N=3, initial all <=3. After operation, new values are averages of two numbers, which are at most max of the two. Actually the new numbers are floor and ceil of average, which lie between min and max inclusive. So they never exceed the original max. So values never exceed initial max, which is <= N. Also they never go below initial min, which is >=0. So values stay within [0,N]. So sum of squares is bounded by N*(N^2) = N^3 = 27e9 for N=3000, but that's large. However each step reduces sum of squares by at least? Let's compute reduction. For a>b, s=a+b. The reduction in sum of squares: Δ = (a^2+b^2) - (floor(s/2)^2+ceil(s/2)^2). Since s is integer? Not necessarily, but a,b integers, s integer. So s parity matters. If s even, then floor(s/2)=ceil(s/2)=s/2, Δ = a^2+b^2 - 2*(s/2)^2 = a^2+b^2 - ( (a+b)^2)/2 = (2a^2+2b^2 - (a^2+2ab+b^2))/2 = (a^2 -2ab + b^2)/2 = (a-b)^2 / 2. Since a-b even? Actually if s even, a and b have same parity, so a-b even, (a-b)^2 divisible by 4, so Δ is integer. For example a=3,b=1, (3-1)^2/2=4/2=2, indeed a^2+b^2=9+1=10, new each=2, sum squares 4+4=8, reduction 2.
If s odd, floor=(s-1)/2, ceil=(s+1)/2. Then new sum squares = ((s-1)/2)^2+((s+1)/2)^2 = (s^2-2s+1 + s^2+2s+1)/4 = (2s^2+2)/4 = (s^2+1)/2. Old sum = a^2+b^2. Since s = a+b. Then Δ = a^2+b^2 - (s^2+1)/2 = (2a^2+2b^2 - (a^2+2ab+b^2) -1)/2 = (a^2 -2ab + b^2 -1)/2 = ((a-b)^2 -1)/2. Since a-b is odd (because sum odd => a,b have opposite parity), (a-b)^2 is odd^2 = odd, so (a-b)^2 -1 is even, Δ integer. For example a=3,b=0, (3-0)^2-1=9-1=8, /2=4, old sum=9+0=9, new: floor(1.5)=1, ceil=2, squares=1+4=5, reduction 4.
Thus each step reduces sum of squares by at least? Minimum reduction when a-b=2? For even case reduction=2, for odd case when a-b=1? But a-b=1 can't happen when sum divisible? As argued earlier, in valid state (where total sum divisible by N) we might not encounter a-b=1? Could we encounter during process? Possibly intermediate states could have a-b=1 even if final average integer. Let's test N=2, sum divisible: [0,2] diff=2, not 1. [1,3] sum=4 avg=2, diff=2? Actually 3-1=2. [2,4] diff=2. So maybe diff=1 cannot appear if sum divisible? But we must check if intermediate state can have diff=1. For N=4, start [1,2,2,3] diff=2. After first step we got [2,2,2,2] diff=0. So not. For [0,0,3], after first step we got [2,0,1] diff=2? Actually max=2, min=0 diff=2. So still even? Actually 2-0=2 even. Next step gave [1,1,1] diff=0. So diff=1 not seen. Could we construct a state where diff=1 occurs? For N=3, target T=2, suppose values [1,2,3] sum=6 avg=2, diff=2. [0,2,4] diff=4. [0,1,5] sum=6 avg=2, diff=5? Not 1. [1,1,4] diff=3. So maybe it's impossible to have max-min=1 in any state reachable from an initial configuration where sum divisible? Possibly because parity invariants? Let's explore.
Consider invariant modulo something. Since each operation replaces a and b with floor and ceil of average, the sum mod something? Actually sum mod N is invariant (overall). But for the multiset, maybe the sum modulo 2? Not sure.
Better: The operation preserves the parity of the sum of all elements? Actually sum is invariant. Also, the parity of each element may change. But maybe there's an invariant: The sum of elements modulo 2? That's just sum mod 2. But that doesn't prevent diff=1.
Consider total sum S and N. The average T = S/N is integer. For any state reachable from initial, perhaps the sum of (A[i] - T) is zero. The operation on a and b: (a-T) + (b-T) = (a+b-2T). After replacement, we have floor((a+b)/2)-T and ceil((a+b)/2)-T. Their sum is a+b-2T, same. So the vector of deviations from T sum to zero.
Now, could there be a state where max-min=1? Suppose min = T - d, max = T - d +1? Actually if max-min=1, then the deviations range from negative to positive. Since sum of deviations zero, it would require some numbers below T, some above, with difference 1. Let the deviations be integers. The minimum deviation is -x, maximum deviation is -x+1? Actually if max-min=1, then max = min+1. Let min = m, max = m+1. Then deviations from T are (m-T) and (m+1-T). Their sum? Not directly. Could such a state be reachable? Possibly.
Let's try to construct for N=3, T=2. We need three integers with sum zero, max-min=1. Let deviations be a,b,c with sum 0, each integer, max-min=1. That means the values are either some k and k+1. Since max-min=1, all numbers must be either m or m+1, because if there were a number less than m or greater than m+1, then max-min>1. So all numbers are either m or m+1. Let count of m+1 be p, count of m be 3-p. Sum deviations = p*(m+1-T) + (3-p)(m-T) = 3(m-T) + p = 0. Since m and T integers. Choose m,T. For T=2, try m=1 => numbers are 1 and 2. Deviations: 1-2=-1, 2-2=0. So m=1 => m-T = -1. Then sum = 3*(-1) + p = -3 + p = 0 => p=3. So all three numbers would be m+1=2? Actually p=3 means all are 2, then max-min=0, not 1. So not. Try m=2 => numbers 2 and 3, deviations 0 and 1. m-T=0, sum=0 + p = p =0 => p=0, all 2, diff 0. So not. m=0 => numbers 0 and 1, deviations -2 and -1, sum = 3*(-2) + p = -6 + p =0 => p=6 impossible. So no configuration with max-min=1 and sum zero exists for N=3 T integer? General condition: For a set of numbers all equal to either m or m+1, with average T integer, we have: Let N numbers, with p numbers = m+1, N-p = m. Then average = m + p/N. For this to be integer T, p must be multiple of N. Since 0<=p<=N, p=0 or N. Both give all equal, thus max-min=0. So indeed for integer average, if all numbers are only two consecutive values, the average cannot be integer unless all numbers are same. So in any state where all numbers are only two consecutive values, average would be non-integer if 0<p<N. But our process might produce states with more than two distinct values, but still max-min could be 1? If max-min=1, then all numbers lie in [m, m+1], so they are only m or m+1. Thus all numbers are only two consecutive values. Then average = m + p/N. For average to be integer (which must hold because total sum is invariant and equal to N*T), we require p/N integer, so p=0 or N, implying all numbers equal. So max-min=1 cannot occur unless all equal (then diff 0). Therefore, during the process, as long as the total sum is divisible by N (i.e., average integer), we will never encounter a state where max-min=1. This is an important invariant.
Thus, in the process, whenever we pick max and min, their difference d >= 2 (since not all equal). And if d=2, then after operation they become equal (since avg integer? Let's check: if d=2, then a and b differ by 2. Their sum parity? a and b have same parity? If a and b differ by 2, they could be both even or both odd. But their sum is even, so floor=ceil = (a+b)/2 integer, so they become equal. So d=2 leads to both becoming same value, which is (a+b)/2, and that value is integer. So that reduces the spread.
If d>=3, after operation we get two numbers that differ by either 0 or 1? Actually if d even, they become equal; if d odd, they become two numbers differing by 1. But as argued, d odd cannot be 1? Actually d odd >=3, so after operation the two new numbers differ by 1. But then the overall multiset may have numbers differing by 1. However, we argued that in a state with integer average, we cannot have max-min=1 unless all equal. But after an odd d operation, we introduce two numbers differing by 1. But the overall max and min of the entire set might still be more than 1 apart because there could be other numbers beyond that range. For example, start with [0,3]? N=2 not allowed? For N>=3, consider initial [0,0,5]? sum=5, target=5/3 not integer, so not allowed. Let's find a case with sum divisible where we get an odd difference after some step. For N=4, start [0,0,0,6]? sum=6, avg=1.5 not integer. Need sum divisible by N. For N=4, target integer. Let's try [0,0,2,6] sum=8 avg=2, diff max-min=6. Step1: pick max=6, min=0, avg=3, both become 3 and 3? Wait (6+0)/2=3 exactly? 6+0=6 even, so both become 3. So d even. That yields [3,0,2,3] => values 0,2,3,3. Now max=3, min=0 diff=3 odd. So we have a state with max=3, min=0 diff=3, and numbers are {0,2,3,3}. Average is 2. So this state has max-min=3, and there exist numbers 2 and 3 which are consecutive? Actually 2 and 3 differ by 1, but max-min is 3, so the set contains numbers 0,2,3. So the two numbers from operation that differ by 1 are present, but overall max-min >1. So the invariant about max-min=1 doesn't apply because the set includes numbers more extreme.
Now, after we perform operation on max=3 and min=0, d=3 odd, R=ceil(3/2)=2, transfer: max becomes 1, min becomes 2 => new values: we replace 3 and 0 with 1 and 2. So new multiset: {1,2,2,3}? Wait we had [3,0,2,3] (indices: two 3's, one 0, one 2). After picking one 3 and the 0, we get 1 and 2. So the multiset becomes: from the two 3's, one becomes 1, the other remains 3; the 0 becomes 2; and we still have the 2. So we have {1,2,2,3}. Now max=3, min=1 diff=2 even. Next step picks max=3, min=1, d=2 even, both become 2. So final {2,2,2,2}. So steps: three steps? Actually initial to {3,0,2,3} (step1), to {1,2,2,3} (step2), to {2,2,2,2} (step3). So 3 steps. This example is similar to [0,0,2,6]? But sum=8, target=2, steps=3? Let's compute directly: [0,0,2,6] step1 (6,0) -> both 3 => [3,0,2,0? Wait we had two zeros? Actually initial [0,0,2,6] we have two zeros. Pick max=6, min=0 (any). After operation: 6->3, 0->3 => array becomes [3,0,2,3] (since we used one zero and the 6, other zero remains). That's step1. Step2: max=3, min=0 (the remaining zero). d=3 odd -> R=2 => 3 becomes 1, 0 becomes 2 => array becomes [3,2,2,1] (since we had another 3? Actually we had two 3's: one from step1 and the original 3? Wait after step1 we had [3,0,2,3]. Now pick max=3 (one of the 3's) and min=0. After: 3->1, 0->2 => array: we have other 3 unchanged, and we add 2 from min and 1 from max, plus existing 2. So {1,2,2,3}. Step3: max=3, min=1 -> d=2 even -> both become 2 => {2,2,2,2}. So 3 steps. So yes.
Thus we can have states where after an odd d operation, we get two numbers differing by 1, but overall max-min may be larger.
Hence the process will continue until all equal.
Now, we need to compute number of steps efficiently.
Given N up to 3000, perhaps we can simulate the process using a priority queue and it will converge quickly. But we need to be sure that the number of steps is not too large. Could it be as large as O(S) where S is sum? In the worst-case scenario with one large value and many zeros, steps? Let's simulate for N=3000, all zeros and one 3000. Let's simulate step count.
We'll attempt to compute steps analytically for that case. At each step, we pair a zero with the current maximum. The maximum value will be halved (or nearly halved) each time? Not exactly, because after we split the max with a zero, we get two numbers equal to half (if even) or floor/ceil. Over time, the large numbers break down.
But note that after we consume a zero, we produce a number that is roughly half of the previous max. However, we also generate another number (the other half) which might become the new max later. Let's attempt to simulate with N=5, one large, others zero. N=5, large =5? Actually A[i] <= N, so max initial =5, target=1. Steps? Let's simulate:
Initial: [0,0,0,0,5] sum=5 target=1.
Step1: max=5, min=0 -> both become 2.5? 5+0=5 odd, floor=2, ceil=3. So we get 2 and 3. So after step1: [3,2,0,0,0]? Actually we used one zero, we get 2 and 3. So multiset: three zeros left? Wait N=5, we had 4 zeros and one 5. After removing one zero and the 5, we add 2 and 3, so we have: zeros: 3 (since 4-1=3), plus 2 and 3 => total 5 numbers: [0,0,0,2,3].
Step2: max=3, min=0 -> 3+0=3 odd -> floor=1, ceil=2 => we get 1 and 2. So after: zeros: 2 (since we used one zero), we have existing 2 and 3? Actually we used the 3 and a zero, so we remove 3 and a zero, add 1 and 2. So new multiset: zeros: 2, plus existing 2 (from before), plus new 1, new 2, plus the other 2 from before? Wait we need to track: before step2: multiset = {0,0,0,2,3}. After step2 (max=3, min=0): remove 3 and a 0, add 1 and 2. So now we have: zeros: remaining two zeros (since three zeros minus one = two), plus the existing 2 (from step1), plus new 1 and new 2. So multiset: {0,0,1,2,2}.
Step3: max=2, min=0 (there are two 2's, pick any). 2+0=2 even -> both become 1. So we remove a 2 and a 0, add two 1's. So after: zeros: one zero left (since two zeros minus one = one), plus existing 1, existing 2? Wait we had {0,0,1,2,2}. Remove a 2 and a 0, add two 1's. So new multiset: zeros: one zero, plus 1 (existing), 2 (the other 2), plus two new 1's => {0,1,1,1,2}.
Step4: max=2, min=0 -> 2+0=2 even -> both become 1. Remove 2 and 0, add two 1's => multiset: {1,1,1,1,1} done.
Total steps = 4.
What is sum of absolute deviations? Initially sum|diff|=|0-1|*4 + |5-1|=4+4=8, half=4 -> steps=4? Actually half of sum of positive deviations? positive deviations: only 5 >1, diff=4, half=2, not 4. Half of total absolute diff =8/2=4 matches steps! Let's test earlier examples: Case1: total absolute diff=2, half=1 matches. Case3: total absolute diff=12, half=6, but steps=3, not 6. So not consistent.
For case3, total absolute diff=12, half=6, but steps=3. So that formula fails.
Maybe steps equals sum of positive deviations? For case3 positive deviations = (5-4)+(6-4)+(7-4)=1+2+3=6, not 3. Negative deviations sum= (4-1)+(4-2)+(4-3)=3+2+1=6. Half of positive =3 matches steps. For case1, positive deviations sum=1, half=0.5 not 1. For N=5 example, positive deviations sum = (5-1)=4, half=2, but steps=4. So not consistent.
Maybe steps = sum of squared deviations? No.
Let's compute for case3: steps=3. Let's manually simulate case3 to see step count:
A=[1,2,3,4,5,6,7] sum=28 target=4.
Step1: max=7, min=1, diff=6 even -> both become (7+1)/2=4. So after: [4,2,3,4,5,6,4] => sorted: 2,3,4,4,4,5,6.
Step2: max=6, min=2, diff=4 even -> both become (6+2)/2=4 => [4,4,3,4,5,4,4]? Actually careful: we replace 6 and 2 with two 4's. So after: values: from step1 we had [4,2,3,4,5,6,4] (let's list: 4 (from first), 2,3,4,5,6,4). After step2: replace 6 and 2 with 4 and 4 => becomes [4,4,3,4,5,4,4] => sorted: 3,4,4,4,4,4,5.
Step3: max=5, min=3, diff=2 even -> both become 4 => all 4.
So 3 steps.
Total absolute diff = 12. Number of steps = 3.
Observation: Each step seems to reduce the range (max-min) by something. But maybe the number of steps equals something like the number of distinct values? Not.
Maybe we can compute steps as the number of "layers" needed to bring all numbers to T. Since the operation on max and min essentially averages them. This process resembles repeatedly taking the current multiset and replacing the extremes with their average, which is similar to performing a balancing that eventually leads to all T. This is reminiscent of the "balancing" problem where you have numbers and you repeatedly take the largest and smallest and replace them with their average; the number of steps might be equal to the number of elements that need to be "adjusted".
Alternatively, we could think of this as a sorting process on the deviations from T. Let x_i = A_i - T. Then sum x_i = 0. The operation: pick max (largest x) and min (smallest x), say a and b (a >= 0? Not necessarily, max could be negative? Actually max is largest value, which corresponds to largest deviation, which could be negative if all below T, but since sum zero, if not all equal, there will be both positive and negative deviations. Indeed min deviation is negative, max deviation is positive. So we have a > 0, b < 0. Their values: P = T + a, Q = T + b. The operation transfers R = ceil((P - Q)/2) = ceil((a - b)/2). After transfer, new values: a' = a - R, b' = b + R. And note that (a' + b') = a + b. And the new deviations become a' and b'.
But also the operation on original numbers corresponds to replacing a and b with floor((P+Q)/2)-T and ceil((P+Q)/2)-T, which are floor((a+b)/2) and ceil((a+b)/2) (since T cancels). Because (P+Q)/2 = T + (a+b)/2. So the new deviations are floor((a+b)/2) and ceil((a+b)/2). Indeed a+b may be negative? Since a positive, b negative, sum could be negative, zero, or positive. But note that a is max deviation, b is min deviation, so a >= 0, b <= 0. Their sum could be anything. However, since the max is positive and min negative, the average (a+b)/2 lies between them. The operation essentially replaces the two extreme deviations with numbers that are closer to zero? Actually if a > 0 and b < 0, then (a+b)/2 could be positive, zero, or negative depending on magnitudes. But the operation on the actual numbers ensures that the new numbers are between the old ones. So the new deviations are floor and ceil of (a+b)/2.
Thus the process on deviations: we have multiset of integers summing to 0. At each step, pick the maximum deviation a (largest) and minimum deviation b (smallest, i.e., most negative), and replace them with floor((a+b)/2) and ceil((a+b)/2). This process continues until all deviations are zero.
Now note that a+b could be odd or even. If a+b is even, then floor=ceil = (a+b)/2. So both become the same. If a+b is odd, they become two numbers differing by 1, one floor and one ceil.
Observing the process on deviations may give insight.
We need to compute number of steps until all zero.
Because N is only 3000, perhaps we can simulate using a priority queue where each step reduces some measure significantly, and the number of steps might be O(N log N) or O(N^2) rather than O(S). Let's attempt to bound steps.
The sum of squares of deviations reduces each step. For deviations d_i, sum of squares Q = sum d_i^2. For a step on a (positive) and b (negative), we replace a^2 + b^2 with floor^2 + ceil^2. Reduction Δ = a^2+b^2 - (floor^2+ceil^2) = ((a-b)^2 - ( (a+b) mod 2 ))/2. Since a-b >=? Since a >=0, b <=0, a-b = a+|b| = (positive) + (positive) >=? At least? Since not all zero, at least one positive and one negative, so a - b >= 1? Actually if a>0 and b<0, then a-b >=2? Could it be 1? Suppose a=1, b=0? But b is min, so if min is 0, that means all deviations >=0, but sum zero implies all zero. So if there is a positive deviation, there must be a negative deviation. Could the negative deviation be -0? No, it must be negative integer. So b <= -1. Then a >= 1. So a - b >= 2. So Δ >= ((2)^2 - 1)/2 = (4-1)/2=1.5 -> integer? Actually Δ integer, so Δ >=? For a-b=2, parity: a and b could be both even/odd? If a=1,b=-1, then a-b=2, a+b=0 even, Δ = (2^2)/2=2. So Δ at least 2. For a=2,b=-1, a-b=3 odd, Δ = (9-1)/2=4. So reduction at least 2. So Q decreases by at least 2 each step.
Initial Q max? Each deviation is between -T and (max initial - T). Since A[i] between 0 and N, T = sum/N <= N. So deviations bounded by N. So max |deviation| <= N. So Q <= N * N^2 = N^3 = 27e9 for N=3000, which is about 2.7e10. Steps could be up to Q/2 ~ 1.35e10, far too many. So cannot simulate step-by-step.
Thus we need a closed form or more efficient method.
Maybe the number of steps is equal to something like sum of positive deviations? But that failed for case1 and case5? Actually case1 positive deviations sum=1, steps=1, so okay? For case1 positive deviations sum=1, steps=1, matches? But N=5 example positive deviations sum=4, steps=4, matches. But case3 positive deviations sum=6, steps=3, does not match. However, in case3, after step1, we had positive deviations? Let's compute deviations initially: [ -3, -2, -1, 0, 1, 2, 3 ]. Positive sum = 1+2+3=6. After step1, we replaced 7 and 1 (deviations 3 and -3) with two 4s (deviations 0). So positive deviations became: originally we had positive ones: 1,2,3; after step1, 3 is removed, we added 0, so positives: 1 and 2 (from 5 and 6) plus maybe others? Actually after step1, array: [4,2,3,4,5,6,4] => deviations: [0,-2,-1,0,1,2,0]. Positive sum = 1+2=3. After step2, we replaced 6 and 2 (deviations 2 and -2) with two 4s (0), positive sum becomes 1 (from 5). After step3, becomes 0. So positive sum decreased by 3, then 2, then 1, total steps 3. So each step reduced the sum of positive deviations by an amount equal to the positive deviation of the max? Not exactly.
In case1, initial positive sum=1, one step reduced it to 0.
In N=5 example, initial positive sum=4, steps: after step1, we had positives? initial deviations: zeros: four -1? Actually target=1, initial [0,0,0,0,5] => deviations: [-1,-1,-1,-1,4] positive sum=4. After step1, we had [3,2,0,0,0] => deviations from target 1: [2,1,-1,-1,-1] positive sum = 2+1=3. After step2: [1,2,2,0,0]? Actually after step2 we had [1,2,2,0,0]? Let's compute deviations from 1: [0,1,1,-1,-1] positive sum =1+1=2. After step3: [1,1,1,1,0]? Actually after step3 we had {0,1,1,1,2}? Let's recalc: step3 gave {0,1,1,1,2}? earlier we had after step3: {0,1,1,1,2}? Wait we had after step3: {0,1,1,1,2}? Actually we had after step3: {0,1,1,1,2}? Let's re-derive N=5 example precisely.
Initial: [0,0,0,0,5] target=1.
Step1: max=5, min=0 => (5+0)=5 odd -> floor=2, ceil=3. So we remove 5 and one 0, add 2 and 3. New multiset: [0,0,0,2,3] (three zeros, one 2, one 3). Deviations from 1: zeros-> -1 (three -1), 2->1, 3->2. Positive sum = 1+2=3.
Step2: max=3, min=0 (one of zeros). (3+0)=3 odd -> floor=1, ceil=2. Remove 3 and one zero, add 1 and 2. New multiset: zeros: two zeros left; plus existing 2; plus new 1 and 2 => [0,0,1,2,2]. Deviations: zeros: -1,-1; 1->0; 2->1,2->1. Positive sum = 1+1=2.
Step3: max=2, min=0. (2+0)=2 even -> both become 1. Remove one 2 and one zero, add two 1's. New multiset: zeros: one zero left; plus existing 1? Actually we had [0,0,1,2,2]. After removing one 2 and one 0, we add two 1's => zeros: one zero; 1's: existing 1 plus two new = three 1's; and one remaining 2? Wait we removed one 2, but there were two 2's, so one 2 remains. So multiset: [0,1,1,1,2]? Actually check: before step3: {0,0,1,2,2}. After step3: remove one 2 and one 0, add two 1's => we have: remaining: one 0 (since two zeros minus one), one 1 (original), one 2 (the other 2), plus two new 1's => {0,1,1,1,2}. Deviations: 0->-1, 1's->0, 2->1. Positive sum = 1.
Step4: max=2, min=0. (2+0)=2 even -> both become 1. Remove 2 and 0, add two 1's => multiset: {1,1,1,1,1}. Positive sum=0.
So positive sum went: 4 -> 3 -> 2 -> 1 -> 0. Steps = 4, equal to initial positive sum.