Source Code
#include "bits/stdc++.h"
using namespace std;
typedef long long ll;

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);

    int n,k;
    cin>>n>>k;
    
    deque<int>dq(n);
    for(auto &x:dq) cin>>x;
    sort(dq.begin(),dq.end());

    vector<int>ans[k];
    int it=0;
    while(!dq.empty()&&dq.front()==0){
        ans[it].push_back(0);
        it=(it+1)%k;
        dq.pop_front();
    }

    it=k-1;
    while(it>=0&&ans[it].empty()){
        ans[it].push_back(dq.back());
        it--;
        dq.pop_back();
    }

    for(int i=1;i<=1e5;i++){
        it=0;
        while(!dq.empty()&&dq.front()==i){
            ans[it].push_back(i);
            dq.pop_front();
            it=(it+1)%k;
        }
    }

    ll sum=0;
    for(int i=0;i<k;i++){
        sort(ans[i].begin(),ans[i].end());
        ans[i].resize(unique(ans[i].begin(),ans[i].end())-ans[i].begin());
        int mex=0;
        for(int j=0;j<(int)ans[i].size();j++){
            if(j!=ans[i][j]) break;
            mex++;
        }
        sum+=mex;
    }

    cout<<sum;
}
Copy
Bitar The Handy Man YazanIstatiyeh
GNU G++17
17 ms
6.4 MB
Accepted