The only difference between easy and hard versions is the number of elements in the array.
You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋).
You can perform such an operation any (possibly, zero) number of times with any a_i.
Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array.
Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists.
Input
The first line of the input contains two integers n and k (1 ≤ k ≤ n ≤ 2 ⋅ 10^5) — the number of elements in the array and the number of equal numbers required.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the i-th element of a.
Output
Print one integer — the minimum possible number of operations required to obtain at least k equal numbers in the array.
Examples
Input
5 3
1 2 2 4 5
Output
1
Input
5 3
1 2 3 4 5
Output
2
Input
5 3
1 2 3 3 3
Output
0
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve the problem: Given n up to 2e5, each a_i up to 2e5, we can apply operation: replace a_i by floor(a_i/2). We can apply any number of times to each element. We want at least k equal numbers (i.e., we want to achieve an array where there exists some value v such that at least k elements equal v). Minimize total number of operations across all elements.
We can think: For each original value x, we can generate a sequence of values by repeatedly dividing by 2: x, floor(x/2), floor(x/4), ... until 0. For each possible target value v, we can check how many elements can be turned into v and at what cost (operations). Then find minimal total cost to get at least k elements equal to v. Since n and max values are up to 2e5, we can process all possible v efficiently.
Observations: Values up to 2e5, after repeated halving, we get O(log max) steps per element, so total sequences length O(n log max). That's okay: n=2e5, log2(2e5) ~ 18, so ~3.6e6 steps. But we need to compute for each v the sum of smallest costs among k elements? Actually we need minimal total operations to get at least k elements equal to v. For a given v, we consider each original element: can we turn it into v? Yes if by repeatedly dividing we eventually hit v. The cost is the number of divisions needed (i.e., the number of times we need to apply halving to get from original to v). If we can get to v via multiple paths? Actually there is a unique path because we only divide by 2 rounding down; starting from x, the sequence is deterministic: x, floor(x/2), floor(x/4), ... So v appears in that sequence if and only if by repeatedly halving x we get v. Since halving reduces the number, v must be ≤ x, and the binary representation? Actually it's like we right shift x by some number of bits, but with floor: floor(x/2^t) = v. So the cost t = min{t : floor(x/2^t) = v}. Since floor is monotonic, t is unique if exists. But also could be multiple t? Could we have floor(x/2^t1) = floor(x/2^t2) = v for t1<t2? Possibly if after some point further divisions keep giving same value? That can happen if v=0, but for v>0, eventually floor(x/2^t) will become 0. But if v>0, it might appear only once? Let's test: x=5, floor(5/2)=2, floor(5/4)=1, floor(5/8)=0. So 2 appears only once. x=6: floor(6/2)=3, floor(6/4)=1, floor(6/8)=0. So 3 appears once. x=2: floor(2/2)=1, floor(2/4)=0. So 1 appears once. x=3: floor(3/2)=1, floor(3/4)=0. So 1 appears once. x=4: floor(4/2)=2, floor(4/4)=1, floor(4/8)=0. So 2 appears once. x=1: floor(1/2)=0. So 1 appears only at t=0. For v=0, it appears for all t >= something? Actually floor(x/2^t) = 0 for all t sufficiently large, but the cost to get 0 is the smallest t such that floor(x/2^t) = 0? But we could also get 0 with larger t but that would be extra operations, wasteful. So for each original x and target v, the minimal operations needed is the smallest t such that floor(x/2^t) = v, if such t exists. If v=0, the minimal t is the smallest t where floor(x/2^t)=0, which is floor(log2(x))+1? Actually if x>0, then floor(x/2^t)=0 when 2^t > x, so minimal t = floor(log2(x)) + 1. For x=1, t=1 gives 0. So we can compute for each x the chain and record for each value encountered the number of steps needed. Then for each value v, we have a list of costs from those elements that can become v. To get at least k elements equal to v, we need to pick the k smallest costs among these (if list size >= k) and sum them; that sum is the minimal total operations to have at least k v's (since we can individually choose which elements to convert to v, and we'd convert those with smallest costs). Note that we can also leave some elements as they are? But we need at least k equal numbers. If some element already equals v (cost 0), we include them. If we have more than k elements that can become v, we pick the cheapest k. So answer = min over v of sum of smallest k costs among all elements' costs to reach v.
We need to compute efficiently for all v. Since max a_i = 2e5, v can range up to maybe 2e5 as well (since we can't increase values, only decrease, so v cannot exceed max original a_i? Actually it could be something like from dividing a larger number to a value that is not originally present? But all generated values are ≤ original numbers, so v can be up to max(a_i) (200k). Also v can be 0 (since we can reduce to 0). So v in [0, 200000]. We'll compute for each v a vector of costs? That would be memory heavy: for each v, we store costs from all elements that can become v, but each element contributes to O(log a_i) different v's. So total contributions = O(n log max) ~ 3.6e6, which is okay. We can have an array of vectors for v from 0 to 200000, each initially empty, then for each a_i, generate its chain and push cost (number of steps) to vector for each v encountered. Then for each v, sort its vector and compute sum of smallest k if size >= k, and keep global minimum.
But sorting each vector individually: total size of all vectors is O(n log max) = ~3.6e6. Sorting each vector independently could be expensive if many vectors have small sizes; overall O(∑ m_v log m_v). Since sum m_v = M, the maximum possible sum of m_v log m_v is when distribution is uneven? However we can sort each vector using standard sort; total complexity should be acceptable for M=3.6e6. However worst-case: n=2e5, each a_i = 200000, then each chain length: floor(log2(200000)) +1 ≈ 18+1=19? Actually 2^17=131072, 2^18=262144 >200000, so max steps = 18? Let's compute: Starting from 200000, floor division by powers: t=0:200000, t=1:100000, t=2:50000, t=3:25000, t=4:12500, t=5:6250, t=6:3125, t=7:1562, t=8:781, t=9:390, t=10:195, t=11:97, t=12:48, t=13:24, t=14:12, t=15:6, t=16:3, t=17:1, t=18:0. So length including 0 is 20? Actually t=0 to t=18 inclusive is 19 values? Let's count: t=0:200000, t=1:100000, t=2:50000, t=3:25000, t=4:12500, t=5:6250, t=6:3125, t=7:1562, t=8:781, t=9:390, t=10:195, t=11:97, t=12:48, t=13:24, t=14:12, t=15:6, t=16:3, t=17:1, t=18:0. That's 19 steps? Actually number of distinct values? Many could be distinct. But even if each element yields about 19 contributions, M ≈ 3.8 million. Sorting each vector individually: total m_v sum = M. Sorting cost: For each v, O(m_v log m_v). The sum of m_v log m_v is maximized when one v gets all M, giving M log M ~ 3.8e6 * 22 = ~84 million, which is acceptable. But if spread out, the logs are smaller, but sum of m_v log m_v is at most M log M (since log is concave? Actually by convexity? Let's think: For fixed sum M, the sum of f(m) where f(m)=m log m is maximized when distribution is as uneven as possible because f is convex (f''(x)=1/x >0 for x>0). So the maximum sum occurs when one v has all M and others have 0. So worst-case is M log M ≈ 3.8e6 * log2(3.8e6)/ln? Actually log2(3.8e6) ~ 22. So 3.8e6*22 = 83.6e6 operations, which is fine. With n=2e5, maximum M could be larger: a_i max 2e5, chain length up to about 18? Actually for a_i=1, chain: 1,0 => 2 values. For a_i=200000, chain length 19 (including 0). So average maybe ~10? So M ~2e6. But let's be safe: 2e5 * 19 = 3.8e6, indeed. So sorting all vectors is fine.
But we can also use a more efficient approach: we don't need to sort all vectors; we can for each v maintain a min-heap of size k? But we need sum of smallest k. Could process contributions and keep top k for each v using a max-heap of size k, and maintain sum. But there are many v's (200k). The total operations would be M insertions into heaps of size at most k, each insertion O(log k). But k up to n=2e5, so worst-case k large. Sorting each vector after we collect all contributions might be simpler and efficient enough. However we need to be careful about memory: storing vectors of ints for each v: 200001 vectors. Each vector has overhead. But total number of integers stored is ~4e6. That's okay (4e6 * 4 bytes = 16 MB). However vector overhead: 200k vectors each with small capacity might be large if each vector has its own small buffer. In C++, a vector object is typically 24 bytes. 200k * 24 = 4.8 MB, plus allocated storage, fine. So straightforward approach works.
But note: The problem statement says "The only difference between easy and hard versions is the number of elements in the array." In easy version n <= 2e5? Actually typical Codeforces problem "Make Them Equal" (both easy and hard) have n up to 2e5 in hard version and maybe 2e5 in easy? Actually sometimes easy version has n <= 2e3, hard up to 2e5. But here both are 2e5? Actually the problem statement given says n ≤ 2⋅10^5, so both? Probably they have two versions with same constraints? Actually typical Codeforces problem 1157C? Let's recall: There is a problem "Make Them Equal" (CF round #1152?). Actually there is problem "Make Them Equal" where n up to 2e5 and a_i up to 2e5, easy version had n up to 2e3 maybe. But here they gave the same constraints? In any case, our solution works for n=2e5.
But careful: For each element, we generate values until 0. However note that values can become 0. For v=0, we can get many contributions. Also, v can be > max? Actually v cannot be larger than original max, because we only divide. So v range is [0, maxA], where maxA = 200000.
One nuance: For each element, we might generate duplicate values? As argued earlier, for positive v, duplicates may occur? Let's test: x=2: sequence: 2,1,0. No duplicate positive. x=3: 3,1,0. x=4: 4,2,1,0. No duplicates. x=5: 5,2,1,0. x=6: 6,3,1,0. x=7: 7,3,1,0. x=8: 8,4,2,1,0. So it seems positive values appear only once because floor(x/2^t) is strictly decreasing until it hits 0? Not strictly? For x=0? But a_i >=1. For x=1: 1,0. So strict until 0. Actually floor(x/2^t) is non-increasing; can it stay same for two consecutive t? Possibly if x is 0? For positive x, floor(x/2^{t+1}) = floor( floor(x/2^t) /2 )? But consider x=1: floor(1/1)=1, floor(1/2)=0, different. x=2: floor(2/1)=2, floor(2/2)=1. x=3: floor(3/2)=1, floor(3/4)=0. So no equal positives. However what about x=0? Starting from 0, but a_i >=1 initially. So positive values are distinct along the chain. So each element will contribute at most one cost per positive v. So we can safely push cost for each encountered v, no duplicates.
But what about v=0? It will appear at the end; we should include that as well. However, if we generate until we hit 0, we get a cost t for 0. That t is the minimal steps to get 0. So we include 0 in the list. But could there be multiple ways to get 0 with more steps? That would be extra operations, but we don't need to consider them because we only record the minimal cost to reach each v for that element. So it's fine.
Now we need to compute the chain efficiently. For each a_i, we can loop: while (x > 0) { record for current x with current steps (starting from 0); then x = x/2; steps++; } After loop, record for x=0 with steps? Actually when x becomes 0, we need to record for 0 as well. The loop above: while (x) { record; x/=2; } This records for all positive values but not for 0. After loop, x is 0, steps = number of divisions performed. We can record for 0 as well. But careful: In this process, for an element, we record for each value encountered (including 0) the steps taken so far. However, for 0, the steps is the number of divisions needed to get to 0 from original. That is minimal because we stop when 0. So it's fine.
Alternatively, we can generate chain until 0 and record all values. Implementation details: For each a_i, we have variable steps = 0, cur = a_i. Then we do: while (true) { record (cur, steps); if cur == 0 break; cur /= 2; steps++; }. This will include 0 as well.
But we must ensure we don't go beyond max possible v? 0 is fine. v could be up to max original, which is 200000. Actually when we divide, values might become larger than max? No, they decrease. So v in [0, 200000] okay.
Now we need to store costs for each v. We can have vector costs[MAX_V+1]. MAX_V = 200000. But we also may need up to 200000 maybe plus some? Actually values from division might go up to original a_i which is ≤ 200000. So we can allocate array of vectors of size 200001.
But memory: 200001 vectors, each initially empty. When we push_back, it will allocate memory. Total pushes 3.8e6, that's okay.
After building the vectors, we iterate v from 0 to 200000, and for each, if size >= k, we sort the vector and compute sum of first k elements. Keep global minimum.
Complexities: O(n log max + ∑ m_v log m_v). Should be fine.
Edge Cases: k=1 -> answer is 0 because we can leave one element unchanged. But our algorithm will compute min sum of smallest 1 cost for each v, which is min over v of min cost to turn any element to v. That includes 0 operations if some v already present. So it works.
Now we need to implement.
But wait: Is there any tricky part? For each element, we might generate many duplicates? For v=0, it appears only once, as argued. However, consider a_i=0? But constraints say a_i >=1 initially. So fine.
But we should also consider that for each v, we only need k smallest costs. Could there be a case where using more than k elements to achieve the target yields fewer operations? No, because we need at least k, not exactly k. Using extra elements would only increase total operations (since costs are non-negative). So we always pick exactly k with smallest costs.
Now, one more nuance: Could we do better by using different operations? The operation is only dividing by 2. So each element can only go down. So our approach covers all possibilities.
Thus the algorithm is correct.
Now we need to implement efficiently. n up to 200k, a_i up to 200k.
Pseudo:
read n, k.
maxA = 200000 (or compute from input).
vector costs[maxA+1]; // but static array of vectors? Use vector<vector> costs(maxA+1) but that allocates all vectors at once, might be okay? 200k vectors, okay.
Alternatively, we can use a map? Not needed.
Initialize costs as array of vectors. In C++, we can do:
const int MAXV = 200000;
vector costs[MAXV+1]; // but this is array of vectors, not allowed? It is allowed, but we need to know size at compile time. We can define MAXV = 200000 and then vector costs[MAXV+1]; Actually that's a fixed-size array of vectors, each default constructed. That's fine.
But note: In some compilers, large local array might cause stack overflow. Better to declare globally or static. We'll declare as global: vector costs[200001]; That may be large but each vector is small object? Actually global array of vectors is fine because each vector is constructed at program start; they'll allocate small internal buffers? Usually vector default constructor doesn't allocate memory. So total memory for array of vectors: 200001 * (maybe 24 bytes) ~ 4.8 MB, okay.
Alternatively, we can use vector of vectors: vector<vector> costs(MAXV+1); but that constructs all vectors, same memory.
But we also need to store ints.
Implementation steps:
int n, k;
cin >> n >> k;
int a;
for(int i=0; i<n; i++) {
cin >> a;
int cur = a;
int steps = 0;
while (true) {
costs[cur].push_back(steps);
if (cur == 0) break;
cur /= 2;
steps++;
}
}
Now iterate v from 0 to MAXV:
if(costs[v].size() >= k) {
sort(costs[v].begin(), costs[v].end());
int sum = 0;
for(int i=0; i<k; i++) sum += costs[v][i];
ans = min(ans, sum);
}
Print ans.
Complexities: Sorting each vector: We can use partial_sort? But sort is fine.
But we need to be careful: For v=0, costs[0] may be huge: n elements each contribute one cost. That's up to 200k entries. Sorting that is O(200k log 200k) ~ 200k*18 = 3.6 million operations, fine.
But what about v=1? Many elements can become 1: For any a_i >=1, by repeated division eventually becomes 1 (unless 0). So costs[1] may have n entries, up to 200k. Sorting 200k entries is fine.
Similarly for other small numbers. So overall sorting may be okay.
But we might optimize by using nth_element or partial sort to get smallest k only? But we need sum of smallest k, we could use nth_element and then accumulate first k. That reduces average cost from sorting full vector to O(m) + O(m log k?) Actually nth_element is linear on average to find k-th element, then we can sort first k or just accumulate with condition. But simpler: sort whole vector, since m log m is not too high. But we must check worst-case: if many v have m ~ n? Actually each element contributes to about log a_i different v's. So each element appears in about log different vectors. So the sum over v of m_v is M ~ n log max. For a given v, m_v could be as high as n (if v is small like 0,1,2...). But can multiple v have m_v = n? For v=0 and v=1, maybe both have n contributions? Let's see: For any a_i >0, after enough divisions you get 1 then 0. So yes, for v=1, every element eventually becomes 1 (except maybe if a_i=0 but not the case). So costs[1] size = n (200k). Similarly v=0 also size = n? Actually for a_i >0, after enough divisions you get 0, so yes costs[0] also size = n. v=2? Many elements can become 2, but not all: those that are >=2 and after some divisions become 2. For instance, a_i=1 cannot become 2 because dividing only reduces. So costs[2] size less than n. However v=3, etc. So there can be several small numbers that have close to n. How many such v? For v <= some threshold, many elements can become v. For each v, the condition for an element a to be able to become v is that v is in the set of values obtained by repeatedly dividing a. That's equivalent to that v <= a and that v appears in the chain, i.e., that after some number of divisions we get exactly v. This is like: there exists t such that floor(a/2^t) = v. This is equivalent to v being in the set of values in the binary representation? Actually it's like v is the prefix of a when expressed in binary (right shift). More precisely, floor(a/2^t) = v => a in [v*2^t, (v+1)2^t -1]. So for a given v, the numbers a that can become v are those in intervals [v2^t, (v+1)2^t -1] for t>=0. So the count of a that can become v is sum over t of count of a in that interval. For small v, many t intervals might cover a large range, so many elements can map to it. For v=0, intervals: for t such that 02^t=0 to (1)*2^t -1 = 2^t -1. So a in [0,2^t-1] become 0 after t steps? Actually for a in [0, 2^t-1], floor(a/2^t) = 0. But note that for a>0, the minimal t to get 0 is floor(log2(a))+1. But if we record minimal cost, we need only the minimal t for each element to become 0. So our costs[0] includes exactly one cost per element, which is the minimal t to get 0. So that's okay. But if we consider contributions to v=1: For each element a, the minimal t to get 1 is the smallest t such that floor(a/2^t)=1. That exists if a>=1, but for a=1, t=0; for a=2,3, t=1; for a in [4,7], t=2? Actually floor(4/4)=1, floor(7/4)=1, so t=2; for a in [8,15], t=3; etc. So for each a>=1, there is a unique minimal t to become 1. So yes, every element contributes to v=1 with some cost. So costs[1] size = n.
Similarly v=2: For a=2, t=0; a=3, t=1? floor(3/1)=3, floor(3/2)=1, floor(3/4)=0, so doesn't become 2. Actually does 3 become 2? floor(3/1)=3, floor(3/2)=1. So 2 never appears. So not all a become 2. However, many a become 2: a=2 (0 steps), a=4,5 (since floor(4/1)=4, floor(4/2)=2 -> t=1; floor(5/2)=2 -> t=1), a=6,7? floor(6/2)=3, floor(6/4)=1; so not 2. So not all.
So there can be at most maybe O(sqrt(n)) v with size n? Actually v=0 and v=1 are the only ones that all elements can reach? Check v=0: all become 0 eventually, yes. v=1: all become 1? Consider a_i=0? not present. All positive integers eventually become 1 after enough divisions? Let's test a_i=3: sequence 3,1,0 -> yes. a_i=5: 5,2,1 -> yes. a_i=6: 6,3,1 -> yes. a_i=7: 7,3,1 -> yes. a_i=8: 8,4,2,1 -> yes. a_i=9: 9,4,2,1 -> yes. So indeed, any positive integer when repeatedly halved (floor) eventually reaches 1. Because eventually you get to 1: For any integer >=1, after t = floor(log2(a)) steps, you get a value in [1,2^t? Actually after t=floor(log2(a)), floor(a/2^t) is at least 1 and less than 2? Actually if a>=1, then floor(log2(a)) is the exponent such that 2^t <= a < 2^{t+1}. Then floor(a/2^t) is either 1 or 2? Actually a/2^t is in [1,2), so floor is 1. So yes, after t steps you get 1. So all positive integers become 1 at step floor(log2(a)). So every element has a cost to become 1. So costs[1] size = n.
Similarly v=0: after t+1 steps, you get 0, so all elements contribute to 0. So two vectors with size n. Possibly v=2? Not all. So only 0 and 1 are universal? Also maybe v=?? For a_i=0 not present. So yes.
Thus the total sorting cost: two sorts of size n (200k) and many smaller sorts. That's fine.
But wait: v=0 and v=1 both have n entries. Sorting each of size n is O(n log n) each, about 200k * 18 = 3.6 million comparisons, each maybe cheap.
Overall: Our algorithm is straightforward.
But careful: The value 0 is allowed, and we consider it as a possible target. However, could we get better answer with 0? Possibly if many elements can become 0 cheaply. For small numbers, becoming 0 may be cheap. For example, a_i=1 requires 1 operation to become 0. So if k=3 and we have three ones, we could make them 0 with 3 operations, but maybe another target gives 2 operations? We'll compute.
Now we should also consider that after some operations, we may have more than k elements equal to some number, but we only need at least k. So picking cheapest k is correct.
Thus the solution is as described.
But we must ensure we use appropriate data types: ans can be large. Worst-case: we might need to convert k elements each requiring up to about 18 operations (maybe more? Actually max steps to reach some v could be up to 18? For a_i=200000, to become something like 200000 itself cost 0; to become 1 cost floor(log2(200000)) = 17? Actually floor(log2(200000))=17, because 2^17=131072, 2^18=262144 >200000. So t=17 gives floor(200000/131072)=1, so cost 17. To become 0 cost 18. So max steps per element <= 18. But if we pick v that is not in the chain, we won't consider it. So maximum cost per element is at most 18. With k up to 200k, worst-case sum = 200k*18 = 3.6 million, fits in int. But we can use int.
But careful: Could there be elements that require more steps to reach certain v? For a_i up to 200k, maximum chain length includes 0, about 19 steps. So int fine.
Thus answer fits in 32-bit int.
Now, implement.
But is there any catch? The problem might be from Codeforces Round #1152? In the hard version, n <= 2e5, but a_i could be up to 2e5 as well. Our solution is O(n log max + sum m_v log m_v). This is typical for the hard version solution. Actually many solutions for this problem use this approach.
Example 2:
1 2 3 4 5, k=3
Check v=2: costs: 2->0, 3? 3 -> floor(3/2)=1 not 2, floor(3/4)=0, so no; 4->1,5->1; So costs[2] = [0,1,1] size 3 sum=2. v=3? costs: 3->0, 6? Not present; 5? floor(5/1)=5, floor(5/2)=2, floor(5/4)=1; doesn't become 3. 6? not. 7? not. 3 from 1? no. So only one element (3) cost 0, maybe others? 6? Not. So size 1. v=4? costs: 4->0, 5? floor(5/2)=2, floor(5/4)=1; no. 8? not. 2? floor(2/2)=1; no. So size1. v=1? costs: all become 1: 1->0 (since a=1 already 1), 2->1, 3->1, 4->2? Wait compute minimal steps to become 1: for a=1 cost0, a=2 cost1 (2/2=1), a=3 cost1 (3/2=1), a=4 cost2 (4/2=2, /2=1), a=5 cost2 (5/2=2, /2=1). So costs[1] = [0,1,1,2,2] size5, smallest 3 sum=0+1+1=2. So ans=2. Output 2.
Example 3:
1 2 3 3 3, k=3
v=3: costs: three 3's cost 0, also 6? Not present. So costs[3] = [0,0,0] sum=0 -> ans=0.
Matches.
Thus solution is correct.
But we need to think about optimization: In our loop for each a_i, we do while(true) with cur division. For a_i up to 200000, maximum iterations ~19, so it's fine.
Now memory: For each v vector, we will store ints. Could we avoid storing all vectors simultaneously? Perhaps we could process elements and for each v compute the smallest k costs on the fly using heaps. But sorting is simpler.
But note: If we have many vectors, we could sort each after collection. But we must be careful about using too much memory if we store vectors for all v. But it's fine.
However, we must ensure that we don't exceed memory limit (usually 256 MB). 200k vectors each with dynamic memory overhead: each vector object is about 24 bytes (on typical implementation) => 4.8 MB. The total stored integers: up to M = n * (log2(max)+1) ≈ 200k * 19 = 3.8 million ints = 15.2 MB. Plus overhead of vector capacity: may be slightly more but still below 256 MB.
Thus fine.
Now consider that max value might be less than 200000; we can compute maxA from input to reduce array size. But it's okay.
Now we should think about potential pitfalls: For each a_i, we record cost for each v, but we need to ensure we record only minimal cost for that v. Since we iterate while reducing, we first record for the original value with steps=0, then for floor(x/2) with steps=1, etc. This yields increasing steps. Since each positive v appears only once in the chain, we are fine. However, for v=0, we also record only once at the end. So each element contributes exactly once for each distinct v encountered.
Now we need to be careful about integer overflow: steps is int, fine.
Now we can implement.
But wait: For v=0, we might have a cost of 0? Only if a_i=0 initially, but a_i>=1, so cost>0. So okay.
Now final answer.
One more nuance: Could there be a scenario where using more than the minimal operations per element is beneficial? Suppose we need two numbers equal to v, and we have two elements: one can become v with cost 0 (already v), another can become v with cost 5, but also can become some other number w with cost 1 and then we could convert the first to w? No, we only have operation dividing; we cannot change numbers upward. So if we target v, we either keep some numbers as v (if they already are) or convert others to v. But we could also aim for w, which might be lower and cheaper for both. So we are exploring all v.
Could there be a scenario where we want to convert an element to a value that is not the minimal steps? For example, we could over-divide to get to the same value with extra steps, but that would never be beneficial because we want to minimize total steps. So minimal steps per element for a given v are optimal.
Thus the algorithm is correct.
Now consider the possibility of using a priority queue for each v: we could maintain for each v a max-heap of size k to keep k smallest costs. But that would require an array of heaps of size up to k each, which could be memory heavy: for each v, we'd have a heap with capacity k, but many heaps would be empty or small. However we could store per v a vector and later sort, as we are doing.
One improvement: Since we only need sum of smallest k, we could collect all costs in vectors and then use nth_element to get kth smallest, then sum all less than that and add (k-count)*kth? Actually we need sum of smallest k. We could do nth_element to partition around kth, then sort first k if needed, or just sum the first k after partition (but after nth_element, elements before kth are not sorted but are all <= kth, but we need exactly smallest k values, not all values <= kth if there are duplicates? Actually nth_element reorders such that the element at position k (0-indexed) is the k-th smallest, and all before it are <= that element, but not necessarily sorted. To sum the smallest k, we can simply sum all elements before the kth index, and add (k - number_before) * value_at_k? But careful: If there are more than k elements less than or equal to the kth, we might sum some extras? Actually nth_element ensures that the element at index k is in its sorted position, elements before are all <= that element, but they could be less or equal. However, there could be more than k elements that are <= the kth element? Wait, if the kth element is the kth smallest, then there are exactly k-1 elements that are less than or equal to it? Actually definition: After nth_element, the element at position k (0-indexed) is the element that would be in that position if sorted. All elements before are <= that element, and all after are >=. However, there could be elements before that are equal to the kth element. The number of elements less than the kth may be less than k, but the number of elements less than or equal to the kth could be more than k. For example, array [1,2,2,2,3], k=3 (0-indexed index 2). The 3rd smallest (index 2) is 2. After nth_element, the elements before index 2 could be {1,2} (two less) and maybe also some 2's? Actually it's not guaranteed that there are exactly k-1 elements before? The algorithm ensures that the kth element is in correct sorted position, but the partition may put equal elements on either side. So if there are duplicates, the kth element might be placed, but elements equal to it could appear both before and after. In typical implementations of nth_element (like std::nth_element), it's not guaranteed that the left side contains exactly the k smallest; it only guarantees that the element at nth is exactly the nth smallest, and elements before are all <= that element, and elements after are >=. However, there could be more than k elements that are <= that element. For summing the smallest k, we need exactly k smallest. One way: use nth_element, then get the value at index k (0-indexed). Then we can count how many elements are less than that value, say cnt_less, and how many equal to that value, cnt_eq. Then we need to sum all less, and from the equals we take (k - cnt_less) of them. But we would have to scan the vector to count less and eq, and also sum less. That could be done in O(m) after nth_element. Then total per v would be O(m) + O(m) (for nth_element) which is O(m) on average, which might be faster than sorting for large m. But for simplicity, sorting is fine.
Given constraints, sorting 200k size vector is cheap. So we can stick with sorting.
But we must be careful: Sorting each vector will be done individually, but we need to clear vectors after processing to free memory? Not necessary.
Now we should implement. In C++, we need to include bits/stdc++.h.
We'll declare:
const int MAXV = 200000;
vector costs[MAXV+1];
But note: MAXV+1 = 200001. But we need to ensure costs[0..MAXV] exist. We can define as vector costs[200001]; but that might be large stack if local? Better to define globally or static.
We'll define:
const int MAX_A = 200000;
vector vals[MAX_A+1];
But careful: "vector vals[MAX_A+1];" creates an array of vectors with size MAX_A+1, but if we declare inside main, it might be on stack and cause stack overflow because each vector object is small, but the array of 200001 vectors is about 200001 * (sizeof(vector)) which on typical implementations is 24 bytes, so about 4.8 MB. That might be too large for stack? Usually stack limit is 1-8 MB. So yes, it's risky. So we should declare globally (outside main) or static. Or use vector<vector> and resize. Better: declare as static within main: static vector costs[MAXV+1]; That puts the array in static data/bss? Actually static inside main is still stored in static memory? In C++, static local variables are allocated in static storage duration, not on stack. So we can do:
int main() {
const int MAXV = 200000;
static vector costs[MAXV+1];
...
}
But need to specify constant size. Alternatively, use a global variable.
We'll do: #define MAXV 200000
vector costs[MAXV+1]; // global
Now iterate.
Implementation details: When reading a_i, we generate chain:
int cur = a_i;
int steps = 0;
while (true) {
costs[cur].push_back(steps);
if (cur == 0) break;
cur /= 2;
steps++;
}
But careful: This loop will include both original value and then divided values. For cur = 0, we break after push? Actually we push 0 with steps when cur becomes 0? In loop: we push for cur, then if cur==0 break; else cur/=2; So if we start with cur=1: push 1 with steps=0; then cur !=0 so cur = 0, steps=1; next iteration: push 0 with steps=1; then cur==0 break. So that's correct.
Edge: a_i = 0? Not in input. So fine.
Now after building, compute ans = some large number. Could use INF = 1e9.
for (int v=0; v<=MAXV; ++v) {
if (costs[v].size() >= k) {
sort(costs[v].begin(), costs[v].end());
int sum = 0;
for (int i=0; i<k; ++i) sum += costs[v][i];
if (sum < ans) ans = sum;
}
}
cout << ans << endl;
Now think about time. Sorting 200k vectors each of possibly small size; the total sum of sizes is M. Sorting each individually can be done, but there is also overhead of many small vectors: e.g., many v with size 1 or 2, sorting such vectors is trivial. But the loop over all v (200k) is okay.
Potential improvements: We might only consider v that appear in some chain, i.e., v for which costs[v] is non-empty. But many v might be empty, but we still loop through 200k, which is fine (200k iterations, negligible).
Now we must be careful about the case where v=0. In costs[0], we push steps for each element. But is it always beneficial to consider v=0? Yes.
But check: Could there be a scenario where we need more than k elements to become v, but we might convert some element to v and leave some as is? That's what we consider.
Now test with random data. It should be fine.
Now think about potential bug: For each element, we push steps for each value encountered. But is it possible that we push duplicate for same v? We argued not for positive v, but what about v=0? It appears only at the end. So it's fine.
But one nuance: For some a_i, when we repeatedly divide, we might get the same value more than once if the value is 0? Actually if cur=0, dividing 0/2=0, would stay 0. But we break after pushing 0 and checking cur==0, we break, so we don't continue. So we don't push extra zeros. So each element contributes exactly one entry for 0.
Thus correct.
Now we need to ensure that we don't exceed array bounds: cur values can be up to original a_i, which ≤ 200000, so indexing costs[cur] is safe. But what if a_i = 200000 and we divide to get e.g., 100000, 50000, ... 0, all within 200000. So safe.
Now I think solution is ready.
But let's test with a corner case:
n=1, k=1, a=[1]. Then ans should be 0. Our algorithm: For each v that appears: v=1 cost0, v=0 cost1. costs[1] size 1>=1, sum=0 => ans=0.
n=200000, k=200000, all a_i = 200000. Then each element can become many v's. We need to get 200000 equal numbers. Best v is 200000 itself: all are already 200000, so sum=0. costs[200000] will have n entries all 0, sort, sum first k =0. So ans 0.
Now test scenario where we need to use v=0: Suppose n=3, k=3, a=[1,2,3]. Then options: v=1: costs: [0,1,1] sum=2. v=0: costs: [1,2,2]? Let's compute: 1->0 cost1, 2->0 cost2? Actually 2: steps:2 (2->1->0) cost2, 3: steps2 (3->1->0) cost2? Actually 3: 3->1 (1 step), 1->0 (1 step) =2. So sum=1+2+2=5 >2. So v=1 better.
v=2: costs: [2->0, 3? can't, 1? can't] only one element -> not enough. So ans=2.
Ok.
Now consider scenario where we need to use v=0 if many small numbers: e.g., [1,1,1,100,100], k=3. v=1: costs: two 1's? Actually 1's have cost0, 100's become 1 with steps: floor(100/64)=1? Let's compute: 100->50->25->12->6->3->1? That's more steps. Actually minimal steps to become 1: floor(log2(100))=6? 2^6=64, 2^7=128>100, so after 6 divisions, floor(100/64)=1, so cost 6. So costs[1] = [0,0,6,6]? Wait we have two 1's? Actually there are three 1's? Input: 1,1,1,100,100. So three 1's: cost0 each, two 100's: cost6 each. So smallest 3 sum=0+0+0=0? Actually there are three 1's already 1, so we can take them: sum=0. So ans 0. So v=0 not needed.
Now scenario where v=0 might be optimal: Suppose [1,2,3,4,5], k=4. v=1: costs: [0,1,1,2,2] smallest 4:0+1+1+2=4. v=0: costs: [1,2,2,3,3]? Compute: 1->0:1; 2->0:2; 3->0:2; 4->0:3? 4: 4->2->1->0? Actually steps: 4->2 (1), 2->1 (2), 1->0 (3) cost3. 5: 5->2 (1), 2->1 (2), 1->0 (3) cost3. So costs[0]=[1,2,2,3,3] sum smallest 4=1+2+2+3=8 >4. So v=1 better.
Now maybe v=2: costs[2]=[0? from 2, from 4? cost1, from 5? cost1] and maybe? 2->0, 4->1,5->1, plus maybe others? 1 cannot become2, 3 cannot. So costs[2] = [0,1,1] only 3 elements, not enough. So v=1 gives ans=4.
Now consider tricky: n=200000, k=100000, many numbers random. Our algorithm will compute.
Now we should check time: For each element, we do a loop of ~18 iterations, pushing into vector. That's ~3.6M push_backs. Each push_back may cause reallocation of the vector if capacity exceeded. But since we push many values into the same vector, those vectors will grow, and each reallocation might copy elements. But total number of reallocations across all vectors is not huge; we can reduce by reserving capacity if we know approximate sizes? But we don't know in advance. However it's fine.
But we can improve by first counting frequencies of each original a_i, because many elements may have the same value, and they would contribute the same chain. But n is 200k, not necessary.
Nevertheless, we could optimize: For each distinct a, we compute its chain and push the cost multiple times for duplicates. But that's similar.
Given constraints, it's fine.
Now we must produce final code.
But wait: There's also the possibility that we can get k equal numbers by using different operations? The operation is only divide by 2. So nothing else.
Now one more nuance: The target v can be any integer that appears in the chain, including those that are not present originally. So we are considering all.
Now we should test with max values to ensure no TLE.
Now I will implement.
Potential pitfalls:
Using global array of vectors: vector costs[MAXV+1]; But MAXV is 200000, so array size 200001. In global scope, it's fine.
Loop: for(int v=0; v<=MAXV; ++v) but if we used MAXV=200000, inclusive.
Sorting each vector: use sort(begin, end). Could also use partial_sort if we want, but not needed.
ans initialization: set ans to a large number like INT_MAX or 1e9.
Now I think solution is correct.
But there might be a more optimal solution that uses DP or BFS? But this is the intended solution for the hard version I think.
Let's verify with sample test.
Now code.
But one more thought: The constraints: a_i up to 2e5, n up to 2e5. So max v is 2e5. But what about v values that are > max? Not needed.
Now we can output ans.
Edge: k could be 0? Actually k >= 1, so fine.
Now we finalize.
But I recall that in some Codeforces editorial, they used an approach: For each possible x, compute for each a_i the minimal steps to get x, then sort those steps, etc. That's exactly our approach.
Now one more nuance: The operation allows dividing any number of times, and we can achieve 0. Our algorithm includes v=0, so it's correct.
Now let's consider test where answer may be large: n=200000, k=200000, all a_i=199999 (odd). Best v might be 0? But we can also get 1 cheaply: each becomes 1 after floor(log2(199999)) ~ 17 steps, sum ~ 3.4M. v=0: steps to 0 = 18 each, sum ~3.6M. v= maybe 199999 itself cost0, so ans=0. So not large.
Worst-case sum maybe about 200k * 18 = 3.6M.
Now potential pitfalls: We use int for sum, but max sum may be 3.6 million, fits.
Now we produce final answer.
But we must be careful: In some cases, a_i may be up to 1e9? The problem says a_i ≤ 2⋅10^5. So fine.
Now we can write final code.
Testing with sample.
Now one more improvement: Since we only need sum of smallest k, we can sort only first k elements? Actually we need the smallest k, so we could use nth_element to find kth and then sum all <= that appropriately. But it's fine.
But we need to be mindful that for vectors with large size (n=200k) and k close to n, sorting whole vector is O(n log n). That is about 200k * log2(200k) ~ 200k*18 = 3.6M comparisons, fine.
Now I'll write code.
Potential bug: In the while loop, we push steps for each cur, including cur=0. But after we push for cur=0, we break. That's correct. But note that when cur becomes 0, we have already incremented steps to the number of divisions to get to 0. That's correct.
But there is also possibility: if a_i=0 initially (not in input), then our loop would push 0 with steps=0 and break. Not relevant.
Now we can also use do-while: do { costs[cur].push_back(steps); if(cur==0) break; cur/=2; steps++; } while(true); That's similar.
Now let's test with a small case: a=1. Steps: start cur=1, steps=0. Push costs[1].push(0). cur!=0 => cur=0, steps=1. Next iteration: push costs[0].push(1). cur==0 break. So costs[1]=[0], costs[0]=[1]. Good.
Now a=2: cur=2 steps0 push2; cur/=2=1 steps1; push1; cur/=2=0 steps2; push0; break. So costs[2]=[0], costs[1]=[1], costs[0]=[2].
Now a=3: cur=3 steps0 push3; cur=1 steps1 push1; cur=0 steps2 push0; break. So costs[3]=[0], costs[1]=[1], costs[0]=[2].
Now a=4: cur=4 steps0 push4; cur=2 steps1 push2; cur=1 steps2 push1; cur=0 steps3 push0; break. So costs[4]=[0], costs[2]=[1], costs[1]=[2], costs[0]=[3].
Now a=5: cur=5 steps0 push5; cur=2 steps1 push2; cur=1 steps2 push1; cur=0 steps3 push0; break. So costs[5]=[0], costs[2]=[1], costs[1]=[2], costs[0]=[3].
Now a=6: cur=6 steps0 push6; cur=3 steps1 push3; cur=1 steps2 push1; cur=0 steps3 push0; break. So costs[6]=[0], costs[3]=[1], costs[1]=[2], costs[0]=[3].
So indeed each element contributes to O(log a) vectors.
Now we need to ensure we include v=0 in our loops. Yes.
Now answer for sample: Should be correct.
Now let's think about possible improvements: Actually, there might be an even more efficient solution: For each v, we can accumulate costs in a bucket and then sort. That's what we have.
Now, the memory: The global array of vectors: 200001 vectors, each with default constructor. That may take time to construct? But it's global, so zero-initialized? Actually vector default constructor constructs empty vector, so it's fine.
But note: In some compilers, declaring a global array of vectors of size 200001 may cause long compilation? It's okay.
Now I think we are done.
But before finalizing, I'll double-check the problem statement: "You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋). You can perform such an operation any (possibly, zero) number of times with any a_i. Your task is to calculate the minimum possible number of operations required to obtain at least k equal numbers in the array. Don't forget that it is possible to have a_i = 0 after some operations, thus the answer always exists."
Yes.
Now I'll consider if there is any scenario where it's beneficial to convert an element to a value that is not the minimal cost for that v? For example, you might want to convert an element to a value v with more operations than necessary to free up another element? But operations are independent; converting an element to v with extra operations doesn't help anything, because you could always stop earlier to get some other value, but not v. The target v is fixed. So to achieve v, you need that element to be exactly v. If you overshoot (i.e., divide too many times), you might get a lower number, which is not v (unless v=0 and you go further, still 0). For v>0, extra divisions will change the value to something else, so you wouldn't get v. So for a given target v (v>0), you must stop at the exact step where the value becomes v. The minimal steps is the only way to get v; any more steps would yield a lower value, not v. So it's unique. For v=0, extra divisions keep value 0, so you could achieve 0 with more steps, but minimal steps is enough. So using minimal steps is optimal.
Thus algorithm stands.
Now we implement.
Potential minor optimization: To avoid iterating over all v up to MAXV (200k) if many are empty, we could store list of v that have been modified. But it's not necessary.
Now let's test with a random scenario to ensure no off-by-one.
We'll write a quick mental test: n=2,k=2, a=[3,4].
Possible v:
v=3: costs: [0] from 3, 4 cannot become 3? 4->2->1->0, no 3. So only one.
v=4: costs: [0] from 4, only one.
v=2: costs: 3? 3 cannot become 2; 4->2 cost1, so one.
v=1: costs: 3->1 cost1, 4->1 cost2? Actually 4: 4->2->1 cost2. So costs[1] = [1,2] sum=3, but k=2, sum=3.
v=0: costs: 3->0 cost2, 4->0 cost3, sum=5.
So best is v=1 with 3 operations. Could we do better? Maybe target v= something else? v= ? Not. So answer 3. Could there be a strategy to get both 2? No because 3 cannot become 2. So answer 3. This seems correct.
Now test with [3,6] k=2:
v=3: 3 cost0, 6? 6->3 cost1 => costs[3]=[0,1] sum=1 => answer 1. That seems correct: divide 6 once -> both 3.
Now test with [5,6] k=2:
v=5: 5 cost0, 6? can't become5? 6->3->1->0, no5. So only one.
v=6: 6 cost0, 5 can't become6 (increase not allowed) -> only one.
v=3: 5? 5->2->1->0, no3; 6->3 cost1, only one.
v=2: 5->2 cost1, 6->3->1? no2. So only one.
v=1: 5->2->1 cost2, 6->3->1 cost2 => costs[1]=[2,2] sum=4.
v=0: costs: 5->0 cost3? 5->2->1->0 cost3, 6->0 cost3? 6->3->1->0 cost3, sum=6.
So best is v=1 with 4 ops. Could we do better by making both 2? 5 becomes 2 with 1 op, 6 cannot become2. So not.
What about v=4? 5 cannot become4 (5/1=5, /2=2), no. So answer 4. Could there be a strategy to get both 3? 5 cannot become3. So 4 seems correct.
Now test with [7,8] k=2:
v=7: 7 cost0, 8? 8->4->2->1->0, no7 -> only one.
v=8: 8 cost0, 7 cannot become8 -> only one.
v=4: 7? 7->3->1, no4; 8->4 cost1 -> only one.
v=3: 7->3 cost1, 8? 8->4->2->1, no3 -> only one.
v=2: 7? 7->3->1, no2; 8->4->2 cost2 -> only one.
v=1: 7->3->1 cost2, 8->4->2->1 cost3 => costs[1]=[2,3] sum=5.
v=0: 7->0 cost3? 7->3->1->0 =3, 8->0 cost4? 8->4->2->1->0 =4, sum=7.
v= ? v=6? 7 cannot, 8 cannot.
v=5? no.
So answer 5. Could we do better by making both 3? Only one can become 3 (7->3) and 8 cannot become 3, so no. Both 2? only 8 can become 2. So answer 5.
Now test with [10,10,10], k=2: v=10 costs three 0's, sum of smallest 2 =0, answer 0.
All good.
Now we can also consider that we might need to use v=0 if many small numbers: e.g., [1,1,1,100000], k=3. v=1: costs: three 0's from 1's, and 100000->1 cost? floor(log2(100000))=16? 2^16=65536, 2^17=131072>100000, so cost 16. So smallest 3 sum=0. So answer 0. v=0: costs: 1's ->1 each, 100000->? 100000->0 cost? floor(log2(100000))+1=17? So sum smallest 3 = 1+1+1=3 >0. So v=1 better.
So answer 0.
Now I think it's correct.
Now there is one more nuance: The target value v can be any integer, but we only consider those up to 200000. Could it be that a target value >200000 could be obtained? Since we only divide, we cannot increase values, so v cannot exceed max original. So v <= maxA.
Now we have to think about maximum a_i maybe 200000, but if we have values like 199999, dividing yields numbers that could be up to 199999. So v range 0..199999 if we compute max from input. But we can just use fixed 200000 for simplicity.
Now I'm going to implement.
But let me double-check: For each element, we push costs for each value visited. However, note that some values may appear in the chain more than once? As argued, for positive values, no duplicates. But what about v=0? It appears at the end. So it's fine.
Now what about if a_i is very large? Not.
Now potential time: The while loop for each element has complexity O(log a_i) ~ up to 18, but each iteration does a push_back into a vector. push_back might cause reallocation. However, overall number of push_backs is ~3.6 million. Each push_back is O(1) amortized. So fine.
Now sorting: For each v, sort. Total sort complexity maybe up to ~3.6M log average. Should run quickly.
Now we should be careful about using C++ i/o fast: use ios_base::sync_with_stdio(false); cin.tie(NULL);
Now let's write code.
But there is one more nuance: In the input, a_i can be up to 2*10^5. That's fine.
Now we need to consider that the answer always exists because we can always make all numbers 0. So there will always be at least one v (0) with at least k elements (since n >= k). So ans will be set.
Now we can finalize.
But wait: Is it possible that for some v, we have more than k elements with minimal costs but we might want to use a different set to achieve a better total? No, because we always pick the k smallest. That's optimal for that v. So we just take min over v.
Now one more nuance: Could we do better by mixing conversions to two different values? No, because we need at least k equal numbers, all must be equal. So we can't mix.
Now I think it's correct.
Now I will produce the final answer.
But before that, let's double-check the constraint: n up to 2e5, but the problem statement says: "The only difference between easy and hard versions is the number of elements in the array." In easy version maybe n <= 2e3, but we are solving hard version? It says n ≤ 2e5, so we are solving hard version.
Now all good.
Now we should think about an alternative approach: Some solutions use BFS from each number to collect counts. But ours is fine.
Now also note: Since a_i are up to 200k, the maximum steps is about 18, so we could also do DP: For each value v, we can compute total cost to get k elements to v using precomputed contributions from each a_i. But our approach is essentially that.
Now I will write final code.
But I want to consider one more improvement: For each element, we could store its chain in reverse and for each v push cost. But we are already doing it.
Now let's code.
Implementation:
#include <bits/stdc++.h>
using namespace std;
const int MAXV = 200000;
vector costs[MAXV+1];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, k;
cin >> n >> k;
for (int i = 0; i < n; ++i) {
int a;
cin >> a;
int cur = a;
int steps = 0;
while (true) {
costs[cur].push_back(steps);
if (cur == 0) break;
cur /= 2;
++steps;
}
}
int ans = INT_MAX;
for (int v = 0; v <= MAXV; ++v) {
if (costs[v].size() >= k) {
vector& vec = costs[v];
sort(vec.begin(), vec.end());
int sum = 0;
for (int i = 0; i < k; ++i) sum += vec[i];
if (sum < ans) ans = sum;
}
}
cout << ans << '\n';
return 0;
}
But wait: Could there be a case where the same v appears many times from one element due to the loop? No.
Now check: For v=0, we push steps for each element. That's fine.
Now costs[2] gets from 2(0), 2(0), 4(1), 5(1) -> [0,0,1,1] sorted, sum first 3 = 1 -> ans candidate. costs[1] gets from 1(0), 2(1),2(1),4(2),5(2) -> [0,1,1,2,2] sum first 3=2. costs[4] gets from 4(0) only? 5? not, etc. So ans=1.
Sample2: 5 3, 1 2 3 4 5. chains as earlier. costs[1] = [0,1,1,2,2] sum first3=2. costs[2] = from 2(0),4(1),5(1) -> [0,1,1] sum=2. So ans=2.
Sample3: 5 3, 1 2 3 3 3. costs[3] from three 3's (0) -> [0,0,0] sum=0. ans=0.
Matches.
Now all good.
One more nuance: In the loop, we push cur with steps. But steps is the number of divisions performed so far. For original cur, steps=0, correct. For next, steps=1, etc.
Now answer.
Now I think it's correct.
But there is a subtlety: For v=0, we push steps. But sometimes, it might be cheaper to get to 0 by doing more divisions than the minimal? No, because we only push the minimal steps (when we first reach 0). But could there be an alternative path to 0 with fewer divisions? No, minimal steps to reach 0 is unique and minimal. So it's fine.
Now about the sum: we use int, but INT_MAX for ans init. The sum can be up to about 3.6e6, so safe.
Now is there any scenario where ans could be larger than 3.6e6? Possibly if we consider v that are not in the chain? But we only consider v that appear, and each element contributes at most log2(max)+1 steps. So maximum sum is k * (max steps per element). max steps is about 18-19, so max sum about 3.8e6. So fine.
Now finalize.
But we should also think about potential improvements: We might consider using array of vectors but global: static vector costs[MAXV+1]; That might be in data segment, but it's okay. In C++, global vector array might cause dynamic initialization? The constructors for each vector will be called before main, which is fine.
Now compile and run.
Potential issue: In some compilers, MAXV = 200000; array size 200001 of vectors; each vector default constructor is O(1). So okay.
Now let's test with maximum values: n=200000, k=100000, a_i all = 200000. Then for each element, chain length = 19. So total pushes = 3.8e6. Then for each v, we sort. Many v will have few contributions. v=200000 will have 200k contributions of 0. Sorting that is 200k log 200k, fine. v=100000: maybe contributions: from 200000? Actually 200000/2=100000 with steps=1, so each element contributes to 100000 with cost 1, so that vector size = 200k, sorting that also 200k log 200k. So we will sort multiple large vectors. That might be a bit heavy but still within time: sorting 200k ints ~ 200k*18=3.6M comparisons, times maybe a few such vectors. For v=200000, v=100000, v=50000, v=25000, v=12500, v=6250, v=3125, v=1562, v=781, v=390, v=195, v=97, v=48, v=24, v=12, v=6, v=3, v=1, v=0. Actually many of these will have large sizes? Let's examine: For a_i = 200000, the chain values: 200000,100000,50000,25000,12500,6250,3125,1562,781,390,195,97,48,24,12,6,3,1,0. That's 19 values. Each element contributes to each of these 19 v's. So the number of v with size n is exactly the number of distinct values that appear in every element's chain. Since all elements are identical (200000), every v in this chain will have size = n. Because each element contributes exactly one to each v in its chain. So there will be about 19 vectors each of size 200k. So we will sort 19 vectors of size 200k each. Sorting each 200k vector is about 3.6M comparisons; 19 * 3.6M = 68.4M comparisons. That's still okay within 2 seconds? In C++, sorting 68 million integers might be borderline but probably okay given modern CPUs and the fact that comparisons are cheap. However we also have to account for sorting many other vectors from other values (but those are small). So total might be around 70-80 million comparisons, which should be okay. But we need to be cautious: In worst-case, if all a_i are the same large number, we might have about log2(max) large vectors. That's fine.
But what if a_i vary, then many v's might have size close to n? For v=1, size = n (all elements can become 1). For v=0, size = n. For v=2, maybe not all, but could be many. So at least 2 large vectors, maybe up to around log2(max) large vectors? Actually v=1 and v=0 always size = n. v=2 might be size roughly n/2? Not necessarily all. But the total sum M = n * average chain length, so average chain length about 18. So sum of sizes across v is about 18n. So if a few v have size n, the others must sum to the remainder. So maximum number of v with size close to n is limited. For example, if 19 v have size n, then total sum would be 19n > 18n, impossible. So at most average chain length v can have size n, but if one v has size n, the others have total (M - n). The maximum number of v with size n is at most floor(M/n) = floor(avg_len) = about 18. So indeed, up to 18 v could have size n if each element contributes to the same set of 18 v's. That happens when all elements are identical. So worst-case: up to 19 vectors of size n. That's okay.
Thus sorting 19 * 200k = 3.8 million integers? Actually each vector size is 200k, not 3.8M. Sorting 19 vectors of 200k ints each results in about 19 * (200k log2 200k) ≈ 19 * (200k * 18) ≈ 68.4M comparisons. That's acceptable.
Now also we have to push back into vectors, and later we iterate over 200k v's. So overall runtime should be under 1 second? Possibly 1-2 seconds but okay.
Now we need to be careful about memory: Each large vector of size 200k uses 200k * 4 = 0.8 MB. 19 such vectors use about 15 MB. Plus others, total maybe ~20-30 MB. That's fine.
Now the code is ready.
But one more nuance: The MAXV value. Since a_i up to 200000, but we may also get intermediate values like 200000/2 = 100000, etc. All within 200000. So we can set MAXV = 200000. However, if we use a_i up to 200000, and we divide, we get values like 200000,100000,50000,... all <=200000. So array size 200001 is enough.
Now I will produce final answer.
But wait: Could there be a value like 199999? Dividing yields floor(199999/2)=99999, etc. So still within 200000. So array size 200001 is safe.
Now final code.
One more thought: For better performance, we could use static vector array but we need to clear it? Not necessary.
Alternatively, we could use a single vector of pairs and then group by v after sorting by v. But that would require sorting by v, which would be O(M log M) global. That could be simpler but maybe more memory? But current method is fine.
Now I will finalize.
But we need to include for INT_MAX or just set ans to 1e9.
Now let's write final answer.
Potential bug: In the loop while(true) we push for cur, then if cur==0 break; else divide. But when cur becomes 0 after division, we will push 0 in the next iteration. That's fine.
But what about the case where a_i=0? Not present. So fine.
Now ensure we use appropriate types: steps increments up to maybe 18, but push as int.
Now final code.
But I recall that in some solutions, they use a different approach: For each v, they count the number of elements that can reach v and the total operations, using something like: for each a_i, while (a_i>0) { cnt[a_i]++; ops[a_i] += steps; steps++; a_i/=2; } and also something else? Actually we need to consider that each a_i can reach multiple v, but we only consider minimal cost for each v. In the above approach, if we simply accumulate ops for each v as we walk down, we are adding the steps from that element to reach that v. That's exactly what we are doing with pushing steps.
Now there is also a more efficient way: For each v, we can compute total minimal cost from all elements to reach v, but we need the sum of the smallest k costs. So we need the distribution.
Thus our method is correct.
Now final answer.
I'll output the code.
But before finalizing, let's test on a random small case using reasoning: n=4,k=2, a=[1,3,5,7]. Compute manually:
Possible v and costs:
v=1: costs: from 1:0, 3:1, 5:2, 7:2? Actually 7: 7->3->1 => steps 2; So costs[1] = [0,1,2,2] smallest2 sum=0+1=1
Now edge: n=200000, k=200000, all a_i=1. Then v=1: costs[1] size n, all 0, sum=0. ans=0. Good.
Now edge: n=200000, k=200000, all a_i=2. Then v=2: costs[2] all 0, sum=0. ans=0. v=1: costs[1] all 1, sum would be 200k, but not needed.
Now edge: n=200000, k=200000, all a_i=199999 (odd). v=199999: all 0, ans=0.
Now edge: n=200000, k=100000, all a_i=199999. Then v=199999: costs[199999] all 0, but we need 100k, sum=0. ans=0.
Now edge: n=200000, k=200000, all a_i random. ans might be >0. But algorithm works.
Now final.
Potential improvement: Use vector.reserve to avoid reallocation? Could compute frequency of each value? Not needed.
But we can also compute an upper bound for total contributions: For each v, we can pre-allocate roughly expected size? Not needed.
Now I'll produce final answer.
But I should also consider that the code uses INT_MAX which might be in . Include it.
Now final code:
#include <bits/stdc++.h>
using namespace std;
const int MAXV = 200000;
vector costs[MAXV+1];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, k;
cin >> n >> k;
for (int i = 0; i < n; ++i) {
int a;
cin >> a;
int cur = a;
int steps = 0;
while (true) {
costs[cur].push_back(steps);
if (cur == 0) break;
cur /= 2;
++steps;
}
}
int ans = INT_MAX;
for (int v = 0; v <= MAXV; ++v) {
if (costs[v].size() >= k) {
vector<int>& vec = costs[v];
sort(vec.begin(), vec.end());
int sum = 0;
for (int i = 0; i < k; ++i) sum += vec[i];
ans = min(ans, sum);
}
}
cout << ans << '\n';
return 0;
}
Now one more thing: When v is 0, we also consider it. But note: In our loop, for each element we push steps for cur=0 with steps = number of divisions to get to 0. That's minimal. So it's fine.
Now I think we are done.
But wait: There is a possibility that we could use a different value v > MAXV? For a_i up to 200000, max is 200000. So no.
Now I'll produce final answer.
One more test: n=2,k=2, a=[200000,200000]. Then chain for each includes 200000. costs[200000] size 2, sum=0. ans=0.
Now n=2,k=2, a=[200000,100000]. v=100000: costs: 200000->100000 cost1, 100000 cost0 => sum=1. v=200000: costs:200000 cost0,100000 cannot become200000. So only one. v=50000? costs:200000->100000->50000 cost2, 100000->50000 cost1, sum=3? Actually 100000 cost1 to become 50000 (since 100000/2=50000 steps1). So sum=1+2? Wait 200000->50000 cost2, 100000->50000 cost1 => sum=3. So v=100000 gives 1. v=1: costs:200000->1 cost? floor(log2(200000))=17 -> cost17, 100000->1 cost16? Actually 100000->1 cost floor(log2(100000))=16 -> cost16 => sum=33. So ans=1.
Now algorithm yields that.
Now final.
I'll now output final answer. ```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXV = 200000;
vector costs[MAXV + 1];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
code
int n, k;
cin >> n >> k;
for (int i = 0; i < n; ++i) {
int a;
cin >> a;
int cur = a;
int steps = 0;
while (true) {
costs[cur].push_back(steps);
if (cur == 0) break;
cur /= 2;
++steps;
}
}
int ans = INT_MAX;
for (int v = 0; v <= MAXV; ++v) {
if (costs[v].size() >= k) {
vector<int>& vec = costs[v];
sort(vec.begin(), vec.end());
int sum = 0;
for (int i = 0; i < k; ++i) {
sum += vec[i];
}
ans = min(ans, sum);
}
}
cout << ans << '\n';
return 0;