C - Not so Diverse
Time limit : 2sec / Memory limit : 256MB
Score : 300 points
Problem Statement
Takahashi has N balls. Initially, an integer Ai 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 the integers on them.
Constraints
- 1≤K≤N≤200000
- 1≤Ai≤N
- All input values are integers.
Input
Input is given from Standard Input in the following format:
N K A1 A2 ... AN
Output
Print the minimum number of balls that Takahashi needs to rewrite the integers on them.
Sample Input 1
5 2 1 1 2 2 5
Sample Output 1
1
For example, if we rewrite the integer on the fifth ball to 2, there are two different integers written on the balls: 1 and 2. On the other hand, it is not possible to rewrite the integers on zero balls so that there are at most two different integers written on the balls, so we should print 1.
Sample Input 2
4 4 1 1 2 2
Sample Output 2
0
Already in the beginning, there are two different integers written on the balls, so we do not need to rewrite anything.
Sample Input 3
10 3 5 1 3 2 4 1 1 2 3 4
Sample Output 3
3
题意:
给定N个球,每个球上都写了一个数,问最少修改多少个球上的数使得最多有K个不同的数
题解:
将数字相同的球放在一个集合中,如果集合的数量tot小于K,则修改次数为0;否则,按集合大小从小到大排序,修改前tot-K个非空集合中的数字即可。
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn=2e5+100; int par[maxn],sum[maxn]; int N,K,p,tot; void init(int n) { for(int i=0;i<=n;i++) par[i]=i; } int find(int x) { if(par[x]==x) return x; return par[x]=find(par[x]); } void unit(int x,int y) { int fx=find(x),fy=find(y); if(fx!=fy) par[fx]=fy; } bool same(int x,int y) { return find(x)==find(y); } int main() { while(~scanf("%d%d",&N,&K)) { int ans=0; memset(sum,0,sizeof(sum)); memset(par,0,sizeof(par)); tot=0; init(N); int t; scanf("%d",&t); sum[t]++; p=t; tot++; for(int i=2;i<=N;i++) { scanf("%d",&t); sum[t]++; if(!same(t,p)) { tot++; unit(t,p); } } sort(sum,sum+N+1); if(tot<=K) ans=0; else { int cnt=tot-K; int pos=lower_bound(sum,sum+N+1,1)-sum; while(cnt--) ans+=sum[pos++]; } printf("%d\n",ans); } return 0; }