Source Code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
 
void solve(){
    int n,k;
    cin>>n>>k;
    int a[n];
    int freq[n+1]{};
    for(int i = 0 ; i<n ; i++){
        cin>>a[i];
        freq[a[i]]++;
    }
    ll sum = 0;
    for(int i = 0 ; i<=n ; i++){
        if(freq[i] == 0)break;
        if(freq[i] >= k){
            sum = k * (i+1);
        }        
        else{
            int prev = k - freq[i];
            int cur = freq[i];
            if(i)
                sum -= cur*i;
            sum += cur*(i+1);
            k = cur;
        }
    }
    cout<<sum<<endl;
}
 
int main(){
    ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    #ifndef ONLINE_JUDGE
        freopen("input.in", "r", stdin);
    #endif
 
    int tt=1;//cin>>tt;
    while(tt--)
        solve();
}
Copy
Bitar The Handy Man hashemtb
GNU G++17
7 ms
1.6 MB
Wrong Answer