跳到正文

题解

题解:P15570 [USACO26FEB] Make All Distinct B

Beacon_wolf约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年5月6日
更新
2026年5月6日
篇幅
约 3 分钟
题目
P15570

版本

  1. v1当前

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

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

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

  • 当 k>0k > 0 时,新产生的数只会变大,因此从小到大处理。
  • 当 k<0k < 0 时,新产生的数只会变小,因此从大到小处理。

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

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

要稍微卡一下常。

C++
#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;
}
原文