讲解:https://www.cnblogs.com/YangKun-/p/12618922.html
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define ll long long
using namespace std;
const ll inf=1e17;
ll a[200009];
ll cnt[200009];
ll sumq[200009],sumh[200009];
int main()
{
int n,k;
ll ans=inf;
scanf("%d%d",&n,&k);
for(int i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
}
sort(a+1,a+1+n);
for(int i=1;i<=n;i++) sumq[i]=sumq[i-1]+a[i];
for(int i=n;i>=1;i--) sumh[i]=sumh[i+1]+a[i];
for(int i=1;i<=n;i++)
{
if(a[i]==a[i-1]) cnt[i]=cnt[i-1]+1;
else cnt[i]=1;
if(cnt[i]>=k)
{
printf("0\n");
return 0;
}
}
for(int i=1;i<=n;i++)
{
if(i>=k)
{
ll tem1=i*(a[i]-1)-sumq[i]+k;
ans=min(tem1,ans);
}
if(n-i+1>=k)
{
ll tem2=n-i+1;
tem2=sumh[i]-tem2*(a[i]+1)+k;
ans=min(tem2,ans);
}
if(i<k&&(n-i+1)<k)
{
ll tem3=i*a[i]-sumq[i]+sumh[i]-(n-i+1)*a[i]-(n-k);
ans=min(tem3,ans);
}
}
printf("%lld\n",ans);
return 0;
}