跳到正文

题解

题解:P15570 [USACO26FEB] Make All Distinct B

szh_AK_all约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年3月15日
收录
2026年3月16日
更新
2026年11月11日
篇幅
约 4 分钟
获赞
1
题目
P15570

版本

  1. v2当前
  2. v1

首先考虑暴力,显然可以对于每个 aia_i 看它至少要增加几个 kk 才会让该值没有出现过。

暴力代码
C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
int a[200005];
map<int, int>q;

signed main() {
	int t;
	cin >> t;
	while (t--) {
		int n, k;
		cin >> n >> k;
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		int ans = 0;
		q.clear();
		for (int i = 1; i <= n; i++) {
			if (!q[a[i]])
				q[a[i]] = 1;
			else {
				for (int j = 1;; j++) {
					if (!q[a[i] + k * j]) {
						ans += j;
						q[a[i] + k * j] = 1;
						break;
					}
				}
			}
		}
		cout << ans << "\n";
	}
}

容易发现,我们可以按照 aia_i 对 ∣k∣|k| 取模得到的结果分组,组与组之间独立。对于同一组内的所有数,若 k<0k<0,则按从大到小的顺序遍历这些数并记录最大的合法的没被使用过的值(合法指得是该值对 ∣k∣|k| 取模的结果与该组中所有数相同,并且该值比当前遍历到的数小);k>0k>0 同理。优于我们记录的合法的没被使用过的值偏移更新的次数是 O(n)O(n) 级别的,所以时间复杂度单 log⁡\log。

代码
C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
int a[200005];
map<int, int>q;
int ke[200005];

signed main() {
	int t;
	cin >> t;
	while (t--) {
		int n, k;
		cin >> n >> k;
		for (int i = 1; i <= n; i++)
			cin >> a[i];
		int ans = 0;
		for (int i = 0; i < abs(k); i++)
			ke[i] = i;
		q.clear();
		if (k > 0) {
			sort(a + 1, a + n + 1);
			for (int i = 1; i <= n; i++) {
				if (!q[a[i]])
					q[a[i]] = 1;
				else {
					int u = a[i] % abs(k);
					while (1) {
						if ((k < 0 && ke[u] > a[i]) || (k > 0 && ke[u] < a[i]) || q[ke[u]])
							ke[u] += k;
						else
							break;
					}
					q[ke[u]] = 1;
					ans += (ke[u] - a[i]) / k;
				}
			}
		} else {
			sort(a + 1, a + n + 1);
			for (int i = 0; i < abs(k); i++)
				ke[i] = (n / abs(k) + 1) * abs(k) + i;
			for (int i = n; i >= 1; i--) {
				if (!q[a[i]])
					q[a[i]] = 1;
				else {
					int u = a[i] % abs(k);
					while (1) {
						if ((k < 0 && ke[u] > a[i]) || (k > 0 && ke[u] < a[i]) || q[ke[u]])
							ke[u] += k;
						else
							break;
					}
					q[ke[u]] = 1;
					ans += (ke[u] - a[i]) / k;
				}
			}
		}
		cout << ans << "\n";
	}
}
/*
1
50 -8
22 34 22 7 10 20 36 19 16 36 26 28 46 20 31 13 25 11 44 50 6 43 46 43 29 10 37 20 43 3 40 35 31 47 48 24 23 25 20 30 37 24 39 46 35 39 7 29 23 5
*/
原文