We need to solve: Given N up to 200,000, array A_i (values between 1 and N). We can change the integer on any ball to any integer (presumably any value, possibly same as existing? But we change to reduce number of distinct values to at most K). The objective: minimize number of balls changed.
Interpretation: Initially we have some multiset of values. We want final multiset to have at most K distinct values. We can change the value on a ball to any integer we want, but each change counts as rewriting that ball. The goal: minimize number of changes needed.
Observation: The operation is effectively: we can keep some values unchanged; for others, we can rewrite them to some value(s) that will be among the final distinct set. Since we can change to any value, we can choose to keep a subset of the original distinct values, and change all balls with other values to some kept value(s). But we could also introduce new values not present originally? That would increase number of distinct values, not helpful if we already have to reduce to at most K. So optimal solution: keep some set S of original distinct values (size <= K), and change all balls with values not in S to some value(s) in S (or possibly also to new values, but that would increase distinct count beyond |S| if we introduce new ones; but we could also introduce new values if it reduces changes? For example, suppose we have many distinct values each with small counts; keeping only top K frequencies might not be optimal if we could change some of them to a new value that consolidates them? But note: we are allowed to rewrite balls to any integer. Suppose we have many values each with count 1. If we keep K values, we must change the others. But could we instead discard all original values and create K new values, rewriting all balls? That would require N changes. That seems worse than keeping K frequent values. So introducing new values is not beneficial because it increases the number of changes: If we keep a value v, we don't change any ball that originally had v. If we replace some balls with a new value, we must change those balls anyway. But maybe by creating a new value, we could reduce the number of distinct values among the ones we keep? Actually, the requirement is only that final distinct count ≤ K. If we keep some original values, they already exist and we don't need to change those balls. If we decide not to keep a certain original value v, we must change all balls with v to something else. Whether that something else is an existing kept value or a new value, we have to change those balls. So using a new value does not reduce the number of changes compared to using an existing value? But consider that we might have more than K distinct original values; we need to get down to at most K. If we choose to keep exactly K original values, we must change all balls with other values. However, what if we keep fewer than K original values? Then we could change some of the balls from the non-kept values to some new value(s) that we introduce, but that would increase distinct count. If we keep fewer than K, we have "room" to introduce new distinct values. Could that reduce the number of changes? For example, suppose we have values with frequencies: a:100, b:1, c:1, d:1, e:1, and K=2. If we keep a and b (freq 100 and 1), then we need to change c,d,e (3 balls). But if we keep only a (freq 100) and introduce a new value X, we could change b,c,d,e to X. That would require 4 changes (since b is also changed). That's worse. But perhaps there is a scenario where it's beneficial to not keep a low-frequency value because we could change it along with others to a new value, but that still requires changes for that low-frequency value. Since we could also keep it, we would avoid changing those balls. So keeping a value never hurts: if a value is kept, we don't change its balls. If we decide to not keep it, we must change all its balls. So keeping it saves changes. Therefore, an optimal solution will keep as many original values as possible, subject to distinct count limit K. But wait: we might be forced to discard some values if there are more than K distinct original values. So we will keep exactly K original values (or all if less than K). Because if we keep fewer than K, we could additionally keep another original value without increasing changes, and that would reduce the number of balls to change (since those balls would not need to be changed). So indeed optimal is: if total distinct original values M ≤ K, answer 0. Else, we need to select K original values to keep, and change all balls with values not among those K. Minimizing number of changes is equivalent to maximizing the total number of balls whose values are kept (i.e., maximize the sum of frequencies of the selected K values). So answer = N - (maximum total frequency of K values among the distinct original values). So we need to compute frequencies of each distinct integer, then take the sum of the largest K frequencies.
But is it always optimal to keep exactly K original values? Suppose we have more than K distinct values, but maybe some values have frequency 0? Not possible. Could it be better to not keep any value (i.e., change all balls) and create K new values? That would require N changes, worse than any strategy that keeps at least one value. So no.
Therefore answer seems straightforward: Count frequencies of each A_i, sort frequencies in descending order, take sum of top K, answer = N - sum.
Check with examples:
Example1: N=5, K=2, A=[1,1,2,2,5]. Frequencies: 1:2, 2:2, 5:1. Top2: 2+2=4, answer=5-4=1. matches.
Example2: N=4, K=4, A=[1,1,2,2]. Frequencies: 1:2, 2:2. M=2 ≤K=4 => answer 0. matches.
Example3: N=10, K=3, A=[5,1,3,2,4,1,1,2,3,4]. Frequencies: 1:3, 2:2, 3:2, 4:2, 5:1. Top3: 3+2+2=7, answer=10-7=3. matches.
Thus the solution is as described.
But wait: The problem statement: "rewrite the integer on some balls so that there are at most K different integers written on the N balls." We can change any ball to any integer, not necessarily from original set. So the above reasoning holds.
Thus algorithm: count frequencies using dictionary/map (since Ai up to N, but could use array of size N+1). Then extract frequencies, sort descending, sum first K (or all if less than K). Output N - sum.
Complexity O(N log N) or O(N) with counting sort since frequencies ≤ N and values ≤ N? Actually N up to 200k, sorting distinct frequencies is O(M log M) where M ≤ N, so fine.
Double-check: Are there any edge cases? K may be 0? Constraints: 1 ≤ K ≤ N, so K≥1. Fine.
But wait: Could there be a scenario where we might want to change some balls among the kept values to another kept value to reduce distinct count? No, because we are already within K distinct values by keeping them. Changing some balls from one kept value to another would not reduce distinct count further (it might even increase if we introduce new? But we could merge two kept values into one, thereby reducing distinct count below K, but that would require changing balls from the other value. However, we are allowed to have at most K different integers. So having less than K is also acceptable. Could it be beneficial to change some balls from a low-frequency kept value to a high-frequency kept value to reduce the number of distinct values, thereby allowing us to keep another higher-frequency value? Actually, consider we have M > K distinct original values. If we decide to keep K values, we change all others. However, maybe we could keep more than K values by merging some of them: e.g., we change a few balls from one kept value to another, reducing the number of distinct values kept to K-1, then we could keep an additional original value without exceeding K. So the idea: We might not keep exactly K original values unchanged; we could keep some original values entirely unchanged, but also partially change some values to merge them, so that we can keep more than K original values? Let's think carefully.
The initial assumption: we choose a set S of original values to "preserve" meaning we do not change balls with those values. For any value not in S, we change all its balls to some value in S (or possibly to a new value). But what about balls originally in S? We might also change some of them to other values, maybe to accommodate more distinct values? That seems counterproductive: changing a ball from a kept value adds to changes, but might allow us to keep an additional original value (by not having to change its balls). So we need to consider if there's a scenario where it's beneficial to change some balls from a low-frequency value to make room to keep a higher-frequency value, because we have to limit to at most K distinct integers overall, not just among those we keep unchanged. In the original simplistic model, we treat "keep" as meaning we don't change those balls; but we could also change some balls from a value we still want to appear in the final set? That is, we might decide that in the final multiset, we want a certain set of distinct values T (size ≤ K). Some of these may be original values that we keep some balls for, but we may also change some balls originally with those values to other values, or we may decide not to keep all balls of a certain original value; but we could still have that value appear in the final set via some balls that originally had other values changed to it. So the final distinct values T are not necessarily a subset of original values; they could be new values, or they could be original values that we either preserve or recreate. However, if an original value v is not in T, we must change all balls with v. If v is in T, we could keep some of its balls unchanged, but we might also change some of its balls to other values (maybe to other values in T). That seems wasteful because it increases changes. But could it be beneficial? Suppose we have three original values: A (freq 100), B (freq 50), C (freq 1). K=2. In the simple approach: we keep top 2 frequencies: A and B, change C (1 ball) => changes=1. But maybe consider: we want final distinct values to be A and B. That's exactly that. So no improvement.
But consider: A (freq 100), B (freq 1), C (freq 1), D (freq 1). K=2. Simple: keep A and B => changes: C,D => 2 changes. But could we do better? If we keep A only, we need to change B, C, D: 3 changes, worse. If we keep A and B, but also maybe change B to A? That would make final distinct values only A, but then we would have changed B (1) to A, plus C and D to A? That's 3 changes. Not better.
Now consider: A (freq 10), B (freq 9), C (freq 9), D (freq 9). K=2. Simple: keep top2: A=10 and B=9 (or C or D) => changes = sum of the other two: 9+9=18. But could we do something like: Keep A (10) and change all B, C, D to something else? That's 27 changes. Worse. Could we keep A (10) and keep B (9) but also change some of B to something else to allow keeping C? Wait, we need at most 2 distinct values final. If we keep A and B, we already have two distinct values, so we cannot keep C as distinct unless we merge B and C into same value. To keep C's balls unchanged, we would need them to be either A or B in final. But they are originally C, so to keep them unchanged they would remain C, which would add a third distinct value. So we must change them. But what if we change some of B's balls to A, thereby reducing the distinct count of B? Actually if we change some of B's balls to A, then B's value still appears from the unchanged B balls, so we still have two distinct values. That doesn't help include C. To include C without changing C's balls, we would need to have only one distinct value among the kept set besides C, meaning we need to eliminate either A or B as a distinct value. But then we would have to change all balls of that value anyway. For example, we could decide to have final distinct values be A and C. Then we would keep A unchanged (10 balls), keep C unchanged (9 balls), change all B (9) and D (9) to either A or C. That yields changes = 9+9=18, same as previous. Or final distinct values be A only: change B, C, D to A => changes 27. So best is indeed 18.
Thus it appears that the simple "keep top K frequencies" is optimal.
But is there any subtlety about the possibility of creating a new value that allows more balls to be unchanged? For example, suppose we have many low-frequency values. By changing them all to a new value, we still have to change them all. But if we keep some low-frequency value, we avoid changes for those balls. So it's always better to keep as many balls unchanged as possible. Since any ball that we don't change retains its original value, and that original value contributes to the distinct count. So the distinct values in the final set include all original values that we didn't change at least one ball. If we change all balls of some original value, that value disappears. So the set of distinct values in the final set is exactly the set of original values for which at least one ball remains unchanged, plus possibly some new values that we introduced by changing balls to them. But if we introduce new values, then those balls were changed anyway. So the number of unchanged balls is N - (number of changed balls). And the number of distinct final values = |U| + |V|, where U is set of original values that we kept (i.e., at least one ball unchanged) and V is set of new values we introduced (by changing balls). To satisfy distinct ≤ K, we need |U|+|V| ≤ K.
We want to maximize unchanged balls. Suppose we have frequencies f_i for each original value i. If we decide to keep a set U of original values (i.e., we keep at least one ball unchanged for each in U), we might also decide to change some balls of those values to other values, but that would reduce the number of unchanged balls, which is not beneficial. So for a given U, we would keep all balls of those values unchanged to maximize unchanged balls. Thus, unchanged balls from U = sum_{i in U} f_i.
Then we have remaining balls (from values not in U) which we must change. We can change them to any values. They could be assigned to values in U, or to new values in V. However, if we assign them to values already in U, that does not increase |U|+|V|. If we assign them to new values, we increase |V|, which may cause violation of the ≤ K constraint. Since we can choose assignments arbitrarily, we would prefer to assign them to existing U to avoid adding new distinct values. But if |U| < K, we could also assign some to new values up to K - |U|. However, creating new values does not reduce the number of changed balls; those balls are changed anyway. So whether we assign changed balls to existing U or new V doesn't affect the number of unchanged balls; it only affects feasibility of distinct count constraint. So the only decision is which original values to keep (U) such that we can assign the changed balls without exceeding distinct count. If we keep |U| = L original values, we have L distinct values from them. We can assign changed balls to those L values only, resulting in total distinct count = L (since no new values). This is feasible if L ≤ K. If L < K, we could also create new values but it's not necessary. So the constraint is simply that |U| ≤ K. Because we can always assign all changed balls to any of the kept values, ensuring no new distinct values appear. (Unless we need to consider that we might want to assign changed balls to new values because we cannot assign them to kept values? But we can always assign them to any kept value; there is no restriction that a kept value cannot appear; it's just an integer. So yes, we can always assign changed balls to one of the kept values. Thus the condition is exactly |U| ≤ K. Therefore we want to choose U (subset of original distinct values) with size ≤ K to maximize total frequency sum. Since increasing size up to K only adds more frequencies, we will choose exactly K if possible (if total distinct M >= K), else all.
Thus the problem reduces to as described.
Therefore solution is correct.
Now we should implement.
Implementation Steps:
- Read N, K.
- Read list A of length N.
- Count frequencies using dict (or list of size N+1 if A_i ≤ N). Since constraints say 1 ≤ A_i ≤ N, we can use an array of length N+1.
- Create list of frequencies (positive counts).
- Sort in descending order.
- Compute sum of first min(K, len(list)) frequencies.
- Answer = N - sum.
Time complexity: O(N + M log M). Space O(N).
Edge Cases:
- K >= M: answer 0.
- N=200000, all A_i distinct => frequencies all 1, M=N. Need to pick K largest => sum = K. Answer = N - K. That's plausible.
Now confirm: The problem statement: "Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite." That's exactly it.
Thus answer is straightforward.
But wait: There is a nuance: The balls are identical except the number written. Rewriting a ball means we can change it to any integer, possibly the same as it originally had? But that would be pointless because it would count as a rewrite even if unchanged? Usually "rewrite" means you change it; you wouldn't rewrite if you keep it same. So we assume we only change balls we need to change. So we don't change balls we keep.
Thus final answer.
Now we can produce code in Python.
Implementation:
def solve():
import sys
input = sys.stdin.readline
N, K = map(int, input().split())
A = list(map(int, input().split()))
freq = [0] * (N+1) # since A_i ≤ N
for a in A:
freq[a] += 1
vals = [f for f in freq if f > 0]
vals.sort(reverse=True)
total_keep = sum(vals[:K]) if len(vals) >= K else sum(vals)
print(N - total_keep)
But careful: If N=200000, using list of size N+1 is fine. However, values could be up to N, so it's safe. However, note that A_i ≤ N, but could be up to 200000, which is same as N. So using length N+1 works.
Alternatively, we could use collections.Counter.
But need to be careful about sorting: If M is large (up to N), sorting O(N log N) is fine for 200k.
Check with examples.
Double-check with random test.
Alright.
But wait: The problem might be from AtCoder (maybe ABC). The solution I recall for similar problem is indeed sort frequencies and sum smallest M-K? Actually typical AtCoder problem: "At most K kinds" and we need to change minimum number of balls. I recall a problem: "AtCoder ABC 117 D"? Not sure. But there is a known problem: "AtCoder ABC 082 B"? No.
Actually there is AtCoder ABC 113 C? Hmm.
I think it's from AtCoder Beginner Contest 111? Not.
But the solution is exactly that.
So I will present the solution.
But wait: The problem statement: "All input values are integers." And constraints: 1 ≤ K ≤ N ≤ 200000, 1 ≤ A_i ≤ N. So as given.
Thus final answer.
Now we need to produce the final output.
I'll include explanation in answer.
But the user request: They want us to solve the problem. Possibly they want the code and explanation. The chat says: "Takahashi has N balls... Output ..." So I think they want the solution. I will provide the solution in Python with the reasoning.
Thus final message: Provide answer.
But I'll also consider if there is any hidden trick: The values A_i are up to N, but not necessarily distinct? Already handled.
Another nuance: The balls are physical, but no.
One might think about the possibility of changing a ball to a value that originally didn't exist, but as argued, that's not beneficial.
Thus final.
Now I'll produce the answer. We need to minimize the number of changes so that the number of distinct integers on the balls is at most K.
It is optimal to keep as many balls unchanged as possible.
If there are already at most K distinct values, no change is needed.
Otherwise, we must reduce the number of distinct values to exactly K by keeping K original values and changing all balls of the other values.
To minimize changes, we should keep the K values with the highest frequencies.
Thus the answer is N minus the sum of the K largest frequencies.
Algorithm
- Count the frequency of each value in the array.
- Collect the frequencies into a list.
- Sort the list in descending order.
- Take the sum of the first K frequencies (or all if there are fewer than K).
- Output N minus that sum.
Complexity
- Time: O(N log N) due to sorting (N ≤ 200000).
- Space: O(N) for frequency storage.
import sys
def solve() -> None:
input = sys.stdin.readline
N, K = map(int, input().split())
A = list(map(int, input().split()))
# frequencies: values are between 1 and N
freq = [0] * (N + 1)
for a in A:
freq[a] += 1
# keep only positive frequencies
values = [f for f in freq if f > 0]
values.sort(reverse=True)
keep = sum(values[:K]) if len(values) >= K else sum(values)
print(N - keep)
if __name__ == "__main__":
solve()