题解:P15570 [USACO26FEB] Make All Distinct B
Beacon_wolf · · 题解
注意到,如果某个数
第
根据
- 当
k > 0 时,新产生的数只会变大,因此从小到大处理。 - 当
k < 0 时,新产生的数只会变小,因此从大到小处理。
可以用 map 维护每个值的出现次数,用堆依次处理当前值即可。
特别地,当
要稍微卡一下常。
#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;
}