We are given t test cases. For each test case, we have n positive integers a_i, and a divisor k. Initially x = 0. Moves: we can either do operation 1: choose an index i that hasn't been used before for operation 1? The problem says "The first operation can be applied no more than once to each i from 1 to n." So we can apply operation 1 at most once per element. Operation 1: a_i := a_i + x; then x := x+1. Operation 2: just increase x by 1 (x := x+1). So essentially we have a sequence of moves, each move increments x by 1. Some moves are "special" where we also add the current x (before increment) to a chosen a_i (provided that i hasn't been used before). The order of moves is arbitrary; we can decide when to apply operation 1 to each element, but each element can be used at most once.
Goal: after some moves, we need every a_i divisible by k. We want to minimize total number of moves (which equals final x because x starts at 0 and increments by 1 each move, so after m moves x = m).
We need to find minimal m such that there exists a sequence of applying operation 1 to a subset (maybe all) of indices at some times, such that for each i, the final a_i is divisible by k.
Important: operation 1 adds the current x (which is before increment) to a_i. Then x increments. So if we apply operation 1 to element i at time t (0-indexed moves), then the value added is the x at that moment, which is equal to the number of moves already performed. After the operation, x increments. So after m total moves, final x = m. For each element i, we have a_i_final = a_i + (time when we applied op1 to i) if we applied op1, else a_i unchanged (if we never used op1 on it). But note: we could also just do op2 moves, which only increase x, not affecting any a_i. So effectively we can decide for each i whether to add some value (the x at that time) to it exactly once, and we can choose the time of addition. The times are integers from 0 to m-1 inclusive (since we have m moves, and each operation 1 consumes one move; operation 2 also consumes one move but doesn't add to any element). We can interleave them arbitrarily.
Let the set of indices where we apply operation 1 be S. For each i in S, let t_i be the move number (starting from 0) when we apply operation 1 to i. Then after m moves, x = m, and final a_i = a_i + t_i (if i in S) else a_i. We need a_i_final ≡ 0 mod k. So for each i in S, we need a_i + t_i ≡ 0 (mod k). For each i not in S, we need a_i ≡ 0 (mod k). But note that we could also choose not to apply operation 1 to an element if it is already divisible by k initially. However, it might be beneficial to apply operation 1 even if a_i is already divisible by k, but that would likely increase moves? But we could also just not apply; it might reduce need to increase m? We need to minimize m, which is the total number of moves.
Observation: Since we can always increase x (via op2) arbitrarily, m can be as large as needed. But we want minimum. The constraints: t_i are distinct? Actually each operation 1 is assigned to a distinct index, but the times t_i can be equal? Since we cannot apply two operation 1 in the same move? Each move is either op1 on a chosen i or op2. So we can only do at most one operation 1 per move. So the t_i values must be distinct integers from 0 to m-1. Also, we might have some moves that are op2, so some times (integers) are not assigned to any element. So essentially we are selecting a set of times (distinct) to assign to some elements, one per element we choose to apply op1. The times are the move indices (starting from 0). So the t_i are a set of distinct non-negative integers less than m.
We need to minimize m such that there exists an injection (maybe not all times used) assigning to each i (that we decide to use) a time t_i ∈ [0, m-1] such that a_i + t_i ≡ 0 (mod k), and for each i not used, a_i ≡ 0 (mod k). The injection's domain is a subset S of indices, and its range is a subset of times (size |S|) within [0, m-1]. The rest of times are op2 moves.
We can also choose to use operation 1 on an element even if it's already divisible, but then we would need a time t_i such that a_i + t_i ≡ 0 mod k, which would require t_i ≡ 0 mod k (since a_i ≡ 0). That might be possible. But maybe we don't want to use it because it uses up a time slot that could be used for another element? But we can always increase m to accommodate extra times. The goal is to minimize m, so we want to assign times as small as possible to satisfy the conditions for all elements. Essentially, we need to cover all indices that are not already divisible by k, because if a_i % k != 0, we must apply operation 1 to it to adjust its remainder (since we cannot change a_i otherwise). Wait: Could we not apply operation 1 to an element and still make it divisible by k by using operation 2 only? Operation 2 does not change a_i, so a_i remains unchanged. So for an element to become divisible, if it's not already divisible, we must apply operation 1 to it exactly once (since we can only apply at most once). So S must include all indices i such that a_i % k != 0. For indices where a_i % k == 0, we can either leave them untouched, or maybe we might need to apply op1 to them if that helps reduce m? Possibly no: if we apply op1 to an already divisible element, we would then need to satisfy a condition a_i + t_i ≡ 0 mod k, which means t_i ≡ 0 mod k. That might force us to have a time slot t_i that is a multiple of k. But we can also simply not use it. Adding extra constraints can only increase m (or at least not decrease). However, there is a nuance: maybe we could use operation 1 on an already divisible element to "use up" some time slots that are forced by other constraints? But since we want to minimize m, we would not voluntarily add extra elements to S. So we can assume that S is exactly the set of indices with a_i % k != 0. But is it always necessary? Consider an element with a_i % k != 0, but it's possible that by not applying operation 1, we could still make it divisible if we could somehow change its value through other means? No, only operation 1 changes a_i, and only once. So indeed we must apply operation 1 to all such indices. So S is forced: all indices i where a_i mod k ≠ 0 must be in S. Let R = number of such indices, say r. Then we must assign distinct times t_i (0 <= t_i < m) to these r indices, such that for each i, (a_i + t_i) mod k = 0. That is, t_i ≡ -a_i (mod k). Let required remainder d_i = (-a_i) mod k, i.e., d_i = (k - (a_i mod k)) % k. So we need to pick distinct integers t_i in [0, m-1] such that t_i ≡ d_i (mod k). Additionally, m is the total number of moves, which must be at least the maximum time assigned + 1 (since times start at 0, after m moves x=m). Also, m could be larger; we can have extra op2 moves at the end. But to minimize m, we would set m = max(t_i) + 1, perhaps plus maybe we need to consider that times must be distinct and cover needed residues. However, there is also the possibility that we could use some times that are not needed for any element? That would increase m without benefit, so minimal m would be the minimal possible max time+1 such that we can assign distinct times to all required elements meeting residue conditions. So problem reduces to: Given r required residues d_i (each in [0, k-1]), we need to assign distinct non-negative integers t_i such that t_i ≡ d_i (mod k). Find minimal T = max(t_i) + 1? Actually m is number of moves, which equals total moves, and if we assign the largest t as some value L, then after L+1 moves we have x = L+1? Wait careful: If we have m moves, the moves are numbered 0 to m-1. After move m-1, x becomes m. So if the maximum t_i is L, we need m > L because we need to have made that move (with index L). So m must be at least L+1. Also, we could have additional moves after the last operation 1? That would increase m but not needed. So minimal m = L+1. So essentially we want to minimize the maximum assigned time (the latest time when we apply an operation 1) such that we can assign distinct times with given residues.
This is reminiscent of scheduling tasks with modular constraints. For each residue class mod k, the times that are ≡ d (mod k) are: d, d+k, d+2k, ... So we need to assign to each element i a distinct number from its arithmetic progression. We want to minimize the maximum number assigned.
This is like: we have multiple "buckets" for each residue (0..k-1). For each element with residue d, we need to pick a distinct value from the set S_d = {d, d+k, d+2k, ...}. The assignment is one-to-one across all elements. We want to minimize the largest chosen value.
This is a classic problem: given multiset of required residues, find smallest L such that we can assign each required residue d to a distinct number ≤ L that is ≡ d (mod k). Equivalent to: can we assign each requirement to a distinct slot from the arithmetic progression up to L. The necessary and sufficient condition is that for each residue d, the number of elements with that residue ≤ the number of available numbers in S_d up to L, i.e., floor((L - d)/k) + 1 if L >= d else 0. Also, total elements <= total numbers up to L, but that's automatically if each residue constraint holds? Actually we also need distinctness across residues; but since numbers from different residues are distinct (they differ mod k), we need that overall count of required numbers ≤ total count of numbers in [0, L] that are ≡ some residue? But that total is L+1 (all integers 0..L) obviously. So if we have r elements, we need L+1 >= r? But also must respect residues. Actually the residues partition the set; we can't assign two elements with same residue to the same number, but we can assign to different numbers in that progression. So we need for each residue d: count_d ≤ cnt_d(L) where cnt_d(L) = number of integers t in [0, L] with t ≡ d (mod k) = floor((L - d)/k) + 1 if L >= d else 0. Additionally, overall sum of counts = r, and sum of cnt_d(L) = L+1 (since covering all residues partitions 0..L). So if each cnt_d(L) >= count_d, then automatically sum counts <= L+1? Actually sum count_d = r, sum cnt_d(L) = L+1, so if each cnt_d(L) >= count_d, then r ≤ L+1. So the condition reduces to for each residue d: count_d ≤ cnt_d(L). And we want smallest L such that holds. Then answer m = L+1.
But is there any further subtlety? The times we assign must be distinct across all elements, and we cannot assign a time to an element if we used that time for another element, but the condition cnt_d(L) >= count_d ensures we have enough numbers in each residue class. However, we also need to consider that numbers from different residues are automatically distinct. So the assignment exists if and only if for all residues d, count_d ≤ cnt_d(L). This is essentially Hall's marriage condition: the bipartite graph between elements and times has each element connected to times with same residue mod k. Since times from different residues are disjoint sets, Hall's condition reduces to each residue class having enough times. Yes.
Thus the minimal L is the smallest integer such that for every residue d (0..k-1), we have count_d ≤ floor((L - d)/k) + 1 (if L >= d). Or equivalently, L must be at least the smallest number such that for each d, the count of needed times for that residue is ≤ the count of available numbers.
We need to compute count_d: for each i where a_i % k != 0, compute d_i = (k - a_i % k) % k. Actually note: d_i = ( -a_i mod k ) = (k - (a_i % k)) % k. For a_i % k == 0, d_i would be 0 but we don't need to consider them because we don't need to apply op1. So count_d is number of i with a_i % k != 0 and d_i = d.
Now we need to find minimal L such that for all d, cnt_d(L) >= count_d.
Observation: Since count_d may be zero for many residues, we only care about residues where count_d > 0. But if count_d > 0, we need L >= d obviously, because the smallest time with that residue is d. Also, for each such d, we need L >= d + k*(count_d - 1). Because the count_d numbers in that progression that are ≤ L must at least include the first count_d numbers: d, d+k, ..., d + k*(count_d-1). So a necessary and sufficient condition is that L >= max over residues d ( d + k*(count_d - 1) ). However, is that sufficient? Let's check: if L >= d + k*(count_d - 1) for all d, then cnt_d(L) = floor((L - d)/k) + 1 >= count_d. Indeed if L >= d + k*(c-1) then (L - d) >= k*(c-1) so floor((L-d)/k) >= c-1, so +1 >= c. So yes, that condition is sufficient. But is it also necessary? If L satisfies cnt_d(L) >= count_d, then L must be at least d + k*(count_d - 1) because the (count_d)th smallest number in that residue class is exactly d + k*(count_d - 1). Since we need to fit count_d numbers ≤ L, L must be at least that number. So minimal L is indeed L_min = max_{d: count_d>0} ( d + k*(count_d - 1) ). However, we must also consider that there could be interactions across residues? Could a smaller L be possible by using some numbers for residues that are not the minimal ones? But the bound is per residue: the smallest possible L that can accommodate count_d numbers in residue class d is exactly d + k*(count_d - 1). So any L that works must satisfy L >= that for each d. Therefore, the minimum L is the maximum of these per-residue lower bounds. And then we can set L = max_{d} (d + k*(count_d - 1)). This L automatically satisfies all residue counts. So answer m = L + 1.
But wait, is there any nuance about the fact that we can also choose to not use some times (i.e., we could have gaps)? That doesn't affect the max bound. The minimal max time is indeed determined by the "latest needed time" for the residue class with the largest required "last slot".
Let's test with examples.
Example 1:
n=4, k=3
a = [1,2,1,3]
Compute a_i % k:
1%3=1 -> need d = (3-1)%3 = 2
2%3=2 -> d = (3-2)%3 = 1
1%3=1 -> d=2
3%3=0 -> already divisible, so skip.
So count_d: d=1: 1, d=2: 2.
Now compute per residue:
d=1: d + k*(count-1) = 1 + 3*(1-1)=1
d=2: 2 + 3*(2-1)=2+3=5
max = 5
Thus L=5, m = L+1 = 6. That matches example output 6.
Example 2:
10 6
a: 8 7 1 8 3 7 5 10 8 9
Compute each mod 6:
8%6=2 -> d = (6-2)%6 = 4
7%6=1 -> d=5
1%6=1 -> d=5
8%6=2 -> d=4
3%6=3 -> d=3
7%6=1 -> d=5
5%6=5 -> d=1
10%6=4 -> d=2
8%6=2 -> d=4
9%6=3 -> d=3
List d: [4,5,5,4,3,5,1,2,4,3]. Count residues:
d=1:1
d=2:1
d=3:2 (from indices 5 and 10? Actually 3 appears twice: a_i 3? Let's count: from list: positions 5? Actually a[5]=3 gives d=3, a[10]=9 gives d=3 -> two)
d=4:3 (from 8, 4, 9? Actually a1=8 d4, a4=8 d4, a9=8 d4 -> three)
d=5:3 (a2=7 d5, a3=1 d5? Wait a3=1 gives d=5? 1%6=1 -> d=5 yes, a6=7 d5 -> three)
d=0? none.
Now compute per residue:
d=1: 1 + 6*(1-1)=1
d=2: 2 + 60 =2
d=3: 3 + 6(2-1)=3+6=9
d=4: 4 + 6*(3-1)=4+12=16
d=5: 5 + 6*(3-1)=5+12=17
max = 17
Thus L=17, m=18. Output example says 18. Good.
Example 3:
5 10
a: 20 100 50 20 100500
Compute mod 10:
20%10=0 -> skip
100%10=0 -> skip
50%10=0 -> skip
20%10=0 -> skip
100500%10=0 -> skip
So no elements need adjustment. count_d all zero. Then L = max over empty set? Convention: if no elements need op1, we can just have m=0? But initial x=0, and array already all divisible by k. Do we need any moves? The problem asks "minimum number of moves required to obtain such an array that each its element is divisible by k". If already satisfied, we can do 0 moves. However, is x=0 considered after 0 moves? Initially x=0, we haven't performed any moves. The array is already good. So answer 0. Our formula: L is undefined. But we can treat L = -1? Then m = L+1 = 0. So we should set answer 0 when r=0. So handle separately.
Example 4:
10 25
a: 24 24 ... (10 times)
Compute each: 24%25 = 24, need d = (25-24)%25 = 1.
So count_d: d=1: 10.
Now compute: d + k*(count-1) = 1 + 25*(10-1)=1+225=226.
L=226, m=227. Output matches 227.
Example 5:
8 8
a: 1 2 3 4 5 6 7 8
Compute mod 8:
1%8=1 -> d=7
2%8=2 -> d=6
3%8=3 -> d=5
4%8=4 -> d=4
5%8=5 -> d=3
6%8=6 -> d=2
7%8=7 -> d=1
8%8=0 -> skip
So count residues: each d from 1 to 7 appears exactly 1.
Compute per residue:
d=1:1+8*0=1
d=2:2
d=3:3
d=4:4
d=5:5
d=6:6
d=7:7
max = 7
L=7, m=8. Output 8. Good.
So the formula works for these examples.
Thus the solution seems straightforward: for each test case, compute counts of required remainders d_i = (k - a_i % k) % k for those a_i not divisible by k. Then compute ans = max_{d} ( d + k*(cnt[d] - 1) ) + 1, unless no such elements, then ans = 0.
Wait, but is there any possibility that we could assign times not strictly in increasing order of residues? The derived bound seems tight. However, we should verify with some edge cases. Consider k large (e.g., 10^9) and many elements with same residue. The bound is large but seems correct.
But wait, is there any scenario where we could achieve a smaller max time by using some times that are not of the form d + k*(c-1) for some residue? For example, suppose we have two residues, and the per-residue lower bounds conflict? Actually each residue's needed times are independent because times from different residues are distinct. The max time is determined by the "latest" time needed among all residues. Could we reduce the max time by using a different assignment within a residue? For a given residue, the optimal assignment to minimize the maximum time is to use the smallest available numbers: d, d+k, d+2k, ... So the c-th smallest is d + k*(c-1). That is the minimal possible maximum for that residue when assigning c numbers. So that's the best you can do for that residue. For other residues, they have their own sequences; the overall max is the maximum of those per-residue maximums. Since times are independent, you cannot reduce the maximum by assigning some element to a larger time in one residue to allow another residue to use a smaller maximum? The max is the maximum among all assigned times; you could potentially lower the overall max by shifting some assignments: if one residue has a large required maximum, maybe you could give one of its elements a time from a different residue's slot? No, because each element must be assigned a time congruent to its required residue mod k. So an element with residue d cannot be assigned a time that is not ≡ d (mod k). So the assignment is constrained to its own residue class. Thus the per-residue constraints are independent. The overall maximum time is the maximum of the largest times used in each residue. To minimize this overall maximum, we want to minimize each residue's largest assigned time individually, which is achieved by taking the smallest numbers in that residue. So the minimal possible overall maximum is indeed the maximum over residues of the (c-th smallest number) where c = count_d. That is L_min = max_{d} ( d + k*(cnt[d] - 1) ) provided we can assign all times without conflict across residues? Since the residue classes are disjoint, there is no conflict. So the assignment exists as long as for each residue, we assign distinct numbers from its progression. There's no cross-residue conflict because numbers are distinct anyway. So it's valid.
But wait, consider the scenario where d=0 is a required residue. d=0 means we need t ≡ 0 mod k. The smallest such number is 0. But is t=0 allowed? At move 0, x initially 0, we can do operation 1? Let's check: Initially x=0. We can perform operation 1 on some i, which adds x (0) to a_i and then increments x to 1. So t=0 is allowed. That is fine.
Now what about the possibility that we might need to use t=0 for some element? If an element has d=0 (i.e., a_i % k == 0), we wouldn't need to apply op1 because it's already divisible. But if we have an element with a_i % k != 0 that yields d=0? That can only happen if a_i % k == 0? Actually d = (k - a_i%k) % k. If a_i%k == 0, d=0. But those are already divisible, so we don't need to include them. So for elements that require op1, d will be in [1, k-1] because if a_i%k != 0 then (k - a_i%k) mod k is between 1 and k-1 inclusive. So d is never 0 for required elements. So we don't need to assign t=0. But could we voluntarily assign to an element with d=0? That would be an element already divisible, and we might assign t=0? But as argued, it's not necessary. So in the minimal solution, we will not include any d=0 assignments. So our set of required residues are all in 1..k-1. However, note that k could be 1. If k=1, then every integer is divisible by 1, so all a_i are already divisible. So answer 0. But what if k=1 and some a_i? Since any integer mod 1 = 0, so all are divisible. So answer 0. In our algorithm, we compute d = (1 - a_i%1) %1? a_i%1 is 0, so d=0. Since we skip divisible ones, count_d empty, ans=0. Good.
If k > 1, required d are from 1 to k-1.
Now, the derived formula seems straightforward. However, we should double-check with tricky cases.
Edge case: large counts, large k. The formula might overflow 64-bit if we compute k*(cnt-1). k up to 1e9, cnt up to n up to 2e5. So product up to 2e5 * 1e9 = 2e14, which fits in 64-bit (max ~9e18). So use long long.
Now, is there any scenario where the minimal m could be less than that bound? Suppose we have two residues with overlapping "last needed times" but we could schedule the largest time of one residue earlier by using a larger time from another residue? But the maximum is the max of the largest times used. If we shift an element from residue A to a larger time, that could increase the max, not decrease. If we shift an element from residue A to a smaller time, that's possible only if there is a smaller available number in that residue that is not used. But we are already using the smallest numbers. So we cannot reduce the largest time for a residue below its (c-th smallest) because we need to assign c distinct numbers from that residue. The largest assigned must be at least the c-th smallest. So the overall max is at least the maximum over residues of that c-th smallest. So the bound is necessary and sufficient.
But wait: Could there be an interaction where two residues share some numbers? No, residues mod k partition the integers.
Thus solution appears correct.
But before finalizing, let's consider a subtle point: The operation 1 can be applied at most once per index, but we are applying it exactly once to each index that needs it. Could there be a scenario where we might want to delay some operation 1 beyond its "optimal" time to reduce the maximum because of some ordering constraints? No, because the times we assign are just the move indices; we can interleave operations arbitrarily. There's no restriction that we must assign times in increasing order of residues or something. So we can assign any distinct times to indices, independent of order.
Another nuance: The process requires that we can only do operation 1 at most once per index. That's satisfied. Also, the order of moves can be arranged arbitrarily; we could do operation 1 on index i at time t_i, and then later maybe operation 1 on index j at time t_j > t_i. There is no dependency. So the assignment of times is free.
Thus the minimal number of moves is essentially the minimal L+1 where L is the smallest integer such that for each residue d, the count of numbers ≤ L that are ≡ d (mod k) is at least count_d. And as argued, the smallest such L is max_{d} ( d + k*(count_d - 1) ). But is it always exactly that? Let's test with a scenario where one residue's required count is zero, but the bound from another residue yields L = some value. For L = that max, for each residue d, cnt_d(L) = floor((L-d)/k)+1. We need to ensure that for all d, cnt_d(L) >= count_d. Since L = max_{d} (d + k*(count_d - 1)), for the residue d* that achieves the max, L = d* + k*(count_{d*} - 1). For that residue, cnt_{d*}(L) = floor(( (d*+k*(c-1) - d*)/k ) +1 = floor(k*(c-1)/k)+1 = (c-1)+1 = c, good. For any other residue d, we need to check that cnt_d(L) >= count_d. Since L >= d + k*(count_d - 1) (by definition of max), we have L - d >= k*(count_d - 1). So floor((L-d)/k) >= count_d - 1, thus cnt_d(L) >= count_d. Good. So L works.
Now, could there be a smaller L' < L that still satisfies all? Suppose L' = L - 1. Then for the residue that gave the maximum, say d0, we have L' < d0 + k*(count_{d0} - 1). So cnt_{d0}(L') = floor((L'-d0)/k)+1. Since L' - d0 < k*(c-1), floor((L'-d0)/k) <= c-2, so cnt <= c-1, insufficient. So L' fails. So L is minimal.
Thus answer = L + 1 (if any required elements) else 0.
But wait: Is there any situation where we could reduce L by using a time that is not in the arithmetic progression for a given residue? No, because the condition is t_i ≡ d_i mod k. So it must be in that progression.
Thus solution is clear.
Now, we must be careful about handling modulo zero? Already covered.
Now confirm with sample: matches.
Thus algorithm: For each test case:
- Read n, k.
- Initialize map or array (but k up to 1e9, so can't allocate array of size k; use unordered_map or map for counts of residues).
- For each a_i:
- compute rem = a_i % k.
- if rem != 0:
d = k - rem // because (k - rem) % k = k - rem (since rem>0)
increment count[d] (d in 1..k-1)
- If map empty: print 0.
- Else: compute max_val = 0. For each (d, cnt) in map:
candidate = d + (cnt - 1) * k
if candidate > max_val: max_val = candidate
- Answer = max_val + 1.
Print answer.
Check with k large and many residues.
Potential pitfalls:
- Overflows: Use long long.
- d = k - rem, but if rem == 0 we skip; else rem from 1 to k-1, so d from 1 to k-1.
- Use map or unordered_map. But number of distinct residues <= n (≤ 2e5). So using map is fine, O(n log n) total across test cases.
Now, is there any scenario where answer could be larger than simply L+1 because we also need to consider that we might have to perform additional moves after the last operation 1? But we defined m = number of moves; after last operation 1, we may still need to increase x further? But why would we need to? The condition is that all a_i must be divisible by k after all moves. After we have assigned all operation 1 at times t_i, we have performed those moves. After the last operation 1, we may have x = (last operation time) + 1 because each op1 increments x, and also there could be op2 moves after that? But if we stop at move L (where L is the largest t_i), then after that move, x = L+1 (since after L moves, x = L). Wait careful: Move indices: we start with x=0 before any move. After first move (move 0), x becomes 1. So after move t (0-indexed), x = t+1. So if the last operation 1 occurs at move L, then after that move x = L+1. But we don't need to increase x further because we only care about final array. The final array after all moves is determined by the a_i values after all operation 1 applications; subsequent moves (op2) would only increase x but not change a_i. So we can stop exactly after the last operation 1. However, note that if the last operation 1 is at time L, we have performed L+1 moves (from 0 to L inclusive). So total moves m = L+1. That matches our formula. So no extra moves needed.
Now, could there be a scenario where we need to perform extra moves because after the last operation 1, some a_i might not be divisible yet? But they should be, because we designed the times to make them divisible. So no.
Thus answer = (max over d of (d + k*(cnt[d] - 1))) + 1.
But wait, what if some element requires d such that d + k*(cnt-1) yields a number L that is very large, but we could assign that element to a time earlier by using a different residue? No, because each element's residue is fixed.
Double-check with a more complex scenario: Suppose k=5, elements: [4,4] => both have rem 4, d=1. count_1=2. According to formula: L = 1 + 5*(2-1)=6, answer=7. Is that minimal? Let's attempt to schedule: We need two times t ≡ 1 mod 5: the smallest are 1 and 6. So we need t values 1 and 6. That means we need moves at times 0..6 inclusive? Actually t=6 is a move index, so we need moves up to 6, total moves=7. Could we do better by using different assignment? For the first element we could assign t=1, for second we must assign t=6 because only two numbers ≡1 mod5 ≤? Could we assign t=1 and t=1? No, must be distinct. So indeed need 6. Could we use t=1 and t=... wait, what about using t=11? That would be larger. So minimal max is 6. Answer 7. That seems plausible.
But is it possible to achieve with 6 moves (i.e., m=6)? Then max time L would be 5 (since m=6 => moves indices 0..5). The available numbers ≡1 mod5 in [0,5] are 1 only. So only one slot, insufficient for two elements. So m=6 impossible. So answer 7 correct.
Now consider multiple residues: k=4, elements: a1=1 (d=3), a2=2 (d=2). Count: d=3:1, d=2:1. Per residue: d=3: 3+4*0=3; d=2:2. Max=3 => answer=4. Is that feasible? Need t for d=3: could be 3. For d=2: could be 2. So times: 2 and 3. So moves indices 0..3 => 4 moves. Works. Could we do with 3 moves? Then L=2. Available for d=3: numbers ≤2 that ≡3 mod4? Only? 3 >2, none. So impossible. So correct.
Now consider scenario where one residue count is huge and others are small. The formula holds.
Thus the solution is essentially:
- Count frequencies of needed remainders d = (k - a_i % k) % k, ignoring d=0.
- ans = 0 if no such elements.
- else ans = 1 + max_{d} ( d + k * (freq[d] - 1) ).
But we should also consider that the answer could be 0 when there are no elements needing adjustment, but what about the case where there is exactly one element needing adjustment and its d maybe 0? Already handled.
Now, let's double-check the problem statement: "The first operation can be applied no more than once to each i from 1 to n." So we cannot apply operation 1 twice on same index. That's respected.
Also, we assume that we must apply operation 1 to all indices with a_i % k != 0. Could it ever be beneficial to not apply operation 1 to some such index, and instead perhaps do something else? Since operation 2 does not change a_i, the only way to change a_i is operation 1. So if a_i is not initially divisible by k, we must change it via operation 1. So indeed we must apply it.
But is there any possibility to change an a_i indirectly via some other operation? No, each operation only adds to one chosen a_i. So yes.
Thus the solution is correct.
But wait, is there any nuance about the order of operations affecting the value added? Because when we apply operation 1 to element i at time t, we add x = t to a_i. That is because before the operation, x equals the number of moves already performed. So it's exactly the move index. So we have full control over which t each element gets, subject to distinctness and each t used at most once (since each move can only do one operation 1 or just increment x). So it's exactly as modeled.
Now, we should also consider that we could possibly apply operation 1 to an element that is already divisible, which would change its value, possibly making it non-divisible, but then we'd need to later adjust it again? But we can only apply op1 once per index, so that would ruin it. So not beneficial.
Thus solution stands.
Now test with random small cases by brute force to ensure no missing constraints. We could attempt mental brute force for small n,k.
Consider n=1, k=3, a=2 -> rem=2, d=1. count_1=1 -> L = 1 + 0 =1? Actually d + k*(cnt-1)=1+0=1, answer=2. Let's simulate: we need a1 divisible by 3. Initially a1=2, x=0. Options: We could apply op1 at move0: add 0 -> a1=2, x=1 (still not divisible). Then we need to do something else? Could we apply op1 again? Not allowed. So we need more moves: maybe apply op1 later. At move0 we could instead do op2: x=1, a1=2. At move1 we could do op1: add x=1 -> a1=3, divisible, then x=2. Total moves=2. That's answer 2. Could we do it in 1 move? If we do op1 at move0, a1 becomes 2 (not divisible). If we do op2 at move0, a1 stays 2, not divisible. So 2 is minimal. Our answer gives 2, correct.
Now n=1, k=3, a=1 -> d=2, L=2, answer=3. Simulate: need to add 2 to get 3 divisible. To add 2, we need to apply op1 at time when x=2. To have x=2, we need to have performed 2 moves before that: either op2 or op1 on something else. But we only have one element, and we can only apply op1 once to it. So we need to have x=2 before applying op1. That means we need to do two op2 moves to increase x to 2, then apply op1 at move2? Let's see: start x=0.
Option: move0: op2 -> x=1, a1=1.
move1: op2 -> x=2, a1=1.
move2: op1 on a1: add x=2 -> a1=3, x=3. So 3 moves. Could we do op1 at move0? adds 0 -> a1=1, not divisible. Then we could do op2 moves later? But a1 already had op1, cannot change again. So cannot. So 3 moves needed. Our answer 3 matches.
Now n=2, k=3, a=[1,2]. a1%3=1 -> d=2; a2%3=2 -> d=1. counts: d2=1, d1=1. L = max(2+0, 1+0)=2, answer=3. Let's try to achieve in 3 moves. Need assign t for d2=2: must be ≡2 mod3, smallest 2. For d1=1: smallest 1. So t1=1, t2=2. Sequence: We have two elements, we need to apply op1 at times 1 and 2. Also we might need to ensure we have x values correct: At time 0, x=0. We can do:
move0: op2 (increase x to 1)
move1: op1 on element with d=1 (needs t=1): add 1 to a2? Actually a2 needs d=1 (since a2=2, need add 1). After move1, a2 becomes 3, x becomes 2.
move2: op1 on element with d=2 (needs t=2): add 2 to a1, a1 becomes 3, x becomes 3. Done after 3 moves. So answer 3. Could we do in 2 moves? Then max time would be 1 (since m=2 => moves 0,1). Times available: for d=2, numbers ≤1 that are ≡2 mod3? None (2>1). So impossible. So correct.
Now consider scenario where counts for same residue require careful ordering? Already handled.
Thus solution appears solid.
But is there any possibility that we could assign times not exactly to the smallest numbers in each residue class but still achieve same max? For a given residue, the minimal possible largest time assigned for that residue when assigning c numbers is indeed the c-th smallest number in that progression. So if we need to minimize overall max, we should assign each residue its smallest c numbers. That yields the overall max as the maximum over residues of (d + k*(c-1)). So correct.
Now, could we reduce the overall max by assigning some element of a residue to a larger time to allow another residue to have a smaller max? The overall max is the maximum of all assigned times. If we increase one time, the max might increase, not decrease. If we decrease a time, we might be able to reduce the max, but we are already using the smallest possible times for each residue. However, there could be a scenario where for a residue with many elements, its largest assigned time is huge, and for another residue with few elements, its largest assigned time is smaller. Could we reduce the huge one by using some times from the other residue's progression? No, because the element must match its residue. So we can't. So bound is tight.
Thus answer formula.
But wait, we need to be careful: The times we assign must be distinct across all elements. If we assign each residue its smallest c numbers, those numbers are distinct because residues differ. However, there is a potential overlap: For different residues, the numbers could coincide? Numbers are distinct if residues differ? For example, residues 2 and 4 with k=6: numbers 2 and 4 are different. In general, numbers from different residue classes mod k are distinct because if two numbers have different residues mod k, they cannot be equal. So no overlap. So assignment is valid.
Thus the algorithm is O(n) per test case.
Now, let's consider if there is any hidden trick: The operation 1 can be applied at most once per i, but we could also choose to not apply it to some i that is not divisible, but then we would never make it divisible. So we must apply to all such i. So no choice.
Thus final answer.
But wait: The problem statement says "The first operation can be applied no more than once to each i from 1 to n." So we can apply it at most once, but we can also choose to apply it zero times. So forced to apply it to non-divisible i.
Edge Cases:
-
k could be 1: then all a_i are divisible, answer 0.
-
k could be very large, up to 1e9, and a_i up to 1e9. Compute d = k - (a_i % k) if a_i%k !=0. However, careful: if a_i % k == 0, skip. else d = k - (a_i % k). That's in range 1..k-1. Use long long to avoid overflow.
-
n large, sum n ≤ 2e5, fine.
Now, what about the scenario where count_d is zero for all d? answer 0.
Implementation steps:
- Read t.
- For each test:
read n, k.
create map<int, long long> or unordered_map for frequencies (since d up to 1e9, map is fine). But note we only need to store d values that appear; use unordered_map for O(1) average, but careful: hashing large ints is fine.
For i in 1..n:
read a.
r = a % k.
if r != 0:
d = k - r // int
freq[d]++
if freq empty:
print 0
continue
long long ans = 0
for (auto &[d, cnt] : freq) {
long long val = d + (cnt - 1) * 1LL * k;
if (val > ans) ans = val;
}
print ans + 1
But careful: d is of type int up to k-1 which could be up to 1e9, still fits in 32-bit signed? 1e9 < 2^31, so int is fine. But product (cnt-1)*k could be up to 2e14, so use long long.
Now, is there any scenario where we might need to consider the order of operations? No.
But wait: The process description says "During one move, you can do one of the following two operations: 1. Choose exactly one i from 1 to n and increase a_i by x (a_i := a_i + x), then increase x by 1 (x := x + 1). 2. Just increase x by 1 (x := x + 1)." So after operation 1, we increase x by 1. So if we apply operation 1 at time t (starting from 0), we add the current x (which is t) to a_i, then x becomes t+1. That's consistent with our model where t is the move index.
Now, think about a possible twist: Could we apply operation 1 to an element multiple times if we first apply it, then later apply operation 1 again to the same element? The problem says "The first operation can be applied no more than once to each i." So only once.
Thus solution seems done.
But wait, the sample 2 gave answer 18, we got 18. Good.
Now, double-check with sample 5: we got 8, correct.
So I'm confident.
Now, I'll consider if there is any alternative interpretation: Perhaps we could apply operation 1 to an element at any time, and the added value is x (before increment). We treat t = current x before the operation? Actually careful: Initially x=0. Move 0: if we do operation 1, we add x (0) and then increment x to 1. So the time index we used is equal to the x before the addition. After the move, x increments. So after m moves, x = m. If we apply operation 1 at a step when x = s, then we add s to a_i and then x becomes s+1. The move number (0-indexed) is s because before the move, x = number of moves already performed. Indeed after each move, x increments by 1. So if we have performed t moves already, x = t. Then we perform another move: either op1 or op2, and after that x = t+1. So the value added during op1 at that move is x before the move, which is t. So the move index (the order number of that move) is t. So the added value is exactly the move index (starting from 0). So our modeling is correct.
Now, consider the possibility of using operation 2 moves interspersed. They just increase x, effectively increasing the move index but not adding to any a_i. So they create "gaps" in the sequence of times that are not used for any op1. In our assignment, we only care about the times assigned to op1; other times are unused. So we can have L as the maximum time used; the total moves m = L+1 because we need to have performed all moves up to index L. This includes all op2 moves before the first op1, between op1s, and after the last op1? Actually if the last op1 occurs at time L, we need to have performed moves 0..L inclusive, which is L+1 moves. Among those, some may be op2. That's fine.
Thus answer.
Now, we should double-check with some custom test:
Case: n=3, k=5, a=[1,2,3] => a1%5=1,d=4; a2%5=2,d=3; a3%5=3,d=2. counts: d4=1,d3=1,d2=1. max per residue: 4,3,2 => max=4 -> ans=5. Let's try to schedule: Need times: one ≡4 mod5 -> smallest 4; one ≡3 -> smallest 3; one ≡2 -> smallest 2. So times: 2,3,4. That's L=4, moves=5. Is there a schedule? Moves: we need to have op1 at times 2,3,4. So we need to have x values: at move0: x=0; we could do op2 to increase to 1; move1: op2 to increase to2; move2: op1 on element needing d=2 (since t=2, add 2) -> x becomes 3; move3: op1 on element needing d=3 (add 3) -> x=4; move4: op1 on element needing d=4 (add 4) -> x=5. After 5 moves, all divisible. Works.
Could we do in 4 moves? Then L=3. Available times for residues: d=4 needs number ≤3 ≡4 mod5? none (4>3). So impossible. So answer 5.
Case: n=2, k=100, a=[1,1] -> both d=99, count_99=2 -> L = 99 + 100*(2-1)=199, ans=200. Seems plausible: times needed: 99 and 199. So need 200 moves. Could we do better? If we try to schedule both at 99 and 199, 199 is needed because only two numbers ≡99 mod100 ≤199 are 99 and 199. So minimal.
Now consider a scenario where k is small and counts are large, formula yields large L. For example, n=10^5, k=2, all a_i odd => each d=1 (since odd mod2=1, d=1). count_1 = n=100000. Then L = 1 + 2*(100000-1)= 1 + 199998 = 199999, ans = 200000. That's 2e5 moves. Is that minimal? Need 100000 distinct times ≡1 mod2: the smallest are 1,3,5,..., up to 1+2*(100000-1)=199999. So max time 199999, total moves 200000. Could we do any better by using times that are ≡1 mod2 but not all odd? They are all odd. The largest odd needed is 199999. So seems right. But is there any way to use even times? No, because d=1 requires odd times. So yes.
Now think about potential pitfalls: The answer could be very large: up to when k=1e9, n=2e5, all with same residue maybe d close to k-1. Then L = (k-1) + k*(n-1) = n*k - 1. That's up to 2e5 * 1e9 = 2e14, which is 200 trillion. That's within 64-bit (9e18). So long long is fine.
Now, the solution is trivial. But is it really that simple? Let's search memory: This problem is Codeforces Round # something, maybe problem "Add to Neighbour and Remove" no. I recall a problem "MEX and Array" but not. Actually I think this is from Codeforces Round #1385? Not sure. Anyway, it seems straightforward.
But before finalizing, let's reflect if there could be a scenario where we could avoid using the smallest numbers for a residue, but instead use a later number, to allow another residue to use a smaller number, thus reducing overall max? Wait, the overall max is the maximum of all assigned times. If we have two residues with high counts, maybe we can assign one residue's later times to earlier numbers of other residues? No, because numbers are fixed by residue. For residue A, the set of available times is A, A+k, A+2k,... . If we decide to not use the smallest number for residue A and instead use a larger one, that would increase the max if that larger number is the new maximum. But perhaps if the largest time currently comes from residue A, we could reduce its max by giving it a smaller number? But we are already using the smallest possible numbers for each residue. The smallest numbers for residue A are the only ones that minimize its maximum. If we use a larger number for some element of A, the maximum for A might increase (if we replace a smaller number with a larger one) or stay the same if we