AtCoder Not so Diverse 并查集&&二分



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

  • 1KN200000
  • 1AiN
  • 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

Copy
5 2
1 1 2 2 5

Sample Output 1

Copy
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

Copy
4 4
1 1 2 2

Sample Output 2

Copy
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

Copy
10 3
5 1 3 2 4 1 1 2 3 4

Sample Output 3

Copy
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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值