题解:P15570 [USACO26FEB] Make All Distinct B

· · 题解

注意到,如果某个数 a 出现 cnt 次,可以保留其中一个,其余依次变为 a + k,a + 2 \times k,\dots,a + (cnt-1)k。

第 i 个需要进行 i 次操作,因此总代价为 \sum_{i=1}^{cnt-1} i。

根据 k 的正负性分类讨论:

可以用 map 维护每个值的出现次数,用堆依次处理当前值即可。

特别地,当 k = 1 时,每次操作只能 +1,问题就可以转换为最少增加多少使数组严格递增,贪心一下就好。

要稍微卡一下常。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define endl '\n'
const int MAXN = 1000010;
ll a[MAXN];
void solve(){
    ll n,k;
    cin >> n >> k;
    unordered_map<ll,ll> mp;
    mp.reserve(n * 2);
    for(int i = 1;i <= n;i++){
        cin >> a[i];
        mp[a[i]]++;
    }
    ll ans = 0;
    if(k == 1){
        sort(a + 1,a + n + 1);
        ll next = a[1];
        for(int i = 1;i <= n;i++){
            if(a[i] >= next){
                next = a[i] + 1;
            }else{
                ans += next - a[i];
                next++;
            }
        }
    }else if(k > 0){
        priority_queue<ll,vector<ll>,greater<ll> > q;
        for(auto i:mp){
            q.push(i.first);
        }
        while(!q.empty()){
            ll now = q.top();
            q.pop();
            int cnt = mp[now];
            for(int i = 1;i < cnt;i++){
                mp[now + k * i]++;
                ans += (ll)i;
                if(mp[now + k * i] == 1) q.push(now + k * i);
            }
        }
    }else{
        priority_queue<ll> q;
        for(auto i:mp){
            q.push(i.first);
        }
        while(!q.empty()){
            ll now = q.top();
            q.pop();
            int cnt = mp[now];
            for(int i = 1;i < cnt;i++){
                mp[now + k * i]++;
                ans += (ll)i;
                if(mp[now + k * i] == 1) q.push(now + k * i);
            }
        }
    }
    cout << ans << endl;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin >> t; 
    while(t--){
        solve();
    }
    return 0;
}